New Collection#unset().

This commit is contained in:
Julien Fontanet 2015-06-26 11:20:50 +02:00
parent 7c54adec9d
commit ce15dbf31b
3 changed files with 47 additions and 0 deletions

View File

@ -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

View File

@ -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)

View File

@ -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' }