mozilla

Revision 509081 of lang/functional

  • Revision slug: Mozilla/Add-ons/SDK/Low-Level_APIs/lang_functional
  • Revision title: lang/functional
  • Revision id: 509081
  • Created:
  • Creator: wbamberg
  • Is current revision? No
  • Comment

Revision Content

Unstable

Functional helper methods.

Usage

The lang/functional module provides functional helper methods. Some of these functions implement APIs from Jeremy Ashkenas's underscore.js and all credits go to him and his contributors.

Globals

Functions

method(lambda)

Takes a function and returns a method associated with an object. When the method is invoked on an instance of the object, the original function is called. It is passed the object instance (i.e. this) as the first parameter, followed by any parameters passed into the method.

let { method } = require("sdk/lang/functional");
let myNumber = {
  times: method(times),
  add: method(add),
  number: 0
};

function times (target, x) {
  return target.number *= x;
}
function add (target, x) {
  return target.number += x;
}

console.log(myNumber.number); // 0
myNumber.add(10); // 10
myNumber.times(2); // 20
myNumber.add(3); // 23
Parameters

lambda : function
The function to be wrapped and returned.

Returns

function : The wrapped lambda.

defer(fn)

Takes a function and returns a wrapped version of the function. Calling the wrapped version will call the original function during the next event loop. This is similar to calling setTimeout with no wait (i.e. setTimeout(function () { ... }, 0)), except that the wrapped function may be reused and does not need to be repeated each time. This also enables you to use these functions as event listeners.

let { defer } = require("sdk/lang/functional");
let fn = defer(function myEvent (event, value) {
  console.log(event + " : " + value);
});

fn("click", "#home");
console.log("done");

// This will print 'done' before 'click : #home' since
// we deferred the execution of the wrapped `myEvent`
// function, making it non-blocking and executing on the
// next event loop
Parameters

fn : function
The function to be deferred.

Returns

function : The new, deferred function.

remit()

An alias for defer.

invoke(callee, params, self)

Invokes callee, passing params as an argument and self as this. Returns the value that is returned by callee.

let { invoke } = require("sdk/lang/functional");

invoke(sum, [1,2,3,4,5], null); // 15

function sum () {
  return Array.slice(arguments).reduce(function (a, b) {
    return a + b;
  });
}
Parameters

callee : function
Function to invoke.

params : Array
Parameters to be passed into callee.

self : mixed
Object to be passed as the this context to callee.

Returns

mixed : Returns the return value of callee.

partial(fn, arguments...)

Takes a function and bind values to one or more arguments, returning a new function of smaller arity.

let { partial } = require("sdk/lang/functional");
let add = function add (x, y) { return x + y; }
let addOne = partial(add, 1);

addOne(5); // 6
addOne(10); // 11
partial(add, addOne(20))(2); // 23
Parameters

fn : function
Function on which partial application is to be performed.

arguments... : mixed
Additional arguments

Returns

function : The partial function.

compose(fn...)

Returns the composition of a list of functions, where each function consumes the return value of the function that follows. In math terms, composing the functions f(), g(), and h() produces f(g(h())).

let { compose } = require("sdk/lang/functional");

let welcome = compose(exclaim, greet);

welcome('moe'); // "hi: moe!";

function greet (name) { return "hi: " + name; }
function exclaim (statement) { return statement + "!"; }
Parameters

fn... : function
Takes a variable number of functions as arguments and composes them from right to left.

Returns

function : The composed function.

wrap(fn, wrapper)

Returns the first function passed as an argument to the second, allowing you to adjust arguments, run code before and after, and conditionally execute the original function.

let { wrap } = require("sdk/lang/functional");

let wrappedHello = wrap(hello, function (fn, name) {
  return "before, " + fn(name) + "after";
});

wrappedHello("moe"); // "before, hello: moe, after"

function hello (name) { return "hello: " + name; }
Parameters

fn : function
The function to be passed into the wrapper function.

wrapper : function
The function that is called when the return function is executed, taking the wrapped fn as the first parameter.

Returns

