Skip to content

Commit

Permalink
Add arethusaUtil.inject
Browse files Browse the repository at this point in the history
  • Loading branch information
LFDM committed May 8, 2014
1 parent 618cadd commit 0d019d9
Show file tree
Hide file tree
Showing 2 changed files with 29 additions and 0 deletions.
9 changes: 9 additions & 0 deletions app/js/arethusa_util.js
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,15 @@ var arethusaUtil = {
return result;
},

// inject like ruby - or more like each_with_object
// Take care - will not work with immutable memos!
inject: function(memo, container, fn){
container.forEach(function(el) {
fn(memo, el);
});
return memo;
},

// flat push
pushAll: function(target, pusher) {
target.push.apply(target, pusher);
Expand Down
20 changes: 20 additions & 0 deletions spec/arethusa_util_spec.js
Original file line number Diff line number Diff line change
Expand Up @@ -35,6 +35,26 @@ describe("arethusaUtil", function() {
});
});

describe('inject', function() {
it('works like a ruby each_with_object', function() {
var coll = [1, 2, 3];
var fn = function(memo, el) {
memo.push(el + 1);
};
var res = [2, 3, 4];
expect(arethusaUtil.inject([], coll, fn)).toEqual(res);
});

it("will not work with immutable objects", function() {
var coll = [1, 2, 3];
var fn = function(memo, el) {
memo += el;
};
expect(arethusaUtil.inject(0, coll, fn)).toEqual(0);
expect(arethusaUtil.inject(0, coll, fn)).not.toEqual(6);
});
});

describe('pushAll', function() {
it('flat-pushes all elements of an array into another', function() {
var arr1 = [1, 2];
Expand Down

0 comments on commit 0d019d9

Please sign in to comment.