All files / src/func func.ts

75.71% Statements 53/70
70% Branches 21/30
79.16% Functions 19/24
75.36% Lines 52/69

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 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465                                                                          20x 163x 7x 7x   163x 2x       163x 159x 159x       163x 2x 2x                                                               1x                             3x                                                               3x     3x 3x 3x     3x 5x   5x 1x 4x     4x       3x   3x                                                                                                                                                                                                   2x 2x     2x 24x 24x 15x   9x 9x                                                                                                       1x   1x 10x   10x 8x   2x 2x 2x                                 2x 2x                                                                                                                                           2x 2x   2x 7x   7x 2x   2x                                     4x                                            
import * as time from '../time/time';
 
/**
 *  A basic debounce implementation.  Debounce will basically wait X amount
 * of seconds to execute AFTER it's last call.
 *
 * ```ts
 *
 * const debouncer = func.debounce((windowEvent)=> {
 *   console.log(wiindowEvent);
 * }, 500);
 *
 * // Now when you resize, it will wait 500 ms until the last resize call.
 * window.addEventListener('resize', debounce);
 *
 * Or
 *
 * window.addEventListener('resize', func.debounce(()=> {
 *   console.log('throttled');
 * }, 500))
 *
 * ```
 *
 * @param callback The function to call.
 * @param wait The ms to delay.
 * @param immediate Optional, whether to immediately run (changes this to throttle)
 * @return A debounced function
 * @tested
 */
export function debounce(
  callback: Function,
  wait: number,
  immediate?: boolean
): () => void {
  let timeOutId: undefined | number;
 
  // eslint-disable-next-line @typescript-eslint/no-explicit-any
  return function (this: any, ...args: any[]) {
    const runLater = () => {
      timeOutId = undefined;
      callback.apply(this, args);
    };
    const throttler = () => {
      timeOutId = undefined;
    };
 
    // Debouncing should reset the timer if it is called again.
    if (!immediate) {
      clearTimeout(timeOutId);
      timeOutId = +setTimeout(runLater, wait);
    }
 
    // For throttling where we call on leading trail (immediate).
    if (immediate && timeOutId === undefined) {
      callback.apply(this, args);
      timeOutId = +setTimeout(throttler, wait);
    }
  };
}
 
/**
 * Throttles a function.  Throttle will run a function immediately when it's
 * called and wait X amount of seconds before it can be called again.
 *
 * ```ts
 *
 * const throttler = func.throttle((windowEvent)=> {
 *   console.log(wiindowEvent);
 * }, 500);
 *
 * // Now when you resize, it will immediately call the throttle function
 * // and wait 500 ms before it can be called again.
 * window.addEventListener('resize', throttler);
 *
 * Or just:
 *
 * window.addEventListener('resize', func.throttle(()=> {
 *   console.log('throttled');
 * }, 500))
 *
 * ```
 *
 * @param callback The callback function
 * @param wait The amount to wait in ms.
 * @tested
 */
export function throttle(callback: Function, wait: number): () => void {
  return debounce(callback, wait, true);
}
 
/**
 * A simple function that resolves after a specific amoutn of time.
 * This is useful to create a delay with await.
 * ```ts
 * console.log('hohoho');
 * await func.wait(500);
 * console.log('hohoho after 500ms');
 * ```
 * @param time
 * @tested
 */
export async function wait(time: number): Promise<void> {
  return new Promise<void>((resolve) => setTimeout(resolve, time));
}
 
/**
 * Wait until a condition becomes truthy.   This under the hood implements
 * polling to evaluate the condition so use wisely.
 *
 * ```ts
 *
 * let someValue = 0;
 * func.waitUntil(()=> someValue === 5).then(()=> {
 *   console.log('some value is 5!!!');
 * })
 *
 * setTimeout(()=> {
 *   someValue = 5;
 * }, 1000);
 *
 * ```
 *
 *
 * @param {Function} A condition that returns a boolean.
 * @param {number} The amount of time that can elapse before rejecting the
 *     returning promise. Defaults to 0, which is evaluated as forever.
 * @param {number} The polling interval amount.
 * @tested
 */
export function waitUntil(
  condition: Function,
  timeout = 0,
  interval = 100
): Promise<void> {
  const startTime = time.now();
  let resolvePromise: Function;
  let rejectPromise: Function;
  const returnPromise = new Promise<void>((resolve, reject) => {
    resolvePromise = resolve;
    rejectPromise = reject;
  });
 
  const evaluateCondition = () => {
    const elapsed = time.timeDiffMs(startTime, time.now());
    // If the condition resolves.
    if (condition()) {
      resolvePromise();
    } else Iif (timeout && elapsed > timeout) {
      rejectPromise('Wait until timed out');
    } else {
      setTimeout(evaluateCondition, interval);
    }
  };
  // Start it up.
  evaluateCondition();
 
  return returnPromise;
}
 
