Function composition

The functions of the processed data are connected like pipes, and the data is passed through the pipes to get the final result

const add1=(x) = >x+1;
const mul3=(x) = >x*3;
const div2=(x) = >x/2;
div2(mul3(add1(add(0))) / / 3;
Copy the code

This is not very readable. We could construct a compose function that takes any number of functions as arguments (the functions take only one argument), and then compose returns a function that does the following:

const operate=compose(div2,mul3,add1,add1)
operate(0)Div2 (mul3(add1(add1(0))))
Copy the code

For example, compose(f,g,h)(x) can be simplified to compose(f,g,h)(x)

To achieve the following

const add1=(x) = >x+1;
const mul3=(x) = >x*3;
const div2=(x) = >x/2;
//funcs: Stores functions to be processed in pipe order
const compose=(. funcs) = >{
	return x= >{
		if(funcs.length===0) {return x;		
		}
		if(funcs.length===1) {return func[0](x)
		}
		return func.reduceRight((result,item) = >	{
			return item(result)
		},x)
	}
}
const operate=compose(div2,mul3,add1,add1);
console.log(operate(0));/ / 3
console.log(operate()(10));/ / 10
console.log(operate(div2)(10));/ / 5
Copy the code