Added Collection#merge()
Before adoption: this commit came in with the history the project adopted, so no landing records it.
authored by visionmedia · committed by visionmedia · parent eebf938 · Browse files · 2 files·+65 added−0 removed
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Diff stats
2 files+65 added−0 removed
- tests:+42 added−0 removed
- other:+23 added−0 removed
Provenance
- Commit
660ac65- Tree
cc43053- Author
visionmedia <tj@vision-media.ca>- Committer
visionmedia <tj@vision-media.ca>- Parent
eebf938
2 files changed+65 added−0 removed
modified:lib/express/collection.js+23 added
1 2 // Express - Collection - Copyright TJ Holowaychuk <tj@vision-media.ca> (MIT Licensed)3 4+// TODO: isArray()5+// TODO: toArray() alias values() alias vals()6+// TODO: v8 native merge?7+// TODO: benchmarks8+9 /**10 * Throw $break in order to stop iteration.11 */12 345 unmodified lines358 })359 },360 361 /**362+ * Merge _other_ with this collection.363+ *364+ * @param {mixed} other365+ * @return {Collection}366+ * @api public367+ */368+ 369+ merge: function(other) {370+ if (this.arr instanceof Array)371+ return $($(other).reduce(this.arr, function(array, val){372+ array.push(val)373+ return array374+ }))375+ else376+ return $(process.mixin(this.arr, $(other).arr))377+ },378+ 379+ /**380 * Convert collection to a string.381 *382 * @return {string}383 * @api public19 unmodified linesmodified:spec/spec.collection.js+42 added
252 unmodified lines253 $([1,2,3]).sum().should.eql 6254 end255 end256 257+ describe '#merge()'258+ it 'should merge two array collections'259+ var a = $([1,2,3])260+ var b = $([4,5,6])261+ a.merge(b).toArray().should.eql [1,2,3,4,5,6]262+ 263+ var a = $([1,2,3])264+ var b = [4,5,6]265+ a.merge(b).toArray().should.eql [1,2,3,4,5,6]266+ end267+ 268+ it 'should merge two object collections'269+ var a = $({ a: 'b' })270+ var b = $({ c: 'd' })271+ a.merge(b).arr.should.eql { a: 'b', c: 'd' }272+ 273+ var a = $({ a: 'b' })274+ var b = { c: 'd' }275+ a.merge(b).arr.should.eql { a: 'b', c: 'd' }276+ end277+ 278+ it 'should merge an array and object collection'279+ var a = $([1,2])280+ var b = $({ a: 'b', c: 'd' })281+ a.merge(b).arr.should.eql [1, 2, 'b', 'd']282+ 283+ var a = $([1,2])284+ var b = { a: 'b', c: 'd' }285+ a.merge(b).arr.should.eql [1, 2, 'b', 'd']286+ end287+ 288+ it 'should merge an object and array collection'289+ var a = $({ a: 'b', c: 'd' })290+ var b = $([1,2])291+ a.merge(b).arr.should.eql { a: 'b', c: 'd', 0: 1, 1: 2 }292+ 293+ var a = $({ a: 'b', c: 'd' })294+ var b = [1,2]295+ a.merge(b).arr.should.eql { a: 'b', c: 'd', 0: 1, 1: 2 }296+ end297+ end298+ 299 describe '#toString()'300 it 'should output [Collection ...] for array'301 $([1,2,3]).toString().should.eql '[Collection 1,2,3]'302 end12 unmodified lines