R

E

A

C

T

O

xamples 

epeat

ode

pproach

ptimize

est

{Unary Function Chainer}

The Question

Write a higher order function for chaining together a list of unary functions.  In other words, it should return a function that does a left fold on the given functions.

Example

chained([a,b,c,d])(input)

 

should yield the same result as

 

d(c(b(a(input))))

Example

function a(num){
    return num * 2; //5 * 2 = 10
}

function b(num){
    return num + 2; //10 + 2 = 12
}

function c(num){
    return num / 4; //12 / 4 = 3
}

function d(num){
    return num - 5; // 3 - 5 = -2
}

chained([a, b, c, d])(5) // returns -2
'use strict'

function chained(functions) {
    return function(x){
        return functions.reduce(function(acc, curr){
            return curr(acc); 
        }, x)
    };
}

Solution

Solution with comments:

Made with Slides.com