array.ts 1.0 KB

123456789101112131415161718192021222324252627282930
  1. /**
  2. * Shuffle.
  3. *
  4. * Return a new array containing the shuffled elements of the given array.
  5. *
  6. * The algorithm used is not the most efficient, but is effectively a one-liner
  7. * whilst being reasonably efficient. To each element we assign a random key,
  8. * then we sort by this key. Since the key is random, the sorted array will have
  9. * the original elements in a random order.
  10. */
  11. export const shuffled = <T>(xs: T[]) =>
  12. xs
  13. .map((x) => [Math.random(), x])
  14. .sort()
  15. .map(([, x]) => x) as T[];
  16. /**
  17. * Return the first non-empty string from the given list of strings.
  18. *
  19. * This function is needed because the `a ?? b` idiom doesn't do what you'd
  20. * expect when a is "". Perhaps the behaviour is wrong, perhaps the expecation
  21. * is wrong; this function papers over the differences.
  22. *
  23. * If none of the strings are non-empty, or if there are no strings in the given
  24. * array, return undefined.
  25. */
  26. export const firstNonEmpty = (ss: (string | undefined)[]) => {
  27. for (const s of ss) if (s && s.length > 0) return s;
  28. return undefined;
  29. };