CPS(Continuation-passing style):显式使用函数表示函数返回的后续操作(就是回调函数)
const add = (x, y)=> x + y;
const square = (z)=> z * z;
square(add(2,3));
// Continuation-passing style
const cps = (x,y,square) => square(x + y);
"use strict";
/**
* 普通递归
* @param num
* @returns {*}
*/
export const cps1 = (num) => {
if (num < 1) return num;
return num + cps1(num - 1);
};
/**
* cps 尾递归
* @param num
* @returns {*}
*/
export const cps2 = (num, sum = 1) => {
if (num < 1) return sum;
// cps2就是个cps风格代码
return cps2(num - 1, sum + num);
};
/**
* 递归转迭代
* @constructor
*/
const Iteration = (fn) => {
let v = 0;
// 状态管理 返回undefined 避免产生调用帧
let active = false;
const args = [];
const f = (...args2) => {
args.push(args2);
if (!active) {
active = true;
while (args.length) {
v = fn(...args.shift());
}
active = false;
return v;
}
};
return f;
};
/**
* 迭代
* @type {f}
*/
export const cps3 = Iteration((num, sum) => {
if (num < 1) return sum;
return cps3(num - 1, sum + num);
});
/**
* chrome测试
*/
// console.log(cps1(10466))
// console.log(cps2(8373))
// console.log(cps3(20000, 1))