• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1// Copyright (C) 2023 The Android Open Source Project
2//
3// Licensed under the Apache License, Version 2.0 (the "License");
4// you may not use this file except in compliance with the License.
5// You may obtain a copy of the License at
6//
7//      http://www.apache.org/licenses/LICENSE-2.0
8//
9// Unless required by applicable law or agreed to in writing, software
10// distributed under the License is distributed on an "AS IS" BASIS,
11// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12// See the License for the specific language governing permissions and
13// limitations under the License.
14
15import {
16  allUnique,
17  arrayEquals,
18  removeFalsyValues,
19  range,
20  moveArrayItem,
21} from './array_utils';
22
23describe('range', () => {
24  it('returns array of elements in range [0; n)', () => {
25    expect(range(3)).toEqual([0, 1, 2]);
26    expect(range(5)).toEqual([0, 1, 2, 3, 4]);
27  });
28
29  it('returns empty array on n = 0', () => {
30    expect(range(0)).toEqual([]);
31  });
32
33  it('throws an error on negative input', () => {
34    expect(() => {
35      range(-10);
36    }).toThrowError();
37  });
38});
39
40describe('allUnique', () => {
41  it('returns true on array with unique elements', () => {
42    expect(allUnique(['a', 'b', 'c'])).toBeTruthy();
43  });
44
45  it('returns false on array with repeated elements', () => {
46    expect(allUnique(['a', 'a', 'b'])).toBeFalsy();
47  });
48
49  // Couple of corner cases
50  it('returns true on an empty array', () => {
51    expect(allUnique([])).toBeTruthy();
52  });
53
54  it('returns true on an array with one element', () => {
55    expect(allUnique(['test'])).toBeTruthy();
56  });
57});
58
59describe('arrayEquals', () => {
60  it('returns true when two arrays are the same', () => {
61    expect(arrayEquals(['a', 'b', 'c'], ['a', 'b', 'c'])).toBeTruthy();
62  });
63
64  it('returns false when two arrays differ', () => {
65    expect(arrayEquals(['a', 'b', 'c'], ['a', 'c', 'b'])).toBeFalsy();
66  });
67
68  it('returns false when arrays have differing lengths', () => {
69    expect(arrayEquals(['a', 'b', 'c'], ['a'])).toBeFalsy();
70  });
71});
72
73test('removeFalsyValues', () => {
74  const input = [
75    'a',
76    false,
77    undefined,
78    null,
79    '',
80    123,
81    123n,
82    true,
83    {foo: 'bar'},
84  ];
85  const expected = ['a', 123, 123n, true, {foo: 'bar'}];
86  expect(removeFalsyValues(input)).toEqual(expected);
87});
88
89test('moveArrayItem.moveForward', () => {
90  const input = range(3);
91  moveArrayItem(input, 0, 2);
92  expect(input).toEqual([1, 0, 2]);
93});
94
95test('moveArrayItem.moveBackward', () => {
96  const input = range(3);
97  moveArrayItem(input, 2, 0);
98  expect(input).toEqual([2, 0, 1]);
99});
100