aboutsummaryrefslogtreecommitdiffhomepage
path: root/shared/core-utils/common/array.ts
blob: 878ed1ffe8d5fab806215409eb03f82a9535e1ad (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
function findCommonElement <T> (array1: T[], array2: T[]) {
  for (const a of array1) {
    for (const b of array2) {
      if (a === b) return a
    }
  }

  return null
}

// Avoid conflict with other toArray() functions
function arrayify <T> (element: T | T[]) {
  if (Array.isArray(element)) return element

  return [ element ]
}

// Avoid conflict with other uniq() functions
function uniqify <T> (elements: T[]) {
  return Array.from(new Set(elements))
}

// Thanks: https://stackoverflow.com/a/12646864
function shuffle <T> (elements: T[]) {
  const shuffled = [ ...elements ]

  for (let i = shuffled.length - 1; i > 0; i--) {
    const j = Math.floor(Math.random() * (i + 1));

    [ shuffled[i], shuffled[j] ] = [ shuffled[j], shuffled[i] ]
  }

  return shuffled
}

export {
  uniqify,
  findCommonElement,
  shuffle,
  arrayify
}