functional.js 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330
  1. /* This Source Code Form is subject to the terms of the Mozilla Public
  2. * License, v. 2.0. If a copy of the MPL was not distributed with this
  3. * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
  4. // Disclaimer: Some of the functions in this module implement APIs from
  5. // Jeremy Ashkenas's http://underscorejs.org/ library and all credits for
  6. // those goes to him.
  7. "use strict";
  8. module.metadata = {
  9. "stability": "unstable"
  10. };
  11. const { deprecateFunction } = require("../util/deprecate");
  12. const { setImmediate, setTimeout } = require("../timers");
  13. const arity = f => f.arity || f.length;
  14. const name = f => f.displayName || f.name;
  15. const derive = (f, source) => {
  16. f.displayName = name(source);
  17. f.arity = arity(source);
  18. return f;
  19. };
  20. /**
  21. * Takes variadic numeber of functions and returns composed one.
  22. * Returned function pushes `this` pseudo-variable to the head
  23. * of the passed arguments and invokes all the functions from
  24. * left to right passing same arguments to them. Composite function
  25. * returns return value of the right most funciton.
  26. */
  27. const method = (...lambdas) => {
  28. return function method(...args) {
  29. args.unshift(this);
  30. return lambdas.reduce((_, lambda) => lambda.apply(this, args),
  31. void(0));
  32. };
  33. };
  34. exports.method = method;
  35. /**
  36. * Takes a function and returns a wrapped one instead, calling which will call
  37. * original function in the next turn of event loop. This is basically utility
  38. * to do `setImmediate(function() { ... })`, with a difference that returned
  39. * function is reused, instead of creating a new one each time. This also allows
  40. * to use this functions as event listeners.
  41. */
  42. const defer = f => derive(function(...args) {
  43. setImmediate(invoke, f, args, this);
  44. }, f);
  45. exports.defer = defer;
  46. // Exporting `remit` alias as `defer` may conflict with promises.
  47. exports.remit = defer;
  48. /**
  49. * Invokes `callee` by passing `params` as an arguments and `self` as `this`
  50. * pseudo-variable. Returns value that is returned by a callee.
  51. * @param {Function} callee
  52. * Function to invoke.
  53. * @param {Array} params
  54. * Arguments to invoke function with.
  55. * @param {Object} self
  56. * Object to be passed as a `this` pseudo variable.
  57. */
  58. const invoke = (callee, params, self) => callee.apply(self, params);
  59. exports.invoke = invoke;
  60. /**
  61. * Takes a function and bind values to one or more arguments, returning a new
  62. * function of smaller arity.
  63. *
  64. * @param {Function} fn
  65. * The function to partial
  66. *
  67. * @returns The new function with binded values
  68. */
  69. const partial = (f, ...curried) => {
  70. if (typeof(f) !== "function")
  71. throw new TypeError(String(f) + " is not a function");
  72. let fn = derive(function(...args) {
  73. return f.apply(this, curried.concat(args));
  74. }, f);
  75. fn.arity = arity(f) - curried.length;
  76. return fn;
  77. };
  78. exports.partial = partial;
  79. /**
  80. * Returns function with implicit currying, which will continue currying until
  81. * expected number of argument is collected. Expected number of arguments is
  82. * determined by `fn.length`. Using this with variadic functions is stupid,
  83. * so don't do it.
  84. *
  85. * @examples
  86. *
  87. * var sum = curry(function(a, b) {
  88. * return a + b
  89. * })
  90. * console.log(sum(2, 2)) // 4
  91. * console.log(sum(2)(4)) // 6
  92. */
  93. const curry = new function() {
  94. const currier = (fn, arity, params) => {
  95. // Function either continues to curry arguments or executes function
  96. // if desired arguments have being collected.
  97. const curried = function(...input) {
  98. // Prepend all curried arguments to the given arguments.
  99. if (params) input.unshift.apply(input, params);
  100. // If expected number of arguments has being collected invoke fn,
  101. // othrewise return curried version Otherwise continue curried.
  102. return (input.length >= arity) ? fn.apply(this, input) :
  103. currier(fn, arity, input);
  104. };
  105. curried.arity = arity - (params ? params.length : 0);
  106. return curried;
  107. };
  108. return fn => currier(fn, arity(fn));
  109. };
  110. exports.curry = curry;
  111. /**
  112. * Returns the composition of a list of functions, where each function consumes
  113. * the return value of the function that follows. In math terms, composing the
  114. * functions `f()`, `g()`, and `h()` produces `f(g(h()))`.
  115. * @example
  116. *
  117. * var greet = function(name) { return "hi: " + name; };
  118. * var exclaim = function(statement) { return statement + "!"; };
  119. * var welcome = compose(exclaim, greet);
  120. *
  121. * welcome('moe'); // => 'hi: moe!'
  122. */
  123. function compose(...lambdas) {
  124. return function composed(...args) {
  125. let index = lambdas.length;
  126. while (0 <= --index)
  127. args = [lambdas[index].apply(this, args)];
  128. return args[0];
  129. };
  130. }
  131. exports.compose = compose;
  132. /*
  133. * Returns the first function passed as an argument to the second,
  134. * allowing you to adjust arguments, run code before and after, and
  135. * conditionally execute the original function.
  136. * @example
  137. *
  138. * var hello = function(name) { return "hello: " + name; };
  139. * hello = wrap(hello, function(f) {
  140. * return "before, " + f("moe") + ", after";
  141. * });
  142. *
  143. * hello(); // => 'before, hello: moe, after'
  144. */
  145. const wrap = (f, wrapper) => derive(function wrapped(...args) {
  146. return wrapper.apply(this, [f].concat(args));
  147. }, f);
  148. exports.wrap = wrap;
  149. /**
  150. * Returns the same value that is used as the argument. In math: f(x) = x
  151. */
  152. const identity = value => value;
  153. exports.identity = identity;
  154. /**
  155. * Memoizes a given function by caching the computed result. Useful for
  156. * speeding up slow-running computations. If passed an optional hashFunction,
  157. * it will be used to compute the hash key for storing the result, based on
  158. * the arguments to the original function. The default hashFunction just uses
  159. * the first argument to the memoized function as the key.
  160. */
  161. const memoize = (f, hasher) => {
  162. let memo = Object.create(null);
  163. let cache = new WeakMap();
  164. hasher = hasher || identity;
  165. return derive(function memoizer(...args) {
  166. const key = hasher.apply(this, args);
  167. const type = typeof(key);
  168. if (key && (type === "object" || type === "function")) {
  169. if (!cache.has(key))
  170. cache.set(key, f.apply(this, args));
  171. return cache.get(key);
  172. }
  173. else {
  174. if (!(key in memo))
  175. memo[key] = f.apply(this, args);
  176. return memo[key];
  177. }
  178. }, f);
  179. };
  180. exports.memoize = memoize;
  181. /**
  182. * Much like setTimeout, invokes function after wait milliseconds. If you pass
  183. * the optional arguments, they will be forwarded on to the function when it is
  184. * invoked.
  185. */
  186. const delay = function delay(f, ms, ...args) {
  187. setTimeout(() => f.apply(this, args), ms);
  188. };
  189. exports.delay = delay;
  190. /**
  191. * Creates a version of the function that can only be called one time. Repeated
  192. * calls to the modified function will have no effect, returning the value from
  193. * the original call. Useful for initialization functions, instead of having to
  194. * set a boolean flag and then check it later.
  195. */
  196. const once = f => {
  197. let ran = false, cache;
  198. return derive(function(...args) {
  199. return ran ? cache : (ran = true, cache = f.apply(this, args));
  200. }, f);
  201. };
  202. exports.once = once;
  203. // export cache as once will may be conflicting with event once a lot.
  204. exports.cache = once;
  205. // Takes a `f` function and returns a function that takes the same
  206. // arguments as `f`, has the same effects, if any, and returns the
  207. // opposite truth value.
  208. const complement = f => derive(function(...args) {
  209. return args.length < arity(f) ? complement(partial(f, ...args)) :
  210. !f.apply(this, args);
  211. }, f);
  212. exports.complement = complement;
  213. // Constructs function that returns `x` no matter what is it
  214. // invoked with.
  215. const constant = x => _ => x;
  216. exports.constant = constant;
  217. // Takes `p` predicate, `consequent` function and an optional
  218. // `alternate` function and composes function that returns
  219. // application of arguments over `consequent` if application over
  220. // `p` is `true` otherwise returns application over `alternate`.
  221. // If `alternate` is not a function returns `undefined`.
  222. const when = (p, consequent, alternate) => {
  223. if (typeof(alternate) !== "function" && alternate !== void(0))
  224. throw TypeError("alternate must be a function");
  225. if (typeof(consequent) !== "function")
  226. throw TypeError("consequent must be a function");
  227. return function(...args) {
  228. return p.apply(this, args) ?
  229. consequent.apply(this, args) :
  230. alternate && alternate.apply(this, args);
  231. };
  232. };
  233. exports.when = when;
  234. // Apply function that behaves as `apply` does in lisp:
  235. // apply(f, x, [y, z]) => f.apply(f, [x, y, z])
  236. // apply(f, x) => f.apply(f, [x])
  237. const apply = (f, ...rest) => f.apply(f, rest.concat(rest.pop()));
  238. exports.apply = apply;
  239. // Returns function identical to given `f` but with flipped order
  240. // of arguments.
  241. const flip = f => derive(function(...args) {
  242. return f.apply(this, args.reverse());
  243. }, f);
  244. exports.flip = flip;
  245. // Takes field `name` and `target` and returns value of that field.
  246. // If `target` is `null` or `undefined` it would be returned back
  247. // instead of attempt to access it's field. Function is implicitly
  248. // curried, this allows accessor function generation by calling it
  249. // with only `name` argument.
  250. const field = curry((name, target) =>
  251. // Note: Permisive `==` is intentional.
  252. target == null ? target : target[name]);
  253. exports.field = field;
  254. // Takes `.` delimited string representing `path` to a nested field
  255. // and a `target` to get it from. For convinience function is
  256. // implicitly curried, there for accessors can be created by invoking
  257. // it with just a `path` argument.
  258. const query = curry((path, target) => {
  259. const names = path.split(".");
  260. const count = names.length;
  261. let index = 0;
  262. let result = target;
  263. // Note: Permisive `!=` is intentional.
  264. while (result != null && index < count) {
  265. result = result[names[index]];
  266. index = index + 1;
  267. }
  268. return result;
  269. });
  270. exports.query = query;
  271. // Takes `Type` (constructor function) and a `value` and returns
  272. // `true` if `value` is instance of the given `Type`. Function is
  273. // implicitly curried this allows predicate generation by calling
  274. // function with just first argument.
  275. const isInstance = curry((Type, value) => value instanceof Type);
  276. exports.isInstance = isInstance;
  277. /*
  278. * Takes a funtion and returns a wrapped function that returns `this`
  279. */
  280. const chainable = f => derive(function(...args) {
  281. f.apply(this, args);
  282. return this;
  283. }, f);
  284. exports.chainable = chainable;
  285. exports.chain =
  286. deprecateFunction(chainable, "Function `chain` was renamed to `chainable`");
  287. // Functions takes `expected` and `actual` values and returns `true` if
  288. // `expected === actual`. Returns curried function if called with less then
  289. // two arguments.
  290. //
  291. // [ 1, 0, 1, 0, 1 ].map(is(1)) // => [ true, false, true, false, true ]
  292. const is = curry((expected, actual) => actual === expected);
  293. exports.is = is;
  294. const isnt = complement(is);
  295. exports.isnt = isnt;