• Skip to main content
  • Select language
  • Skip to search
MDN Web Docs
  • Technologies
    • HTML
    • CSS
    • JavaScript
    • Graphics
    • HTTP
    • APIs / DOM
    • WebExtensions
    • MathML
  • References & Guides
    • Learn web development
    • Tutorials
    • References
    • Developer Guides
    • Accessibility
    • Game development
    • ...more docs
Add-ons
  1. MDN
  2. Mozilla
  3. Add-ons
  4. Add-on SDK
  5. Low-Level APIs
  6. lang/functional

lang/functional

In This Article
  1. Usage
  2. Globals
    1. Functions
      1. method(lambda)
      2. defer(fn)
      3. remit()
      4. invoke(callee, params, self)
      5. partial(fn, arguments...)
      6. compose(fn...)
      7. wrap(fn, wrapper)
      8. identity(value)
      9. memoize(fn, hasher)
      10. delay(fn, ms, arguments)
      11. once(fn)
      12. chain(fn)
      13. cache()
      14. debounce(fn, wait)
      15. throttle(fn, wait, options)

Add-ons using the techniques described in this document are considered a legacy technology in Firefox. Don't use these techniques to develop new add-ons. Use WebExtensions instead. If you maintain an add-on which uses the techniques described here, consider migrating it to use WebExtensions.

From Firefox 53 onwards, no new legacy add-ons will be accepted on addons.mozilla.org (AMO).

From Firefox 57 onwards, WebExtensions will be the only supported extension type, and Firefox will not load other types.

Even before Firefox 57, changes coming up in the Firefox platform will break many legacy extensions. These changes include multiprocess Firefox (e10s), sandboxing, and multiple content processes. Legacy extensions that are affected by these changes should migrate to WebExtensions if they can. See the "Compatibility Milestones" document for more.

A wiki page containing resources, migration paths, office hours, and more, is available to help developers transition to the new technologies.

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.

debounce(fn, wait)

This function is new in Firefox 30.

From Underscore's debounce() function: this takes a function and returns a new version of the function which, when invoked, will not be executed until it has not been invoked for wait milliseconds. This means that if the function's called many times in quick succession the function will only execute once, after the blizzard of calls has finished. This could be useful, for example, if we are checking the user's keyboard input, and want to wait until they've paused in their typing before we do so.

Parameters

fn : function
The function to debounce.

wait : integer
The number of milliseconds to wait before the function is executed.

Returns

function : The debounced version of fn.

throttle(fn, wait, options)

This function is new in Firefox 30.

From Underscore's throttle() function: this takes a function and returns a new version of the function which, when invoked repeatedly, will not excute the function more than once per wait milliseconds.

Parameters

fn : function
The function to debounce.

wait : integer
The number of milliseconds to wait before the function is executed.

options : object
By default the function is called as soon as it is invoked (the leading edge of the wait period), and at the end of wait (the trailing edge of the wait period). Pass {leading : false} to stop the function being called at the leading edge, and {trailing : false} to stop it being called at the trailing edge.

Returns

function : The throttled version of fn.

Document Tags and Contributors

 Contributors to this page: wbamberg, stoyanster, jsantell
 Last updated by: wbamberg, Dec 1, 2016, 10:29:28 AM