function : A function which, when called, executes wrapper with fn as the first parameter, and passes in any additional parameters to the wrapper function.

identity(value)

Returns the same value that is used as the argument. In math: f(x) = x.

let { identity } = require("sdk/lang/functional");
let x = 5;
identity(x); // 5
Parameters

value : mixed
The value to be returned.

Returns

mixed : The value that was originally passed in.

memoize(fn, hasher)

Memoizes a given function by caching the computed result. Useful for speeding up slow-running computations. If passed an optional hashFunction, it will be used to compute the hash key for storing the result, based on the arguments to the original function. The default hashFunction just uses the first argument to the memoized function as the key.

let { memoize } = require("sdk/lang/functional");

let memoizedFn = memoize(primeFactorization);

memoizedFn(50); // Returns [2, 5, 5], had to compute
memoizedFn(100); // Returns [2, 2, 5, 5], had to compute
memoizedFn(50); // Returns [2, 5, 5] again, but pulled from cache

function primeFactorization (x) {
  // Some tricky stuff
}

// We can also use a hash function to compute a different
// hash value. In this example, we'll fabricate a function
// that takes a string of first and last names that
// somehow computes the lineage of that name. Our hash
// function will just parse the last name, as our naive
// implementation assumes that they will share the same lineage

let getLineage = memoize(function (name) {
  // computes lineage
  return data;
}, hasher);

// Hashing function takes a string of first and last name
// and returns the last name.
function hasher (input) {
  return input.split(" ")[1];
}

getLineage("homer simpson"); // Computes and returns information for "simpson"
getLineage("lisa simpson"); // Returns cached for "simpson"
Parameters

fn : function
The function that becomes memoized.

hasher : function
An optional function that takes the memoized function's parameter and returns a hash key for storing the result.

Returns

function : The memoized version of fn.

delay(fn, ms, arguments)

Much like setTimeout, delay invokes a function after waiting a set number of milliseconds. If you pass additional, optional, arguments, they will be forwarded on to the function when it is invoked.

let { delay } = require("sdk/lang/functional");

delay(printAdd, 2000, 5, 10);

// Prints "5+10=15" in two seconds (2000ms)
function printAdd (a, b) { console.log(a + "+" + b + "=" + (a+b)); }
Parameters

fn : function
A function to be delayed.

ms : number
Number of milliseconds to delay the execution of fn.

arguments : mixed
Additional arguments to pass to fn upon execution

once(fn)

Creates a version of the input function that can only be called one time. Repeated calls to the modified function will have no effect, returning the value from the original call. Useful for initialization functions, instead of having to set a boolean flag and checking it later.

let { once } = require("sdk/lang/functional");
let setup = once(function (env) {
  // initializing important things
  console.log("successfully initialized " + env);
  return 1; // Assume success and return 1
});

setup('dev'); // returns 1
// prints "successfully initialized dev"

// Future attempts to call this function just return the cached
// value that was returned previously
setup('production'); // Returns 1
// No print message is displayed since the function isn't executed
Parameters

fn : function
The function that will be executed only once inside the once wrapper.

Returns

function : The wrapped fn that can only be executed once.

chain(fn)

Creates a version of the input function that will return this.

let { chain } = require("sdk/lang/functional");

function Person (age) { this.age = age; }
Person.prototype.happyBirthday = chain(function () this.age++);

let person = new Person(30);

person
  .happyBirthday()
  .happyBirthday()
  .happyBirthday()

console.log(person.age); // 33
Parameters

fn : function
The function that will be wrapped by the chain function.

Returns

function : The wrapped function that executes fn and returns this.

cache()

An alias for once.

Revision Source

<div class="note">
 <p>Unstable</p>
