shared-utils.ts 1.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041
  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. * Given an array of option arrays `[['red, 'blue'], ['small', 'large']]`, this method returns a new array
  10. * containing all the combinations of those options:
  11. *
  12. * @example
  13. * ```
  14. * generateAllCombinations([['red, 'blue'], ['small', 'large']]);
  15. * // =>
  16. * // [
  17. * // ['red', 'small'],
  18. * // ['red', 'large'],
  19. * // ['blue', 'small'],
  20. * // ['blue', 'large'],
  21. * // ]
  22. */
  23. export function generateAllCombinations<T>(
  24. optionGroups: T[][],
  25. combination: T[] = [],
  26. k: number = 0,
  27. output: T[][] = [],
  28. ): T[][] {
  29. if (k === optionGroups.length) {
  30. output.push(combination);
  31. return [];
  32. } else {
  33. // tslint:disable:prefer-for-of
  34. for (let i = 0; i < optionGroups[k].length; i++) {
  35. generateAllCombinations(optionGroups, combination.concat(optionGroups[k][i]), k + 1, output);
  36. }
  37. // tslint:enable:prefer-for-of
  38. return output;
  39. }
  40. }