JavaScript-Curry
2015-08-24 00:28
766 查看
Currying allows you to easily create custom functions by partially invoking an existing function. Here’s a simple example:
Generally, curry returns a copy of the invoking function, with its first n arguments pre-assigned with the arguments passed by the curry invocation.
The curry function does not exist in native JavaScript, but it’s easy to write your own. Here I’m augmenting function’s prototype with an implementation based on the Prototype framework. (Notice I’m also throwing in a toArray function for convenience. This is because function’s arguments property is not a true array, and we need it to work with array’s concat function)
The returned function expects to be invoked with additional argument(s) which it will concatenate with the argument(s) it got from the curry function.
var add = function(a,b) { return a + b; } var addTen = add.curry(10); //create function that returns 10 + argument addTen(20); //30
Generally, curry returns a copy of the invoking function, with its first n arguments pre-assigned with the arguments passed by the curry invocation.
The curry function does not exist in native JavaScript, but it’s easy to write your own. Here I’m augmenting function’s prototype with an implementation based on the Prototype framework. (Notice I’m also throwing in a toArray function for convenience. This is because function’s arguments property is not a true array, and we need it to work with array’s concat function)
function toArray(enum) { return Array.prototype.slice.call(enum); } Function.prototype.curry = function() { if (arguments.length<1) { return this; //nothing to curry with - return function } var __method = this; var args = toArray(arguments); return function() { return __method.apply(this, args.concat(toArray(arguments))); } }
The returned function expects to be invoked with additional argument(s) which it will concatenate with the argument(s) it got from the curry function.
A CURRY FUNCTION IN JAVASCRIPT
function curry (fn, scope) { var scope = scope || window; var args = []; for (var i=2, len = arguments.length; i < len; ++i) { args.push(arguments[i]); }; return function() { fn.apply(scope, args); }; }
Quote From:
Curry: cooking up tastier functions
JavaScript currying
相关文章推荐
- atitit.javascript js 上传文件的本地预览
- atitit.javascript js 上传文件的本地预览
- Js计算间隔天数和Date对象
- atitit.javascript js 上传文件的本地预览
- 正则表达式详解
- javascript实现支持移动设备画廊
- js实现类似MSN提示的页面效果代码分享
- 纯javascript判断查询日期是否为有效日期
- js实现的黑背景灰色二级导航菜单效果代码
- javascript中SetInterval与setTimeout的定时器用法
- js贪吃蛇网页版游戏特效代码分享(挑战十关)
- js实现的简洁网页滑动tab菜单效果代码
- js淡入淡出的图片轮播效果代码分享
- json格式化
- Seeking Front End Developer前端开发工程师(JavaScript)
- javascript中attribute与property 的区别
- 记一篇讲js的函数讲的比较好的帖子
- JSP相关图书推荐
- 【摘】【编写可维护的JavaScript】判断javascript中的类型
- JavaScript弹新窗口