</div>
<p><span class="seoSummary">Functional helper methods.</span></p>
<h2 id="Usage">Usage</h2>
<p>The <code>lang/functional</code> module provides functional helper methods. Some of these functions implement APIs from Jeremy Ashkenas's <a href="http://underscorejs.org">underscore.js</a> and all credits go to him and his contributors.</p>
<h2 id="Globals">Globals</h2>
<h3 id="Functions">Functions</h3>
<h4 class="addon-sdk-api-name" id="method(lambda)"><code>method(lambda)</code></h4>
<p>Takes a function and returns a method associated with an object. When the method is invoked on an instance of the object, the original function is called. It is passed the object instance (i.e. <code>this</code>) as the first parameter, followed by any parameters passed into the method.</p>
<pre class="brush: js">
<code>let { method } = require("sdk/lang/functional");</code>
<code>let myNumber = {
  times: method(times),
  add: method(add),
  number: 0
};

function times (target, x) {
  return target.number *= x;
}
function add (target, x) {
  return target.number += x;
}

console.log(myNumber.number); // 0
myNumber.add(10); // 10
myNumber.times(2); // 20
myNumber.add(3); // 23</code></pre>
<h5 id="Parameters">Parameters</h5>
<p><strong>lambda : function</strong><br />
 The function to be wrapped and returned.</p>
<h5 id="Returns">Returns</h5>
<p><strong>function</strong> : The wrapped <code>lambda</code>.</p>
<h4 class="addon-sdk-api-name" id="defer(fn)"><code>defer(fn)</code></h4>
<p>Takes a function and returns a wrapped version of the function. Calling the wrapped version will call the original function during the next event loop. This is similar to calling <a href="/en-US/Add-ons/SDK/High-Level_APIs/timers#setTimeout(callback%2C_ms)">setTimeout</a> with no wait (i.e. <code>setTimeout(function () { ... }, 0)</code>), except that the wrapped function may be reused and does not need to be repeated each time. This also enables you to use these functions as event listeners.</p>
<pre class="brush: js">
<code>let { defer } = require("sdk/lang/functional");
let fn = defer(function myEvent (event, value) {
  console.log(event + " : " + value);
});</code>

<code>fn("click", "#home");
console.log("done");</code>

<code>// This will print 'done' before 'click : #home' since
// we deferred the execution of the wrapped `myEvent`
// function, making it non-blocking and executing on the
// next event loop</code></pre>
<h5 id="Parameters">Parameters</h5>
<p><strong>fn : function</strong><br />
 The function to be deferred.</p>
<h5 id="Returns">Returns</h5>
<p><strong>function</strong> : The new, deferred function.</p>
<h4 class="addon-sdk-api-name" id="remit()"><code>remit()</code></h4>
<p>An alias for <a href="#defer(fn)">defer</a>.</p>
<h4 class="addon-sdk-api-name" id="invoke(callee.2C_params.2C_self)"><code>invoke(callee, params, self)</code></h4>
<p>Invokes <code>callee</code>, passing <code>params</code> as an argument and <code>self</code> as <code>this</code>. Returns the value that is returned by <code>callee</code>.</p>
<pre class="brush: js">
<code>let { invoke } = require("sdk/lang/functional");</code>

<code>invoke(sum, [1,2,3,4,5], null); // 15</code>

<code>function sum () {
  return Array.slice(arguments).reduce(function (a, b) {
    return a + b;
  });
}</code></pre>
<h5 id="Parameters">Parameters</h5>
<p><strong>callee : function</strong><br />
 Function to invoke.</p>
<p><strong>params : Array</strong><br />
 Parameters to be passed into <code>callee</code>.</p>
<p><strong>self : mixed</strong><br />
 Object to be passed as the <code>this</code> context to <code>callee</code>.</p>
<h5 id="Returns">Returns</h5>
<p><strong>mixed</strong> : Returns the return value of <code>callee</code>.</p>
<h4 class="addon-sdk-api-name" id="partial(fn.2C_arguments...)"><code>partial(fn, arguments...)</code></h4>
<p>Takes a function and bind values to one or more arguments, returning a new function of smaller arity.</p>
<pre class="brush: js">
<code>let { partial } = require("sdk/lang/functional");
let add = function add (x, y) { return x + y; }
let addOne = partial(add, 1);</code>

<code>addOne(5); // 6
addOne(10); // 11
partial(add, addOne(20))(2); // 23</code></pre>
<h5 id="Parameters">Parameters</h5>
<p><strong>fn : function</strong><br />
 Function on which partial application is to be performed.</p>