/**
 * Similar to waitUntil but will repeatedly perform an
 * action until a condition is met.
 * @param condition
 * @param action
 * @param timeout
 * @param interval
 *
 *
 * ```
 * let someValue = 0;
 * func.repeatUntil(
 *  ()=> {return someValue === 5},
 *  ()=> { somevalue++; }
 * ).then(()=> {
 *   console.log('some value is 5!!!');
 * })
 * ```
 */
export function repeatUntil(
  condition: Function,
  // The action that should be performed
  action: Function,
  timeout = 0,
  interval = 100
): Promise<void> {
  const startTime = time.now();
  let resolvePromise: Function;
  let rejectPromise: Function;
  const returnPromise = new Promise<void>((resolve, reject) => {
    resolvePromise = resolve;
    rejectPromise = reject;
  });
 
  const evaluateCondition = () => {
    const elapsed = time.timeDiffMs(startTime, time.now());
    // If the condition resolves.
    if (condition()) {
      resolvePromise();
    } else if (timeout && elapsed > timeout) {
      rejectPromise('Wait until timed out');
    } else {
      action();
      setTimeout(evaluateCondition, interval);
    }
  };
  // Start it up.
  evaluateCondition();
 
  return returnPromise;
}
 
/**
 * Memoizes a function with just a one time memory.   This memoize
 * conserves RAM (probably :))
 *
 * If the same parameter is passed as the last execution, the results are
 * pulled from the cache.  When paramers change, the callback is reevaluated
 * for new results.
 *
 * The key difference between [[func.memoize]] is that this memoize stores
 * just the last results as opposed to a dictionary of all previous results.
 *
 * If running a lot of executions, this can save memory.
 *
 * Consider the following example.  The calculations are done only when
 * a mutation occurs in the parameters.  Otherwise, the results are
 * pull from the single cache.
 *
 * ```ts
 * let expensiveCalculation = func.memoizeSimple((a,b,c)=> {
 *   return a + b + c;
 * })
 *
 * expensiveCalculation(1, 1, 1); // 3, callback executed and results cached.
 * expensiveCalculation(1, 1, 1); // 3 from cache
 * expensiveCalculation(1, 1, 1); // 3 from cache
 * expensiveCalculation(1, 1, 1); // 3 from cache
 *
 * expensiveCalculation(2, 2, 2); // 6, callback executed and results cached.
 * expensiveCalculation(2, 2, 2); // 6 from cache
 *
 * // Now in a classic memozize the below would not be reexecuted. But since
 * // this memoize only has a simple memory, it will be reexecuted.
 * expensiveCalculation(1, 1, 1); // 3, callback executed and results cached.
 * expensiveCalculation(1, 1, 1); // 3 from cache
 *
 * ```
 * @param {Function} callback The function to wrap the memoize mechanism.
 *     It's expect that this function returns something.  Can't be void.
 * @return {Function}
 * @tested
 */
export function memoizeSimple(callback: Function): Function {
  // eslint-disable-next-line @typescript-eslint/no-explicit-any
  let cachedResults: any = null;
  let cachedArgs: string | null = null;
 
  // eslint-disable-next-line @typescript-eslint/no-explicit-any
  return (...args: any[]) => {
    const stringifiedArgs = JSON.stringify(args);
    if (stringifiedArgs === cachedArgs) {
      return cachedResults;
    } else {
      cachedArgs = stringifiedArgs;
      return (cachedResults = callback(...args));
    }
  };
}
 
/**
 * Memoizes a function.  If the params passed to the function are the same
 * as a previous call, then the cached results are returned, saving an
 * unncessary excecution.
 *
 *
 * Consider the follwing example
 * ```ts
 * let expensiveCalculation = func.memoize((a,b,c)=> {
 *   return a + b + c;
 * })
 *
 * expensiveCalculation(1, 1, 1); // 3, callback executed and results cached.
 * expensiveCalculation(1, 1, 1); // 3 from cache
 * expensiveCalculation(1, 1, 1); // 3 from cache
 *
 * expensiveCalculation(2, 2, 2); // 6, callback executed and results cached.
 * expensiveCalculation(2, 2, 2); // 6 from cache
 *
 * expensiveCalculation(1, 1, 1); // 3 from cache
 * expensiveCalculation(2, 2, 2); // 6 from cache
 * ```
 *
 * A common case for memoize might be to use it in a class method.
 * You can implement that with this pattern.
 *
 * ```ts
 * class MyClass {
 *
 *     constructor() {
 *        this.calculate = func.memoize(this.calculate.bind(this)) as any;
 *     }
 *
 *     calculate(a, b) {
 *       return a + b;
 *     }
 * }
 *
 * ```
 *
 * @param {Function} callback The function to wrap the memoize mechanism.
 *     It's expect that this function returns something.  Can't be void.
 * @return {Function}
 * @tested
 */
