From 3e7c913c44c64c7c0b3c815049ec294ca09ec287 Mon Sep 17 00:00:00 2001 From: Tom Payne Date: Wed, 6 Mar 2013 15:48:00 +0100 Subject: [PATCH] Add ol.Collection.remove --- src/ol/collection.exports | 1 + src/ol/collection.js | 16 ++++++++++++++++ test/spec/ol/collection.test.js | 29 +++++++++++++++++++++++++++++ 3 files changed, 46 insertions(+) diff --git a/src/ol/collection.exports b/src/ol/collection.exports index a22ce5d472..11b7e20c8f 100644 --- a/src/ol/collection.exports +++ b/src/ol/collection.exports @@ -6,5 +6,6 @@ @exportProperty ol.Collection.prototype.insertAt @exportProperty ol.Collection.prototype.pop @exportProperty ol.Collection.prototype.push +@exportProperty ol.Collection.prototype.remove @exportProperty ol.Collection.prototype.removeAt @exportProperty ol.Collection.prototype.setAt diff --git a/src/ol/collection.js b/src/ol/collection.js index 5c2b043020..08d3340188 100644 --- a/src/ol/collection.js +++ b/src/ol/collection.js @@ -159,6 +159,22 @@ ol.Collection.prototype.push = function(elem) { }; +/** + * Removes the first occurence of elem from the collection. + * @param {*} elem Element. + * @return {*} The removed element or undefined if elem was not found. + */ +ol.Collection.prototype.remove = function(elem) { + var i; + for (i = 0; i < this.array_.length; ++i) { + if (this.array_[i] === elem) { + return this.removeAt(i); + } + } + return undefined; +}; + + /** * @param {number} index Index. * @return {*} Value. diff --git a/test/spec/ol/collection.test.js b/test/spec/ol/collection.test.js index 6253714d43..b32b5893d9 100644 --- a/test/spec/ol/collection.test.js +++ b/test/spec/ol/collection.test.js @@ -104,6 +104,35 @@ describe('ol.collection', function() { }); }); + describe('remove', function() { + it('removes the first matching element', function() { + var collection = new ol.Collection([0, 1, 2]); + expect(collection.remove(1)).toEqual(1); + expect(collection.getArray()).toEqual([0, 2]); + expect(collection.getLength()).toEqual(2); + }); + it('fires a remove event', function() { + var collection = new ol.Collection([0, 1, 2]); + var cb = jasmine.createSpy(); + goog.events.listen(collection, ol.CollectionEventType.REMOVE, cb); + expect(collection.remove(1)).toEqual(1); + expect(cb).toHaveBeenCalled(); + expect(cb.mostRecentCall.args[0].elem).toEqual(1); + }); + it('does not remove more than one matching element', function() { + var collection = new ol.Collection([0, 1, 1, 2]); + expect(collection.remove(1)).toEqual(1); + expect(collection.getArray()).toEqual([0, 1, 2]); + expect(collection.getLength()).toEqual(3); + }); + it('returns undefined if the element is not found', function() { + var collection = new ol.Collection([0, 1, 2]); + expect(collection.remove(3)).toBeUndefined(); + expect(collection.getArray()).toEqual([0, 1, 2]); + expect(collection.getLength()).toEqual(3); + }); + }); + describe('setAt and event', function() { it('does dispatch events', function() { var collection = new ol.Collection(['a', 'b']);