JavaScript Patterns 4.10 Curry
Function Application
apply() takes two parameters: the first one is an object to bind to this inside of the function, the second is an array or arguments, which then becomes the array-like arguments object available inside the function. If the first parameter is null, then this points to the global object, which is exactly what happens when you call a function that is not a method of a specific object.
// define a function
var sayHi = function(who) {
return "Hello" + ( who ? ", " + who : "") + "!";
};
// invoke a function
sayHi();
// "Hello"
sayHi('world');
// "Hello, world!"
// apply a function
sayHi.apply(null, ["hello"]);
// "Hello, hello!"
//-----------------------------------------------------------------------
var alien = {
sayHi : function(who) {
return "Hello" + ( who ? ", " + who : "") + "!";
}
};
alien.sayHi('world');
// "Hello, world!"
sayHi.apply(alien, ["humans"]);
// "Hello, humans!"
In the preceding snippet, this inside of sayHi() points to alien. In the previous example this points to the global object.
When you have a function that takes only one parameter, you can save the work of creating arrays with just one element:
// the second is more efficient, saves an array sayHi.apply(alien, ["humans"]); // "Hello, humans!" sayHi.call(alien, "humans"); // "Hello, humans!"
Partial Application
var add = function(x, y) {
return x + y;
};
// full application
add.apply(null, [5, 4]);
//
// partial application
var newadd = add.partialApply(null, [5]);
// applying an argument to the new function
newadd.apply(null, [4]);
//
Here’s no partialApply() method and functions in JavaScript don’t behave like this by default. But you can make them, because JavaScript is dynamic enough to allow this. The process of making a function understand and handle partial application is called currying.
// a curried add()
// accepts partial list of arguments
function add(x, y) {
var oldx = x, oldy = y;
if ( typeof oldy === "undefined") {// partial
return function(newy) {
return oldx + newy;
};
}
// full application
return x + y;
}
// test
typeof add(5);
// "function"
add(3)(4);
//
// create and store a new function
var add2000 = add(2000);
add2000(10);
//
General-purpose currying function
function schonfinkelize(fn) {
var slice = Array.prototype.slice, stored_args = slice.call(arguments, 1);
return function() {
var new_args = slice.call(arguments), args = stored_args.concat(new_args);
return fn.apply(null, args);
};
}
// a normal function
function add(x, y) {
return x + y;
}
// curry a function to get a new function
var newadd = schonfinkelize(add, 5);
newadd(4);
//
// another option -- call the new function directly
schonfinkelize(add, 6)(7);
//
// a normal function
function add(a, b, c, d, e) {
return a + b + c + d + e;
}
// works with any number of arguments
schonfinkelize(add, 1, 2, 3)(5, 5);
//
// two-step currying
var addOne = schonfinkelize(add, 1);
addOne(10, 10, 10, 10);
//
var addSix = schonfinkelize(addOne, 2, 3);
addSix(5, 5);
//
When to Use Currying
When you find yourself calling the same function and passing mostly the same parameters, then the function is probably a good candidate for currying. You can create a new function dynamically by partially applying a set of arguments to your function. The new function will keep the repeated parameters stored (so you don’t have to pass them every time) and will use them to pre-fill the full list of arguments that the original function expects.
References:
JavaScript Patterns - by Stoyan Stefanov (O`Reilly)
JavaScript Patterns 4.10 Curry的更多相关文章
- JavaScript Patterns 2.10 Naming Conventions
1. Capitalizing Constructors var adam = new Person(); 2. Separating Words camel case - type the word ...
- JavaScript Patterns 7.1 Singleton
7.1 Singleton The idea of the singleton pattern is to have only one instance of a specific class. Th ...
- JavaScript Patterns 6.7 Borrowing Methods
Scenario You want to use just the methods you like, without inheriting all the other methods that yo ...
- JavaScript Patterns 6.6 Mix-ins
Loop through arguments and copy every property of every object passed to the function. And the resul ...
- JavaScript Patterns 6.5 Inheritance by Copying Properties
Shallow copy pattern function extend(parent, child) { var i; child = child || {}; for (i in parent) ...
- JavaScript Patterns 6.4 Prototypal Inheritance
No classes involved; Objects inherit from other objects. Use an empty temporary constructor function ...
- JavaScript Patterns 6.3 Klass
Commonalities • There’s a convention on how to name a method, which is to be considered the construc ...
- JavaScript Patterns 6.2 Expected Outcome When Using Classical Inheritance
// the parent constructor function Parent(name) { this.name = name || 'Adam'; } // adding functional ...
- JavaScript Patterns 6.1 Classical Versus Modern Inheritance Patterns
In Java you could do something like: Person adam = new Person(); In JavaScript you would do: var ada ...
随机推荐
- 背水一战 Windows 10 (7) - 控件 UI: VisualState, VisualStateManager, 控件的默认 UI
[源码下载] 背水一战 Windows 10 (7) - 控件 UI: VisualState, VisualStateManager, 控件的默认 UI 作者:webabcd 介绍背水一战 Wind ...
- MySQL的安装与配置
首先,到http://www.mysql.com/downloads/下载MySQL的安装文件mysql-installer,双击运行安装. 然后,配置环境变量,右键单击:我的电脑->高级-&g ...
- 【Linux_Fedora_应用系列】_2_如何安装视频播放器和视频文件解码
在前面的一篇博文中,我们进行了音乐播放器的安装和解码器的安装.[Linux_Fedora_应用系列]_1_如何安装音乐播放器和mp3解码 这里我们来进行视频播放器的安装.我们还是通过yum方式安装. ...
- No.019:Remove Nth Node From End of List
问题: Given a linked list, remove the nth node from the end of list and return its head. For example, ...
- jquery多次上传同一张图片
$().reset(); wrap():$('p').wrap('div');===><div><p></p></div>; .closest() ...
- 【HTML5】<datalist>标签和<select>标签的比较
<select>标签: 注:该标签定义了下拉列表的实现 <select name = "location"> <option value = &quo ...
- 【经验之谈】前端面试知识点总结(CSS相关)——附答案
目录 二.CSS部分 1.解释一下CSS的盒子模型? 2.请你说说CSS选择器的类型有哪些,并举几个例子说明其用法? 3.请你说说CSS有什么特殊性?(优先级.计算特殊值) 4.要动态改变层中内容可以 ...
- js控住DOM实现发布微博简单效果
这段代码的效果具体是输入标题和内容,点击发布把消息发布出去,并使最新的消息始终在内容的最上面,代码为: <!DOCTYPE html> <html lang="en&quo ...
- 使用js制作一般网站首页图片轮播效果
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8&quo ...
- SharePoint 2013 列表关于大数据的测试
本文主要介绍SharePoint列表库的效率问题,一直以来以为阙值5k,超过会线性下降,需要分文件夹存放:或许这是之前版本的描述,但是2013版本通过测试,真心不是这么一回事儿. 下面,简单介绍下自己 ...