Skip to content

Commit

Permalink
add merge method for collections and arrays
Browse files Browse the repository at this point in the history
  • Loading branch information
MyMediaMagnet committed Mar 20, 2018
1 parent 52ca1b6 commit ad4f0e4
Show file tree
Hide file tree
Showing 3 changed files with 58 additions and 0 deletions.
20 changes: 20 additions & 0 deletions dist/classes/collection/Collection.js
Original file line number Diff line number Diff line change
Expand Up @@ -286,6 +286,26 @@ var Collection = function () {
return this.sum(key) / this.items.length;
}

// Get the average of all values, or all values of a given column

}, {
key: 'merge',
value: function merge(items) {
var _this2 = this;

if (items instanceof Collection) {
items.each(function (item, key) {
_this2.add(item);
});
} else {
items.forEach(function (item) {
_this2.add(item);
});
}

return this;
}

// PRIVATE METHODS
// Private: used to determine if an item should be added to list based on where query

Expand Down
15 changes: 15 additions & 0 deletions src/classes/collection/Collection.js
Original file line number Diff line number Diff line change
Expand Up @@ -211,6 +211,21 @@ class Collection {
return this.sum(key) / this.items.length
}

// Get the average of all values, or all values of a given column
merge(items) {
if(items instanceof Collection) {
items.each((item, key) => {
this.add(item)
})
} else {
items.forEach((item) => {
this.add(item)
})
}

return this
}

// PRIVATE METHODS
// Private: used to determine if an item should be added to list based on where query
_passesWhereQuery(item) {
Expand Down
23 changes: 23 additions & 0 deletions test/collection.js
Original file line number Diff line number Diff line change
Expand Up @@ -442,6 +442,29 @@ describe('#Collection', function() {

expect(collection.average('count')).to.equal(2.5)
})

it('it should be able to merge another collection', function() {
let items1 = [1, 1, 2, 4]
let collection1 = new Collection(items1)

let items2 = [99, 100]
let collection2 = new Collection(items2)

let collection = collection1.merge(collection2)

expect(collection.count()).to.equal(6)
})

it('it should be able to merge an array into the collection', function() {
let items1 = [1, 1, 2, 4]
let collection1 = new Collection(items1)

let items2 = [99, 100]

let collection = collection1.merge(items2)

expect(collection.count()).to.equal(6)
})

});

Expand Down

0 comments on commit ad4f0e4

Please sign in to comment.