JavaScript 学习札记十二 函数式编程风格
JavaScript 学习笔记十二 函数式编程风格
//Util.js function abs(x){ return x>0?x:-x;} function add(a, b){ return a+b; } function sub(a, b){ return a-b; } function mul(a, b){ return a*b; } function div(a, b){ return a/b; } function rem(a, b){ return a%b; } function inc(x){ return x + 1; } function dec(x){ return x - 1; } function equal(a, b){ return a==b; } function great(a, b){ return a>b; } function less(a, b){ return a<b; } function negative(x){ return x<0; } function positive(x){ return x>0; } function sin(x){ return Math.sin(x); } function cos(x){ return Math.cos(x); }
var logs = function (str) { document.writeln(str + "<br>"); } // n*(n-1)*(n-2)*...*3*2*1 函数式编程风格 function factorial(n){ return (function factiter(product,counter,max){ //通过一个立即运行的函数 factiter,将外部的 n 传递进去,并立即参与计算,最终返回运算结果 if( great(counter,max)){ return product; }else { return factiter(mul(counter,product),inc(counter),max); } })(1,1,n); } logs(factorial(8)) ; //下面是简写,不用那么多的函数式 function factorial(x){ return x == 0 ? 1:x * factorial(x-1); } //匿名函数,能不能进行递归操作 ----> Y-结合子 // 简单的方法来实现 Y-结合子: var fact = function(x){ return x == 0 ? 1 : x * arguments.callee(x-1); //arguments.callee 表示函数的调用者 } logs(fact(10));