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 ...
随机推荐
- 速战速决 (1) - PHP: 概述, 常量, 变量, 运算符, 表达式, 控制语句
[源码下载] 速战速决 (1) - PHP: 概述, 常量, 变量, 运算符, 表达式, 控制语句 作者:webabcd 介绍速战速决 之 PHP 概述 常量 变量 运算符 表达式 控制语句 示例1. ...
- Android使用SAX解析XML(5)
parse_handler.java文件: package com.hzhi.my_sax; import org.xml.sax.Attributes; import org.xml.sax.SAX ...
- hibernate----1-1-----两表关联属性放在另一个表里面
package com.ij34.dao; import javax.persistence.*; @Entity @Table(name="Address_inf") publi ...
- 指针,&的用法
#include "stdafx.h" #include <stdio.h> #include <string.h> int main() { ] = {, ...
- nginx和apache的比较
1.nginx的IO是非阻塞的,apache的IO是阻塞的. nginx accept一个连接以后会把它放到EPOLL的消息循环中,APACHE需要启动一个线程,当系统线程达到瓶颈以后,会阻塞网络IO ...
- MyEclipse10 中的两种FreeMarker插件的安装与配置
第一个插件是: freemarker-ide MyEclipce10.0中安装FreeMarker插件,这绝对是最简单的方法 ...
- 把GAE程序通过SSH部署到 VPS
大部分在文档上都写了, 写这篇文章的目的是发现现在appcfg.py update xxxx的时候会打开浏览器访问google请求授权(后台内建了一个本地server, 端口是8090, 授权成功后会 ...
- [js开源组件开发]tip提示组件
tip提示组件 常见的应用场景中,总是难免会遇到提示信息,比如显示不完全时需要鼠标移上去显示title,比如验证时的错误提示,比如操作按钮的辅助说明等,所以我独立出来了一个小的js组件,tip提示组件 ...
- [deviceone开发]-数据绑定示例
一.简介 这个示例详细介绍了do平台数据bind的灵活使用方式.所有UI组件都支持binddata的方式,可以绑定到do_HashData,do_ListData对象.初学者推荐. 二.效果图 三.相 ...
- asp.net C#发送邮件类
很久前写的一个简单邮件发送类分享给大家: using System; using System.Data; using System.Configuration; using System.Web; ...