Saturday, January 07, 2023

JavaScript function composition

JavaScript function composition: What’s the big deal? by James Sinclair

// We call our function c2, short for 'compose two functions together'. 
const c2 = (funcA, funcB) => x => funcA(funcB(x));


const compose = (...fns) => x0 => fns.reduceRight( (x, f) => f(x), x0 );


// We call this function 'flow' as the values flow, from left to right.
const flow = (...fns) => x0 => fns.reduce( (x, f) => f(x), x0 );


const pipe = (x0, ...fns) => fns.reduce( (x, f) => f(x), x0 );




const map = f => function*(iterable) { 
   for (let x of iterable) yield f(x); 
}; 

const filter = p => function*(iterable) { 
   for (let x of iterable) { 
       if (p(x)) yield x; 
   } 
}; 

const take = n => function*(iterable) { 
    let i = 0; 
    for (let x of iterable) { 
        if (i >= n) return; 
        yield x; 
        i++; 
    } 
}; 

const join = s => iterable => [...iterable].join(s);


No comments: