企业🤖AI Agent构建引擎,智能编排和调试,一键部署,支持私有化部署方案 广告
[TOC] ## 函数式编程 ### 异步执行 ``` const curry=function (f) { return function () { const key=arguments setTimeout(function () { console.log(f.apply(f, key)); },0) } } const echo = curry(x=>x) echo("hello") console.log("world"); //world // hello ``` ### 缓存函数执行结果 ``` const memoize =function (f) { const cache=[]; return function () { const key = JSON.stringify(arguments) if (!cache[key]){ cache[key]=f.apply(this,arguments) } return cache[key] } } const add = memoize(x=>x+x) console.log(add(1));//2 console.log(add(1));//2 ``` ## 科里化 ``` function curry(func) { return function curried(...args) { // function.length 用来获取函数的形参个数 // arguments.length 获取的是实参个数 if (args.length >= func.length) { return func.apply(this, args) } return function (...args2) { return curried.apply(this, args.concat(args2)) } } } // 示意而已 function ajax(type, url, data) { var xhr = new XMLHttpRequest(); xhr.open(type, url, true); xhr.send(data); } // 虽然 ajax 这个函数非常通用,但在重复调用的时候参数冗余 ajax('POST', 'www.test.com', "name=kevin") ajax('POST', 'www.test2.com', "name=kevin") ajax('POST', 'www.test3.com', "name=kevin") // 利用 curry var ajaxCurry = curry(ajax); // 以 POST 类型请求数据 var post = ajaxCurry('POST'); post('www.test.com', "name=kevin"); // 以 POST 类型请求来自于 www.test.com 的数据 var postFromTest = post('www.test.com'); postFromTest("name=kevin"); ```