From 49a6320fef5c4a8695cf6e70725c7f4c8139bacf Mon Sep 17 00:00:00 2001 From: Chris Wanstrath Date: Sat, 8 Nov 2025 11:17:45 -0800 Subject: [PATCH] add list.insert --- src/prelude/list.ts | 10 +++++++++- src/prelude/tests/prelude.test.ts | 16 ++++++++++++++++ 2 files changed, 25 insertions(+), 1 deletion(-) diff --git a/src/prelude/list.ts b/src/prelude/list.ts index 8e861b9..0c7d7be 100644 --- a/src/prelude/list.ts +++ b/src/prelude/list.ts @@ -73,6 +73,13 @@ export const list = { const realItems = items.map(item => item.value) 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 reverse: (list: any[]) => list.slice().reverse(), @@ -142,4 +149,5 @@ export const list = { ; (list.push as any).raw = true ; (list.pop as any).raw = true ; (list.shift as any).raw = true - ; (list.unshift as any).raw = true \ No newline at end of file + ; (list.unshift as any).raw = true + ; (list.insert as any).raw = true \ No newline at end of file diff --git a/src/prelude/tests/prelude.test.ts b/src/prelude/tests/prelude.test.ts index 86341d3..27bb919 100644 --- a/src/prelude/tests/prelude.test.ts +++ b/src/prelude/tests/prelude.test.ts @@ -349,6 +349,22 @@ describe('collections', () => { 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 () => { await expect(`list.sort [3 1 4 1 5] null`).toEvaluateTo([1, 1, 3, 4, 5]) })