JSFiddle - React, Tailwind, and code Playground

by mayorovp

JavaScript

function reduceList(list /*, step1, step2, ...*/) {
    var result = [];
    var step = {
        begin: function() { return true; },
        end: function () { return result; },
        value: function (item) { return  result.push(item), true; },
    };
    for (var i=arguments.length-1; i>=1; i--)
        step = arguments[i](step);
    
    if (step.begin())
        for (var i=0; i<list.length; i++)
            if (!step.value(list[i]))
                break;
    return step.end();
}

function take(n) {
    return function takeNT(next) {
        var count = n;
        return {
            begin: function() {
                 return next.begin() && count > 0;
            },
            end: next.end,
            value: function(item) {
                 return count && next.value(item) && --count;
            },
        }
    }
}

function append(/*args*/) {
    var args = arguments;
    return function appendT(next) {
        return {
            begin: next.begin,
            value: next.value,
            end: function() {
                for (var i=0; i<args.length; i++)
                    if (!next.value(args[i]))
                        break;
                return next.end();
            },
        };
    }
}

console.log("Тест номер 1");
console.log(reduceList([1,2,3,4,5], take(3))); // [1,2,3]
console.log(reduceList([1,2,3], append(6,7))); // [1,2,3,6,7]
console.log(reduceList([1,2,3,4,5], take(3), append(6,7))); // [1,2,3] - Может, мы перепутали аргументы местами?..
console.log(reduceList([1,2,3,4,5], append(6,7), take(3))); // [1,2,3] - WTF?!

console.log("Тест номер 2");
console.log(reduceList([1,2,3,4,5], append(), take(3))); // [1,2,3]
console.log(reduceList([1,2,3,4], append(5), take(3))); // [1,2,3]
console.log(reduceList([1,2,3], append(4,5), take(3))); // [1,2,3]
console.log(reduceList([1,2], append(3,4,5), take(3))); // Uncaught TypeError: undefined is not a function - WTF?!