Twig Tag - Shuffle

Actually shuffles the content before output.

by Henry

HTML

<script src="https://cdnjs.cloudflare.com/ajax/libs/twig.js/0.8.9/twig.js"></script>

JavaScript

Twig.extend(function(Twig) {

    var state;

    // http://www.htmlblog.us/random-javascript-array
    var shuffle = function(data) {
        var j,
            temp,
            i = data.length;

        do {
            j = Math.floor(Math.random() * (i - 1));
            temp = data[i];
            data[i] = data[j];
            data[j] = temp;
        } while (--i);

        return data;
    };

    var compileShuffle = function(token) {
        token._shuffle.count += 1;
        return token;
    };

    var parseShuffle = function(token, context, chain) {
        var output;

        if (chain) {
            output = Twig.parse.apply(this, [token.output, context]);
            if (output.replace(/^\s*|\s*$/g, '').length !== 0) {
                token._shuffle.output.push(output);
            }
        }
        
        if (--token._shuffle.count <= 0) {
            output = shuffle(token._shuffle.output).join('');
        } else {
            output = '';
        }
        
        return {
            chain: chain,
            output: output
        };
    };

    Twig.exports.extendTag({
        type: 'shuffle',
        regex: /^shuffle$/,
        next: ['andshuffle', 'endshuffle'],
        open: true,
        compile: function(token) {
            state = token._shuffle = {
                output: [],
                count: 0
            };
            return compileShuffle.call(this, token);
        },
        parse: parseShuffle
    });

    Twig.exports.extendTag({
        type: 'andshuffle',
        regex: /^andshuffle$/,
        next: ['andshuffle', 'endshuffle'],
        open: false,
        compile: function(token) {
            token._shuffle = state;
            return compileShuffle.call(this, token);
        },
        parse: parseShuffle
    });

    Twig.exports.extendTag({
        type: 'endshuffle',
        regex: /^endshuffle$/,
        next: [],
        open: false,
        compile: function(token) {
            state = null;
         ...