手写组合函数

function whCompose(...fns) {
	let length = fns.length;
	for (let i = 0; i < length; i++) {
		if (typeof fns[i] !== 'function') {
			throw new TypeError('Expected params are functions');
		}
	}

	return function com(...params) {
		let index = 0;
		let result = length ? fns[index].apply(this, params) : params;
		while (++index < length) {
			result = fns[index].apply(this, [result]);
		}
		return result;
	};
}

function double(n) {
	return n * 2;
}

function square(m) {
	return m ** 2;
}

let fn = whCompose(double, square);
console.log(fn(1));

posted @ 2021-11-19 08:54  Wayhome'  阅读(32)  评论(0编辑  收藏  举报
// 侧边栏目录 // https://blog-static.cnblogs.com/files/douzujun/marvin.nav.my1502.css