aboutsummaryrefslogtreecommitdiff
path: root/src/helpers/arrayFunctions.ts
blob: 234e1358585ece43c1ba675f8c4e8cd3b930e53c (plain)
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
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
/**
 * isArrayOfType check if the array contains only the specified type
 * @param array: the array to be checked
 * @param type: the type to be checked
 * @returns true if the array contains only the specified type
 */

export function isArrayOfType(array: any[], type: string): boolean {
  return array.filter((i) => typeof i === type).length === array.length;
}

/**
 * range - returns an array of numbers from start to end
 * @param start: the start of the range
 * @param end: the end of the range
 * @param step: the step of the range
 * @returns an array of numbers from start to end
 */

export function range(
  start: number,
  end: number,
  step = 1,
  remove?: Array<number>
): Array<number> {
  // Check if start, end and step are integers
  if (
    !Number.isInteger(start) ||
    !Number.isInteger(end) ||
    !Number.isInteger(step)
  ) {
    throw new Error('range parameters must be integers');
  }
  const rangeArray: Array<number> = [];
  // Start must be less than end
  if (start > end) {
    throw new Error('starting value must be less than end value');
  }

  // Step must be greater than 0
  if (step <= 0) {
    throw new Error('step must be greater than 0');
  }

  // Generate an array from start to end
  for (let i = start; i <= end; i += step) {
    if (remove) {
      if (!remove.includes(i)) {
        rangeArray.push(i);
      }
    } else {
      rangeArray.push(i);
    }
  }
  return rangeArray;
}