All files / packages/design-system/shared/utils task.js

88.88% Statements 16/18
100% Branches 2/2
92.85% Functions 13/14
100% Lines 12/12

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56                                            11x       1x       3x 3x         1x 1x                   2x 2x 2x     1x 1x 1x  
// Copyright (c) 2015-present, salesforce.com, inc. All rights reserved
// Licensed under BSD 3-Clause - see LICENSE.txt or git.io/sfdc-license
 
/**
 * Minimal lazy Task (future) monad — a local, dependency-free replacement for
 * the deprecated `data.task` package (and the `futurize` helper).
 *
 * Implements exactly the surface the build scripts use:
 *   constructor: new Task((reject, resolve) => ...)
 *   static:      Task.of
 *   instance:    map, chain, fork
 *   helper:      futurize(Task) -> (nodeStyleFn) -> (...args) -> Task
 *
 * Like data.task, a Task is LAZY: the executor does not run until `.fork()` is
 * called. `map`/`chain` build up the computation without executing it.
 */
 
class Task {
  /**
   * @param {(reject: Function, resolve: Function) => void} computation
   */
  constructor(computation) {
    this.fork = computation;
  }
 
  static of(value) {
    return new Task((_reject, resolve) => resolve(value));
  }
 
  map(fn) {
    return new Task((reject, resolve) =>
      this.fork(reject, (value) => resolve(fn(value))),
    );
  }
 
  chain(fn) {
    return new Task((reject, resolve) =>
      this.fork(reject, (value) => fn(value).fork(reject, resolve)),
    );
  }
}
 
/**
 * futurize(Task) returns a function that lifts a Node-style callback API
 * (`(...args, (err, result) => ...)`) into a function that returns a Task.
 * Mirrors the `futurize` package's default behavior.
 */
const futurize = (TaskCtor) => (fn) => (...args) =>
  new TaskCtor((reject, resolve) => {
    fn(...args, (error, result) => (error ? reject(error) : resolve(result)));
  });
 
module.exports = Task;
module.exports.default = Task;
module.exports.futurize = futurize;