add list.insert

This commit is contained in:
Chris Wanstrath 2025-11-08 11:17:45 -08:00
parent 7da437212d
commit 49a6320fef
2 changed files with 25 additions and 1 deletions

View File

@ -73,6 +73,13 @@ export const list = {
const realItems = items.map(item => item.value) const realItems = items.map(item => item.value)
return toValue(realList.splice(realStart, realDeleteCount, ...realItems)) return toValue(realList.splice(realStart, realDeleteCount, ...realItems))
}, },
insert: (list: Value, index: Value, item: Value) => {
if (list.type !== 'array') return toNull()
const realList = list.value as any[]
const realIndex = index.value as number
realList.splice(realIndex, 0, item)
return toValue(realList.length)
},
// sequence operations // sequence operations
reverse: (list: any[]) => list.slice().reverse(), reverse: (list: any[]) => list.slice().reverse(),
@ -142,4 +149,5 @@ export const list = {
; (list.push as any).raw = true ; (list.push as any).raw = true
; (list.pop as any).raw = true ; (list.pop as any).raw = true
; (list.shift as any).raw = true ; (list.shift as any).raw = true
; (list.unshift as any).raw = true ; (list.unshift as any).raw = true
; (list.insert as any).raw = true

View File

@ -349,6 +349,22 @@ describe('collections', () => {
await expect(`arr = [1 2 3 4 5]; list.splice arr 3 2; arr`).toEvaluateTo([1, 2, 3]) await expect(`arr = [1 2 3 4 5]; list.splice arr 3 2; arr`).toEvaluateTo([1, 2, 3])
}) })
test('list.insert adds element at index and mutates array', async () => {
await expect(`arr = [1 2 4 5]; list.insert arr 2 3; arr`).toEvaluateTo([1, 2, 3, 4, 5])
})
test('list.insert returns array length', async () => {
await expect(`list.insert [1 2 4] 2 3`).toEvaluateTo(4)
})
test('list.insert at start', async () => {
await expect(`arr = [2 3]; list.insert arr 0 1; arr`).toEvaluateTo([1, 2, 3])
})
test('list.insert at end', async () => {
await expect(`arr = [1 2]; list.insert arr 2 99; arr`).toEvaluateTo([1, 2, 99])
})
test('list.sort with no callback sorts ascending', async () => { test('list.sort with no callback sorts ascending', async () => {
await expect(`list.sort [3 1 4 1 5] null`).toEvaluateTo([1, 1, 3, 4, 5]) await expect(`list.sort [3 1 4 1 5] null`).toEvaluateTo([1, 1, 3, 4, 5])
}) })