All files / src/utils utils.ts

81.63% Statements 40/49
63.63% Branches 7/11
66.66% Functions 10/15
81.57% Lines 31/38

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 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80                  19x 45x 1440x 1440x 1440x       19x 42x 42x 42x   42x 80x 80x 42x 42x 42x       42x     19x   19x 67x     19x 34x 34x 34x     19x 34x   33x   33x   33x 34x     33x           19x                                
/**
 * data-structure-typed
 *
 * @author Tyler Zeng
 * @copyright Copyright (c) 2022 Tyler Zeng <zrwusa@gmail.com>
 * @license MIT License
 */
import type { Thunk, ToThunkFn, TrlAsyncFn, TrlFn } from '../types';
 
export const uuidV4 = function () {
  return 'xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx'.replace(/[x]/g, function (c) {
    const r = (Math.random() * 16) | 0,
      v = c == 'x' ? r : (r & 0x3) | 0x8;
    return v.toString(16);
  });
};
 
export const arrayRemove = function <T>(array: T[], predicate: (item: T, index: number, array: T[]) => boolean): T[] {
  let i = -1,
    len = array ? array.length : 0;
  const result = [];
 
  while (++i < len) {
    const value = array[i];
    if (predicate(value, i, array)) {
      result.push(value);
      Array.prototype.splice.call(array, i--, 1);
      len--;
    }
  }
 
  return result;
};
 
export const THUNK_SYMBOL = Symbol('thunk');
 
export const isThunk = (fnOrValue: any) => {
  return typeof fnOrValue === 'function' && fnOrValue.__THUNK__ === THUNK_SYMBOL;
};
 
export const toThunk = (fn: ToThunkFn): Thunk => {
  const thunk = () => fn();
  thunk.__THUNK__ = THUNK_SYMBOL;
  return thunk;
};
 
export const trampoline = (fn: TrlFn) => {
  const cont = (...args: [...Parameters<TrlFn>]) => toThunk(() => fn(...args));
 
  return Object.assign(
    (...args: [...Parameters<TrlFn>]) => {
      let result = fn(...args);
 
      while (isThunk(result) && typeof result === 'function') {
        result = result();
      }
 
      return result;
    },
    { cont }
  );
};
 
export const trampolineAsync = (fn: TrlAsyncFn) => {
  const cont = (...args: [...Parameters<TrlAsyncFn>]) => toThunk(() => fn(...args));
 
  return Object.assign(
    async (...args: [...Parameters<TrlAsyncFn>]) => {
      let result = await fn(...args);
 
      while (isThunk(result) && typeof result === 'function') {
        result = await result();
      }
 
      return result;
    },
    { cont }
  );
};