arrayUtils.ts 1.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142
  1. import type { AnyJson } from '~/types/data'
  2. export default class ArrayUtils {
  3. // Private constructor to prevent instantiation
  4. private constructor() {
  5. // This utility class is not meant to be instantiated
  6. }
  7. /**
  8. * Trie un tableau
  9. *
  10. * @param array
  11. * @param reverse
  12. */
  13. public static sort(
  14. array: Array<object | string | number>,
  15. reverse: boolean = false,
  16. ): Array<object | string | number> {
  17. return array.sort((a, b) => {
  18. return (a < b ? -1 : a > b ? 1 : 0) * (reverse ? -1 : 1)
  19. })
  20. }
  21. /**
  22. * Trie un tableau d'objets selon une propriété commune
  23. *
  24. * @param array Une array d'objets
  25. * @param property Le nom d'une propriété possédée par tous les objets
  26. * @param reverse
  27. */
  28. public static sortObjectsByProp(
  29. array: Array<AnyJson>,
  30. property: string,
  31. reverse: boolean = false,
  32. ): Array<AnyJson> {
  33. return array.sort((a: AnyJson, b: AnyJson) => {
  34. return (
  35. (a[property] < b[property] ? -1 : a[property] > b[property] ? 1 : 0) *
  36. (reverse ? -1 : 1)
  37. )
  38. })
  39. }
  40. }