Skip to content

Commit

Permalink
Added delete implementation
Browse files Browse the repository at this point in the history
  • Loading branch information
Andrei15193 committed Jun 24, 2024
1 parent 54e9a58 commit 5504f6d
Show file tree
Hide file tree
Showing 2 changed files with 94 additions and 1 deletion.
16 changes: 15 additions & 1 deletion src/collections/observableMap/ReadOnlyObservableMap.ts
Original file line number Diff line number Diff line change
Expand Up @@ -177,7 +177,21 @@ export class ReadOnlyObservableMap<TKey, TItem> extends ViewModel implements IRe
* @see [Map.delete](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Map/delete)
*/
protected delete(key: TKey): boolean {
throw new Error("Method not implemented.");
const removedItem = this._map.get(key);
const wasItemRemoved = this._map.delete(key);

if (wasItemRemoved) {
this._changeToken = (this._changeToken + 1) % Number.MAX_VALUE;

this._mapChangedEvent.dispatch(this, {
operation: 'delete',
addedEntries: [],
removedEntries: [[key, removedItem]]
});
this.notifyPropertiesChanged('size');
}

return wasItemRemoved;
}

/**
Expand Down
79 changes: 79 additions & 0 deletions src/collections/observableMap/tests/ObservableMap.delete.tests.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,79 @@
import { ObservableMap } from '../ObservableMap';
import { testBlankMutatingOperation, testMutatingOperation } from './common';

describe('ObservableMap.delete', (): void => {
it('deleting an item from an empty map returns false', (): void => {
testBlankMutatingOperation<number, string>({
initialState: [],

applyOperation: map => map.delete(1),

expectedResult: false
});
});

it('deleting an existing item removes it from the map and returns true', (): void => {
testMutatingOperation<number, string>({
mapOperation: 'delete',
initialState: [
[1, 'a'],
[2, 'b'],
[3, 'c']
],
changedProperties: ['size'],

applyOperation: map => map.delete(2),

expectedMap: [
[1, 'a'],
[3, 'c']
],
expectedResult: true
});
});

it('deleting an item that does not exist returns false', (): void => {
testBlankMutatingOperation<number, string>({
initialState: [
[1, 'a'],
[2, 'b'],
[3, 'c']
],

applyOperation: map => map.delete(4),

expectedResult: false
});
});

it('deleting items while iterating will break iterators', (): void => {
expect(
() => {
const observableMap = new ObservableMap<number, string>([
[1, 'a'],
[2, 'b'],
[3, 'c']
]);

for (const _ of observableMap)
observableMap.delete(2);
})
.toThrow(new Error('Map has changed while being iterated.'));
});

it('deleting item that does not exist will not break iterators', (): void => {
expect(
() => {
const observableMap = new ObservableMap<number, string>([
[1, 'a'],
[2, 'b'],
[3, 'c']
]);

for (const _ of observableMap)
observableMap.delete(4);
})
.not
.toThrow();
});
});

0 comments on commit 5504f6d

Please sign in to comment.