From 32414d8b93fba93836e1df9860494ca37bac706b Mon Sep 17 00:00:00 2001 From: Justin Ridgewell Date: Thu, 29 Feb 2024 00:57:41 -0500 Subject: [PATCH] Add remove API --- src/set-array.ts | 17 +++++++++++++ test/set-array.test.ts | 57 +++++++++++++++++++++++++++++++++++++++++- 2 files changed, 73 insertions(+), 1 deletion(-) diff --git a/src/set-array.ts b/src/set-array.ts index 86e6cbf..c05926e 100644 --- a/src/set-array.ts +++ b/src/set-array.ts @@ -63,3 +63,20 @@ export function pop(setarr: SetArray): void { const last = array.pop()!; indexes[last] = undefined; } + +/** + * Removes the key, if it exists in the set. + */ +export function remove(setarr: SetArray, key: T): void { + const index = get(setarr, key); + if (index === undefined) return; + + const { array, _indexes: indexes } = cast(setarr); + for (let i = index + 1; i < array.length; i++) { + const k = array[i]; + array[i - 1] = k; + indexes[k]!--; + } + indexes[key] = undefined; + array.pop(); +} diff --git a/test/set-array.test.ts b/test/set-array.test.ts index f783f5e..155113d 100644 --- a/test/set-array.test.ts +++ b/test/set-array.test.ts @@ -1,4 +1,4 @@ -import { SetArray, get, put, pop } from '../src/set-array'; +import { SetArray, get, put, pop, remove } from '../src/set-array'; import { strict as assert } from 'assert'; describe('SetArray', () => { @@ -111,4 +111,59 @@ describe('SetArray', () => { assert.equal(get(array, 'foo'), 0); }); }); + + describe('remove()', () => { + it('removes item from array', () => { + const array = new SetArray(); + + put(array, 'test'); + put(array, 'foo'); + put(array, 'bar'); + + remove(array, 'foo'); + assert.deepEqual(array.array, ['test', 'bar']); + remove(array, 'bar'); + assert.deepEqual(array.array, ['test']); + remove(array, 'test'); + assert.deepEqual(array.array, []); + }); + + it('unsets the key', () => { + const array = new SetArray(); + + put(array, 'test'); + remove(array, 'test'); + assert.equal(get(array, 'test'), undefined); + }); + + it('updates indexes of following keys', () => { + const array = new SetArray(); + + put(array, 'test'); + put(array, 'foo'); + put(array, 'bar'); + + remove(array, 'foo'); + assert.equal(get(array, 'test'), 0); + assert.equal(get(array, 'bar'), 1); + }); + + it('putting afterwards writes to array at old index', () => { + const array = new SetArray(); + + put(array, 'test'); + remove(array, 'test'); + put(array, 'foo'); + assert.deepEqual(array.array, ['foo']); + }); + + it('getting after put gets old key ', () => { + const array = new SetArray(); + + put(array, 'test'); + remove(array, 'test'); + put(array, 'foo'); + assert.equal(get(array, 'foo'), 0); + }); + }); });