See also
  1. WebExtensions
  2. Getting started
    1. What are WebExtensions?
    2. Your first WebExtension
    3. Your second WebExtension
    4. Anatomy of a WebExtension
    5. Example WebExtensions
  3. How to
    1. Intercept HTTP requests
    2. Modify a web page
    3. Add a button to the toolbar
    4. Implement a settings page
  4. Concepts
    1. Using the JavaScript APIs
    2. User interface components
    3. Content scripts
    4. Match patterns
    5. Internationalization
    6. Content Security Policy
    7. Native messaging
  5. Porting
    1. Porting a Google Chrome extension
    2. Porting a legacy Firefox add-on
    3. Embedded WebExtensions
    4. Comparison with the Add-on SDK
    5. Comparison with XUL/XPCOM extensions
    6. Chrome incompatibilities
  6. Firefox workflow
    1. Temporary Installation in Firefox
    2. Debugging
    3. Getting started with web-ext
    4. web-ext command reference
    5. WebExtensions and the Add-on ID
    6. Publishing your WebExtension
  7. JavaScript APIs
    1. Browser support for JavaScript APIs
    2. alarms
    3. bookmarks
    4. browserAction
    5. browsingData
    6. commands
    7. contextMenus
    8. contextualIdentities
    9. cookies
    10. downloads
    11. events
    12. extension
    13. extensionTypes
    14. history
    15. i18n
    16. identity
    17. idle
    18. management
    19. notifications
    20. omnibox
    21. pageAction
    22. runtime
    23. sessions
    24. sidebarAction
    25. storage
    26. tabs
    27. topSites
    28. webNavigation
    29. webRequest
    30. windows
  8. Manifest keys
    1. applications
    2. author
    3. background
    4. browser_action
    5. chrome_url_overrides
    6. commands
    7. content_scripts
    8. content_security_policy
    9. default_locale
    10. description
    11. developer
    12. homepage_url
    13. icons
    14. manifest_version
    15. name
    16. omnibox
    17. options_ui
    18. page_action
    19. permissions
    20. short_name
    21. sidebar_action
    22. version
    23. web_accessible_resources
  9. Add-on SDK
  10. Getting started
    1. Installation
    2. Getting started
    3. Troubleshooting
  11. High-Level APIs
    1. addon-page
    2. base64
    3. clipboard
    4. context-menu
    5. hotkeys
    6. indexed-db
    7. l10n
    8. notifications
    9. page-mod
    10. page-worker
    11. panel
    12. passwords
    13. private-browsing
    14. querystring
    15. request
    16. selection
    17. self
    18. simple-prefs
    19. simple-storage
    20. system
    21. tabs
    22. timers
    23. ui
    24. url
    25. webextension
    26. widget
    27. windows
  12. Low-Level APIs
    1. /loader
    2. chrome
    3. console/plain-text
    4. console/traceback
    5. content/content
    6. content/loader
    7. content/mod
    8. content/symbiont
    9. content/worker
    10. core/heritage
    11. core/namespace
    12. core/promise
    13. dev/panel
    14. event/core
    15. event/target
    16. frame/hidden-frame
    17. frame/utils
    18. fs/path
    19. io/byte-streams
    20. io/file
    21. io/text-streams
    22. lang/functional
    23. lang/type
    24. loader/cuddlefish
    25. loader/sandbox
    26. net/url
    27. net/xhr
    28. places/bookmarks
    29. places/favicon
    30. places/history
    31. platform/xpcom
    32. preferences/event-target
    33. preferences/service
    34. remote/child
    35. remote/parent
    36. stylesheet/style
    37. stylesheet/utils
    38. system/child_process
    39. system/environment
    40. system/events
    41. system/runtime
    42. system/unload
    43. system/xul-app
    44. tabs/utils
    45. test/assert
    46. test/harness
    47. test/httpd
    48. test/runner
    49. test/utils
    50. ui/button/action
    51. ui/button/toggle
    52. ui/frame
    53. ui/id
    54. ui/sidebar
    55. ui/toolbar
    56. util/array
    57. util/collection
    58. util/deprecate
    59. util/list
    60. util/match-pattern
    61. util/object
    62. util/uuid
    63. window/utils
  13. Firefox for Android
  14. Getting started
    1. Walkthrough
    2. Debugging
    3. Code snippets
  15. APIs
    1. Accounts.jsm
    2. BrowserApp
    3. HelperApps.jsm
    4. Home.jsm
    5. HomeProvider.jsm
    6. JavaAddonManager.jsm
    7. NativeWindow
    8. Notifications.jsm
    9. PageActions.jsm
    10. Prompt.jsm
    11. RuntimePermissions.jsm
    12. Snackbars.jsm
    13. Sound.jsm
    14. Tab
  16. Legacy
  17. Restartless extensions
    1. Overview
  18. Overlay extensions
    1. Overview
  19. Themes
  20. Lightweight themes
    1. Overview
  21. Complete themes
    1. Overview
  22. Publishing add-ons
  23. Guides
    1. Signing and distribution overview
    2. Submit an add-on
    3. Review policies
    4. Developer agreement
    5. Featured add-ons
    6. Contact addons.mozilla.org
  24. Community and support
  25. Channels
    1. Add-ons blog
    2. Add-on forums
    3. Stack Overflow
    4. Development newsgroup
    5. IRC Channel