<p><strong>arguments... : mixed</strong><br />
 Additional arguments</p>
<h5 id="Returns">Returns</h5>
<p><strong>function</strong> : The partial function.</p>
<h4 class="addon-sdk-api-name" id="compose(fn...)"><code>compose(fn...)</code></h4>
<p>Returns the <a href="http://en.wikipedia.org/wiki/Function_composition_(computer_science)">composition</a> of a list of functions, where each function consumes the return value of the function that follows. In math terms, composing the functions <code>f()</code>, <code>g()</code>, and <code>h()</code> produces <code>f(g(h()))</code>.</p>
<pre class="brush: js">
<code>let { compose } = require("sdk/lang/functional");</code>

<code>let welcome = compose(exclaim, greet);</code>

<code>welcome('moe'); // "hi: moe!";</code>

<code>function greet (name) { return "hi: " + name; }
function exclaim (statement) { return statement + "!"; }</code></pre>
<h5 id="Parameters">Parameters</h5>
<p><strong>fn... : function</strong><br />
 Takes a variable number of functions as arguments and composes them from right to left.</p>
<h5 id="Returns">Returns</h5>
<p><strong>function</strong> : The composed function.</p>
<h4 class="addon-sdk-api-name" id="wrap(fn.2C_wrapper)"><code>wrap(fn, wrapper)</code></h4>
<p>Returns the first function passed as an argument to the second, allowing you to adjust arguments, run code before and after, and conditionally execute the original function.</p>
<pre class="brush: js">
<code>let { wrap } = require("sdk/lang/functional");</code>

<code>let wrappedHello = wrap(hello, function (fn, name) {
  return "before, " + fn(name) + "after";
});</code>

<code>wrappedHello("moe"); // "before, hello: moe, after"</code>

<code>function hello (name) { return "hello: " + name; }</code></pre>
<h5 id="Parameters">Parameters</h5>
<p><strong>fn : function</strong><br />
 The function to be passed into the <code>wrapper</code> function.</p>
<p><strong>wrapper : function</strong><br />
 The function that is called when the return function is executed, taking the wrapped <code>fn</code> as the first parameter.</p>
<h5 id="Returns">Returns</h5>
<p><strong>function</strong> : A function which, when called, executes <code>wrapper</code> with <code>fn</code> as the first parameter, and passes in any additional parameters to the <code>wrapper</code> function.</p>
<h4 class="addon-sdk-api-name" id="identity(value)"><code>identity(value)</code></h4>
<p>Returns the same value that is used as the argument. In math: f(x) = x.</p>
<pre class="brush: js">
<code>let { identity } = require("sdk/lang/functional");</code><code>
let x = 5;
identity(x); // 5</code></pre>
<h5 id="Parameters">Parameters</h5>
<p><strong>value : mixed</strong><br />
 The value to be returned.</p>
<h5 id="Returns">Returns</h5>
<p><strong>mixed</strong> : The value that was originally passed in.</p>
<h4 class="addon-sdk-api-name" id="memoize(fn.2C_hasher)"><code>memoize(fn, hasher)</code></h4>
<p><a href="http://en.wikipedia.org/wiki/Memoization">Memoizes</a> a given function by caching the computed result. Useful for speeding up slow-running computations. If passed an optional <code>hashFunction</code>, it will be used to compute the hash key for storing the result, based on the arguments to the original function. The default <code>hashFunction</code> just uses the first argument to the memoized function as the key.</p>
<pre class="brush: js">
<code>let { memoize } = require("sdk/lang/functional");</code>

<code>let memoizedFn = memoize(primeFactorization);</code>

<code>memoizedFn(50); // Returns [2, 5, 5], had to compute
memoizedFn(100); // Returns [2, 2, 5, 5], had to compute
memoizedFn(50); // Returns [2, 5, 5] again, but pulled from cache</code>

<code>function primeFactorization (x) {
  // Some tricky stuff
}</code>

<code>// We can also use a hash function to compute a different
// hash value. In this example, we'll fabricate a function
// that takes a string of first and last names that
// somehow computes the lineage of that name. Our hash
// function will just parse the last name, as our naive
// implementation assumes that they will share the same lineage</code>

