shared-utils.ts 1.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748
  1. /**
  2. * Predicate with type guard, used to filter out null or undefined values
  3. * in a filter operation.
  4. */
  5. export function notNullOrUndefined<T>(val: T | undefined | null): val is T {
  6. return val !== undefined && val !== null;
  7. }
  8. /**
  9. * Used in exhaustiveness checks to assert a codepath should never be reached.
  10. */
  11. export function assertNever(value: never): never {
  12. throw new Error(`Expected never, got ${typeof value}`);
  13. }
  14. /**
  15. * Given an array of option arrays `[['red, 'blue'], ['small', 'large']]`, this method returns a new array
  16. * containing all the combinations of those options:
  17. *
  18. * @example
  19. * ```
  20. * generateAllCombinations([['red, 'blue'], ['small', 'large']]);
  21. * // =>
  22. * // [
  23. * // ['red', 'small'],
  24. * // ['red', 'large'],
  25. * // ['blue', 'small'],
  26. * // ['blue', 'large'],
  27. * // ]
  28. */
  29. export function generateAllCombinations<T>(
  30. optionGroups: T[][],
  31. combination: T[] = [],
  32. k: number = 0,
  33. output: T[][] = [],
  34. ): T[][] {
  35. if (k === optionGroups.length) {
  36. output.push(combination);
  37. return [];
  38. } else {
  39. // tslint:disable:prefer-for-of
  40. for (let i = 0; i < optionGroups[k].length; i++) {
  41. generateAllCombinations(optionGroups, combination.concat(optionGroups[k][i]), k + 1, output);
  42. }
  43. // tslint:enable:prefer-for-of
  44. return output;
  45. }
  46. }