1//Util.js 2function abs(x){ return x>0?x:-x;} 3function add(a, b){ return a+b; } 4function sub(a, b){ return a-b; } 5function mul(a, b){ return a*b; } 6function div(a, b){ return a/b; } 7function rem(a, b){ return a%b; } 8function inc(x){ return x + 1; } 9function dec(x){ return x - 1; } 10function equal(a, b){ return a==b; } 11function great(a, b){ return a>b; } 12function less(a, b){ return a<b; } 13function negative(x){ return x<0; } 14function positive(x){ return x>0; } 15function sin(x){ return Math.sin(x); } 16function cos(x){ return Math.cos(x); } 17 18var logs = function (str) { 19 document.writeln(str + "<br>"); 20 } 21 22 // n*(n-1)*(n-2)*...*3*2*1 函数式编程风格 23 function factorial(n){ 24 return (function factiter(product,counter,max){ 25 //通过一个立即运行的函数 factiter,将外部的 n 传递进去,并立即参与计算,最终返回运算结果 26 if( great(counter,max)){ 27 return product; 28 }else { 29 return factiter(mul(counter,product),inc(counter),max); 30 } 31 })(1,1,n); 32 } 33 logs(factorial(8)) ; 34 //下面是简写,不用那么多的函数式 35 function factorial(x){ 36 return x == 0 ? 1:x * factorial(x-1); 37 } 38 39 //匿名函数,能不能进行递归操作 ----> Y-结合子 40 // 简单的方法来实现 Y-结合子: 41 var fact = function(x){ 42 return x == 0 ? 1 : x * arguments.callee(x-1); //arguments.callee 表示函数的调用者 43 } 44 logs(fact(10));
JavaScript 学习笔记十二 函数式编程风格
Stella981
2021-10-11
982 0 0
点赞
收藏
评论区
加载中...