-
-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathtest.js
116 lines (93 loc) · 2.49 KB
/
test.js
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
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
import assert from 'node:assert/strict'
import test from 'node:test'
import {arrayIterate} from './index.js'
test('arrayIterate()', async function (t) {
assert.throws(
function () {
// @ts-expect-error: missing arguments.
arrayIterate()
},
/^Error: Iterate requires that \|this\| not be undefined$/,
'should throw without `values`'
)
assert.throws(
function () {
// @ts-expect-error: incorrect arguments.
arrayIterate({})
},
/Error: Iterate requires that \|this\| has a `length`/,
'should throw without `values.length`'
)
assert.throws(
function () {
// @ts-expect-error: missing arguments.
arrayIterate([])
},
/^TypeError: `callback` must be a function$/,
'should throw without `callback`'
)
await t.test('should invoke `callback` each step', function () {
const list = [0, 1, 2]
let n = 0
arrayIterate(list, function (value, index, values) {
assert.equal(value, n)
assert.equal(index, n)
assert.equal(values, list)
assert.equal(this, undefined)
n++
})
assert.equal(n, 3)
})
await t.test('should invoke `callback` with context', function () {
const context = {tada: true}
let n = 0
arrayIterate(
[1, 2, 3],
function () {
assert.equal(this, context)
n++
},
context
)
assert.equal(n, 3)
})
await t.test('should use the given return value', function () {
let n = 0
arrayIterate([0, 1, 2], function (value, index) {
n++
assert.equal(value, index)
// Stay on position `0` ten times.
if (n <= 10) {
return 0
}
})
assert.equal(n, 13)
})
await t.test('should ignore missing values', function () {
const magicNumber = 10
/** @type {(number|undefined)[]} */
// eslint-disable-next-line unicorn/no-new-array
const list = new Array(magicNumber)
/** @type {number|undefined} */
let n
list.push(magicNumber + 1)
arrayIterate(list, function (value, index) {
assert.equal(value, magicNumber + 1)
assert.equal(index, magicNumber)
n = index
})
assert.equal(n, magicNumber)
})
await t.test('should support negative indices', function () {
let n = 0
const results = ['a', 'b', 'a', 'b', 'c', 'd']
arrayIterate(['a', 'b', 'c', 'd'], function (value) {
assert.equal(value, results[n])
n++
if (n === 2) {
return -1
}
})
assert.equal(n, results.length)
})
})