Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript functional programming quiz

Here is the problem. I have to implement make function:

var sum = function (a, b) { return a + b; }
var mult = function (a, b) { return a * b; }

//'make' function goes here

var res = make(1)(2)(3)(4);

console.log(res(sum));    //OUTPUT: 10
console.log(res(mult));   //OUTPUT: 24

I have implemented it, but I feel like a little better way still exists. :)

So, here is my solution:

function make(a, arr) {
    if (a instanceof Function) { return arr.reduce(a); }

    arr = arr || [];
    arr.push(a);

    return function (b) { return make(b, arr); };
}
like image 498
Andrei Avatar asked Jun 22 '26 14:06

Andrei


1 Answers

You want functions? You can have functions!

function sum(a, b) { return a + b; }
function mult(a, b) { return a * b; }
function diff(a, b) { return a - b; }

function make(x, f) {
    if (typeof x === 'function') return f(x);
    return function(y) { 
        return make(y, function(a) { 
            return f ? a(f(a), x) : x; 
        });
    };
}

console.log(make(1)(2)(3)(4)(sum));   // -> 10
console.log(make(1)(2)(3)(4)(mult));  // -> 24
console.log(make(4)(3)(2)(1)(diff));  // -> -2

Instead of building up an array, this builds up a function that, when given a function, reduces all the elements using that function, from left to right :)

I'm pretty sure this wouldn't qualify as code that anyone would ever want to see in their codebase.

like image 84
Niklas B. Avatar answered Jun 24 '26 08:06

Niklas B.



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!