Skip to content

Commit d1c6465

Browse files
committed
test: array.splice
1 parent 96527b0 commit d1c6465

File tree

2 files changed

+56
-18
lines changed

2 files changed

+56
-18
lines changed

src/array.js

Lines changed: 17 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -131,18 +131,28 @@ const move_comments = (
131131

132132
class CommentArray extends Array {
133133
// - deleteCount + items.length
134-
splice (begin, deleteCount, ...items) {
135-
const {length} = this
136134

137-
const ret = super.splice(begin, deleteCount, ...items)
135+
// We should avoid `splice(begin, deleteCount, ...items)`,
136+
// because `splice(0, undefined)` is not equivalent to `splice(0)`
137+
splice (...args) {
138+
const {length} = this
139+
const ret = super.splice(...args)
138140

139-
// > If deleteCount is 0 or negative, no elements are removed.
140-
// > In this case, you should specify at least one new element (see below).
141-
if (deleteCount <= 0) {
141+
// If no element removed, just skip moving comments.
142+
// This is also used as argument type checking
143+
if (!ret.length) {
142144
return ret
143145
}
144146

145-
if (deleteCount === UNDEFINED) {
147+
// JavaScript syntax is silly
148+
// eslint-disable-next-line prefer-const
149+
let [begin, deleteCount, ...items] = args
150+
151+
if (begin < 0) {
152+
begin += length
153+
}
154+
155+
if (arguments.length === 1) {
146156
deleteCount = length - begin
147157
} else {
148158
deleteCount = Math.min(length - begin, deleteCount)

test/array.test.js

Lines changed: 39 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -11,28 +11,56 @@ const a1 = `[
1111
2
1212
]`
1313

14-
const CASES = [
15-
[
16-
'splice',
17-
a1,
18-
array => array.splice(0, 1),
19-
(t, ret, str) => {
20-
t.deepEqual(ret, [0])
21-
t.is(str, `[
14+
const a2 = `[
2215
// 1
2316
1,
2417
// 2
2518
2
26-
]`)
27-
}
19+
]`
20+
21+
const CASES = [
22+
[
23+
'splice(0, 1)',
24+
a1,
25+
array => array.splice(0, 1),
26+
[0],
27+
a2
28+
],
29+
[
30+
'splice(0)',
31+
a1,
32+
array => array.splice(0),
33+
[0, 1, 2],
34+
'[]'
35+
],
36+
[
37+
'splice(- 3, 1)',
38+
a1,
39+
array => array.splice(- 3, 1),
40+
[0],
41+
a2
42+
],
43+
[
44+
'invalid: splice(0, undefined)',
45+
a1,
46+
array => array.splice(0, undefined),
47+
[],
48+
a1
2849
]
2950
]
3051

31-
CASES.forEach(([d, a, run, expect]) => {
52+
CASES.forEach(([d, a, run, e, s]) => {
3253
test(d, t => {
3354
const parsed = parse(a)
3455
const ret = run(parsed)
3556

57+
const expect = isFunction(e)
58+
? e
59+
: (tt, r, str) => {
60+
tt.deepEqual(r, e)
61+
tt.is(str, s)
62+
}
63+
3664
expect(t, [...ret], stringify(parsed, null, 2), parsed, ret)
3765
})
3866
})

0 commit comments

Comments
 (0)