export function memoize(callback: Function): Function {
  // eslint-disable-next-line @typescript-eslint/no-explicit-any
  const cachedResults: Record<string, any> = {};
  // eslint-disable-next-line @typescript-eslint/no-explicit-any
  return (...args: any[]) => {
    const stringifiedArgs = JSON.stringify(args);
 
    if (cachedResults[stringifiedArgs]) {
      return cachedResults[stringifiedArgs];
    }
    const result = callback(...args);
    cachedResults[stringifiedArgs] = result;
    return result;
  };
}
 
/**
 * A function that only ever runs once even if it is called multiple times.
 * ```
 * let hello = func.runOnlyOnce(()=> {
 *    console.log('hello');
 * })
 *
 * hello() // hello
 * hello() // cull
 * hello() // cull
 * * ```
 */
export function runOnlyOnce(callback: Function): Function {
  return runOnceOnChange(() => {
    callback();
  });
}
 
/**
 * Runs a function ONLY when the parameters have changed.
 *
 *
 * Running the below, you will see only four console.logs executed, each
 * when the params have changed.
 * ```ts
 *
 *   let expensiveOperation = func.runOnceOnChange(
 *       (name) => {
 *           // Do expensive stuff here.
 *           console.log(name);
 *       }
 *   );
 *
 *   expensiveOperation('Scott');  // Scott
 *   expensiveOperation('Scott');
 *   expensiveOperation('Scott');
 *   expensiveOperation('Scott');
 *   expensiveOperation('Scott');
 *   expensiveOperation('John');   // John
 *   expensiveOperation('John');
 *   expensiveOperation('Aya');    // Aya
 *   expensiveOperation('Aya');
 *   expensiveOperation('John');   // John
 *   expensiveOperation('John');
 * ```
 *
 * More in practice.  Here we want to do mutate only when the window.innerWidth
 * or windowHeight has changed.
 * ```ts
 * let updateCanvasSize = func.runOnceOnChange(
 *    (windowWidth, windowHeight)=> {
 *       // Do something expensive.
 *       console.log('Change the canvas size');
 * })
 *
 * new Raf(()=> {
 *   updateCanvasSize(window.innnerWidth, window.innerHeight);
 * });
 * ```
 *
 * You can implement this for a class method as follows
 * ```ts
 * class MyClass {
 *
 *     constructor() {
 *        this.element = document.getElementById('hello');
 *        this.render = func.runOnceOnChange(this.render.bind(this));
 *
 *        this.render(800);
 *        this.render(800); // Won't be called a second time.
 *     }
 *
 *     render(height) {
 *       this.element.style.height = height + 'px';
 *     }
 * }
 *
 * ```
 * @param {Function} callback The callback to execute.  Doesn't require
 *     the callback to return a value.
 * @tested
 */
export function runOnceOnChange(callback: Function) {
  // eslint-disable-next-line @typescript-eslint/no-explicit-any
  let cachedResults: any = null;
  let cachedArgs: string | null = null;
  // eslint-disable-next-line @typescript-eslint/no-explicit-any
  return (...args: any[]) => {
    const stringifiedArgs = JSON.stringify(args);
    // Only excute if arguments are different.
    if (stringifiedArgs !== cachedArgs) {
      cachedArgs = stringifiedArgs;
      // eslint-disable-next-line
      return (cachedResults = callback(...args));
    }
  };
}
 
/**
 * A method that sets the default value if undefined.
 * Useful in setting explicit default values.
 *
 * ```ts
 *
 * func.setDefault(10, 20); // 10
 * func.setDefault(undefined, 20); // 20
 * func.setDefault(undefined, false); // false
 * ```
 * @tested
 */
// eslint-disable-next-line @typescript-eslint/no-explicit-any
export function setDefault(value: any, defaultValue: any) {
  return Object.is(value, undefined) ? defaultValue : value;
}
 
/**
 * Run the callback a specific number of times.
 *
 * ```ts
 *
 *  // Runs 5 times.
 *  func.times(5, (i) => {
 *       console.log('times', i);
 *  });
 *
 * ```
 * @param count
 * @param callback
 */
export function times(count: number, callback: Function) {
  [...Array(count)].forEach((x, i) => {
    callback(i);
  });
}