From ce15dbf31b528a60201ac31a1d4c2759c80f0f30 Mon Sep 17 00:00:00 2001 From: Julien Fontanet Date: Fri, 26 Jun 2015 11:20:50 +0200 Subject: [PATCH] New Collection#unset(). --- packages/xo-collection/README.md | 9 ++++++ packages/xo-collection/src/collection.js | 10 +++++++ packages/xo-collection/src/collection.spec.js | 28 +++++++++++++++++++ 3 files changed, 47 insertions(+) diff --git a/packages/xo-collection/README.md b/packages/xo-collection/README.md index 50ed2bded..3659b46d9 100644 --- a/packages/xo-collection/README.md +++ b/packages/xo-collection/README.md @@ -82,6 +82,15 @@ col.remove('bar') - **Throws** `NoSuchItem` if the item is not in the collection. +**Removing an item without error** + +This is the symmetric method of `set()`: it removes the item if it +exists otherwise does nothing. + +```javascript +col.unset('bar') +``` + **Removing all items** ```javascript diff --git a/packages/xo-collection/src/collection.js b/packages/xo-collection/src/collection.js index 534ad02cc..6b312f6a6 100644 --- a/packages/xo-collection/src/collection.js +++ b/packages/xo-collection/src/collection.js @@ -144,6 +144,16 @@ export default class Collection extends EventEmitter { return this.get(key) } + unset (keyOrObjectWithId) { + const [key] = this._resolveItem(keyOrObjectWithId) + + if (this.has(key)) { + delete this._items[key] + this._size-- + this._touch('remove', key) + } + } + update (keyOrObjectWithId, valueIfKey = undefined) { const [key, value] = this._resolveItem(keyOrObjectWithId, valueIfKey) this._assertHas(key) diff --git a/packages/xo-collection/src/collection.spec.js b/packages/xo-collection/src/collection.spec.js index 8e3582665..1dc4955d7 100644 --- a/packages/xo-collection/src/collection.spec.js +++ b/packages/xo-collection/src/collection.spec.js @@ -204,6 +204,34 @@ describe('Collection', function () { }) }) + describe('#unset()', function () { + it('removes an existing item', function () { + this.col.unset('bar') + + expect(this.col.has('bar')).to.be.false() + + return eventToPromise(this.col, 'remove').then(function (removed) { + expect(removed).to.have.all.keys('bar') + expect(removed.bar).to.not.exist() + }) + }) + + it('does not throw if the item does not exists', function () { + this.col.unset('foo') + }) + + it('accepts an object with an id property', function () { + this.col.unset({id: 'bar'}) + + expect(this.col.has('bar')).to.be.false() + + return eventToPromise(this.col, 'remove').then(function (removed) { + expect(removed).to.have.all.keys('bar') + expect(removed.bar).to.not.exist() + }) + }) + }) + describe('touch()', function () { it('can be used to signal an indirect update', function () { const foo = { id: 'foo' }