array.ts 1.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344
  1. import clone from "lodash/clone"
  2. /**
  3. * Sorts the array based on the sort func.
  4. * NOTE: Creates a new array, if you don't need ref
  5. * to original array, use `arrayUnsafeSort` for better perf
  6. * @param sortFunc Sort function to sort against
  7. */
  8. export const arraySort =
  9. <T>(sortFunc: (a: T, b: T) => number) =>
  10. (arr: T[]) => {
  11. const newArr = clone(arr)
  12. newArr.sort(sortFunc)
  13. return newArr
  14. }
  15. /**
  16. * Sorts an array based on the sort func.
  17. * Unsafe because this sort mutates the passed array
  18. * and returns it. So use it if you do not want the
  19. * original array for better performance
  20. * @param sortFunc sort function to sort against (same as Array.sort)
  21. */
  22. export const arrayUnsafeSort =
  23. <T>(sortFunc: (a: T, b: T) => number) =>
  24. (arr: T[]) => {
  25. arr.sort(sortFunc)
  26. return arr
  27. }
  28. /**
  29. * Equivalent to `Array.prototype.flatMap`
  30. * @param mapFunc The map function
  31. * @returns
  32. */
  33. export const arrayFlatMap =
  34. <T, U>(mapFunc: (value: T, index: number, arr: T[]) => U[]) =>
  35. (arr: T[]) =>
  36. arr.flatMap(mapFunc)
  37. export const stringArrayJoin = (separator: string) => (arr: string[]) =>
  38. arr.join(separator)