Tags:JavaScript

Category: Front End

Pipe function in JavaScript

  • sometimes we need to pass a parameter to serveral function in a specific order,
    get the final return value.

  • My first thought of this problem is using simple nested function to finish.

function one(x) {
    return x + 1;
}

function two(x) {
    return x * 2;
}

// implement a pipe function that use the parameter to pass function one and two as sequence and get the final value

// my way
function pipe(val) {
    return two(one(value))
}
  • This way actually works, but in real practice the the number of the sequence is unknown, so a better way which I learn.
// Use ES6 Array.reduce to spread all functions in the pipe and return the value to next function

const square = x => x * x;
const double = x => x * 2;
const pipe = (...sequence) => x => {
    return sequence.reduce((prevSeq,currSeq)=> currSeq(prevSeq),x);
}

pipe(square,double)(3) // 18