Skip to content

Commit

Permalink
Add some() and every() methods for Collection (#216)
Browse files Browse the repository at this point in the history
  • Loading branch information
baopham authored and fkling committed Mar 7, 2018
1 parent 99aaae5 commit aada675
Show file tree
Hide file tree
Showing 2 changed files with 64 additions and 0 deletions.
24 changes: 24 additions & 0 deletions src/Collection.js
Original file line number Diff line number Diff line change
Expand Up @@ -78,6 +78,30 @@ class Collection {
return this;
}

/**
* Tests whether at-least one path passes the test implemented by the provided callback.
*
* @param {function} callback
* @return {boolean}
*/
some(callback) {
return this.__paths.some(
(path, i, paths) => callback.call(path, path, i, paths)
);
}

/**
* Tests whether all paths pass the test implemented by the provided callback.
*
* @param {function} callback
* @return {boolean}
*/
every(callback) {
return this.__paths.every(
(path, i, paths) => callback.call(path, path, i, paths)
);
}

/**
* Executes the callback for every path in the collection and returns a new
* collection from the return values (which must be paths).
Expand Down
40 changes: 40 additions & 0 deletions src/__tests__/Collection-test.js
Original file line number Diff line number Diff line change
Expand Up @@ -234,6 +234,46 @@ describe('Collection API', function() {
});
});

describe('some', function() {
it('lets you test each element of a collection and stops when one passes the test', function() {
const each = jest.genMockFunction().mockImplementation(() => true);
Collection.fromNodes(nodes).some(each);

expect(each.mock.calls.length).toBe(1);
expect(each.mock.calls[0][0].value).toBe(nodes[0]);
});

it('returns true if at least one element passes the test', function() {
const result = Collection.fromNodes(nodes).some((_, i) => i === 1);
expect(result).toBe(true);
});

it('returns false if no elements pass the test', function() {
const result = Collection.fromNodes(nodes).some(() => false);
expect(result).toBe(false);
});
});

describe('every', function() {
it('lets you test each element of a collection and stops when one fails the test', function() {
const each = jest.genMockFunction().mockImplementation(() => false);
Collection.fromNodes(nodes).every(each);

expect(each.mock.calls.length).toBe(1);
expect(each.mock.calls[0][0].value).toBe(nodes[0]);
});

it('returns true if all elements pass the test', function() {
const result = Collection.fromNodes(nodes).every(() => true);
expect(result).toBe(true);
});

it('returns false if at least one element does not pass the test', function() {
const result = Collection.fromNodes(nodes).every((_, i) => i === 1);
expect(result).toBe(false);
});
});

describe('map', function() {
it('returns a new collection with mapped values', function() {
const root = Collection.fromNodes(nodes);
Expand Down

0 comments on commit aada675

Please sign in to comment.