Skip to content

Commit

Permalink
Add remove API
Browse files Browse the repository at this point in the history
  • Loading branch information
jridgewell committed Feb 29, 2024
1 parent 973bb8f commit 32414d8
Show file tree
Hide file tree
Showing 2 changed files with 73 additions and 1 deletion.
17 changes: 17 additions & 0 deletions src/set-array.ts
Original file line number Diff line number Diff line change
Expand Up @@ -63,3 +63,20 @@ export function pop<T extends Key>(setarr: SetArray<T>): void {
const last = array.pop()!;
indexes[last] = undefined;
}

/**
* Removes the key, if it exists in the set.
*/
export function remove<T extends Key>(setarr: SetArray<T>, 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();
}
57 changes: 56 additions & 1 deletion test/set-array.test.ts
Original file line number Diff line number Diff line change
@@ -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', () => {
Expand Down Expand Up @@ -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);
});
});
});

0 comments on commit 32414d8

Please sign in to comment.