<code>let getLineage = memoize(function (name) {
  // computes lineage
  return data;
}, hasher);</code>

<code>// Hashing function takes a string of first and last name
// and returns the last name.
function hasher (input) {
  return input.split(" ")[1];
}</code>

<code>getLineage("homer simpson"); // Computes and returns information for "simpson"
getLineage("lisa simpson"); // Returns cached for "simpson"</code></pre>
<h5 id="Parameters">Parameters</h5>
<p><strong>fn : function</strong><br />
 The function that becomes memoized.</p>
<p><strong>hasher : function</strong><br />
 An optional function that takes the memoized function's parameter and returns a hash key for storing the result.</p>
<h5 id="Returns">Returns</h5>
<p><strong>function</strong> : The memoized version of <code>fn</code>.</p>
<h4 class="addon-sdk-api-name" id="delay(fn.2C_ms.2C_arguments)"><code>delay(fn, ms, arguments)</code></h4>
<p>Much like <code>setTimeout</code>, <code>delay</code> invokes a function after waiting a set number of milliseconds. If you pass additional, optional, arguments, they will be forwarded on to the function when it is invoked.</p>
<pre class="brush: js">
<code>let { delay } = require("sdk/lang/functional");</code>

<code>delay(printAdd, 2000, 5, 10);</code>

<code class="brush: js">// Prints "5+10=15" in two seconds (2000ms)
function printAdd (a, b) { console.log(a + "+" + b + "=" + (a+b)); }</code></pre>
<h5 id="Parameters">Parameters</h5>
<p><strong>fn : function</strong><br />
 A function to be delayed.</p>
<p><strong>ms : number</strong><br />
 Number of milliseconds to delay the execution of <code>fn</code>.</p>
<p><strong>arguments : mixed</strong><br />
 Additional arguments to pass to <code>fn</code> upon execution</p>
<h4 class="addon-sdk-api-name" id="once(fn)"><code>once(fn)</code></h4>
<p>Creates a version of the input function that can only be called one time. Repeated calls to the modified function will have no effect, returning the value from the original call. Useful for initialization functions, instead of having to set a boolean flag and checking it later.</p>
<pre class="brush: js">
<code class="brush: js">let { once } = require("sdk/lang/functional");</code><code class="brush: js">
let setup = once(function (env) {
  // initializing important things
  console.log("successfully initialized " + env);
  return 1; // Assume success and return 1
});</code>

<code>setup('dev'); // returns 1
// prints "successfully initialized dev"</code>

<code>// Future attempts to call this function just return the cached
// value that was returned previously
setup('production'); // Returns 1
// No print message is displayed since the function isn't executed</code></pre>
<h5 id="Parameters">Parameters</h5>
<p><strong>fn : function</strong><br />
 The function that will be executed only once inside the once wrapper.</p>
<h5 id="Returns">Returns</h5>
<p><strong>function</strong> : The wrapped <code>fn</code> that can only be executed once.</p>
<h4 class="addon-sdk-api-name" id="chain(fn)"><code>chain(fn)</code></h4>
<p>Creates a version of the input function that will return <code>this</code>.</p>
<pre class="brush: js">
<code>let { chain } = require("sdk/lang/functional");</code>

<code>function Person (age) { this.age = age; }
Person.prototype.happyBirthday = chain(function () this.age++);</code>

<code>let person = new Person(30);</code>

<code>person
  .happyBirthday()
  .happyBirthday()
  .happyBirthday()</code>

<code>console.log(person.age); // 33</code></pre>
<h5 id="Parameters">Parameters</h5>
<p><strong>fn : function</strong><br />
 The function that will be wrapped by the chain function.</p>
<h5 id="Returns">Returns</h5>
<p><strong>function</strong> : The wrapped function that executes <code>fn</code> and returns <code>this</code>.</p>
<h4 class="addon-sdk-api-name" id="cache()"><code>cache()</code></h4>
<p>An alias for <a href="#once(fn)">once</a>.</p>
Revert to this revision