Skip to content

Commit

Permalink
[ADD] partition
Browse files Browse the repository at this point in the history
  • Loading branch information
HubCodes committed Sep 13, 2018
1 parent a205adb commit 457ec30
Show file tree
Hide file tree
Showing 3 changed files with 39 additions and 0 deletions.
2 changes: 2 additions & 0 deletions index.js
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ const foldLeft = require('./foldLeft');
const foldRight = require('./foldRight');
const map = require('./map');
const partialFunction = require('./partialFunction');
const partition = require('./partition');
const zip = require('./zip');

module.exports = {
Expand All @@ -15,5 +16,6 @@ module.exports = {
foldRight,
map,
partialFunction,
partition,
zip,
};
12 changes: 12 additions & 0 deletions partition/index.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
module.exports = function partition(iterable, predicator) {
const left = [];
const right = [];
for (const element of iterable) {
if (predicator(element)) {
left.push(element);
} else {
right.push(element);
}
}
return [left, right];
};
25 changes: 25 additions & 0 deletions test/partition.test.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
const assert = require('assert');
const $ = require('../');

describe('partition test', () => {
let iterable = [1, 2, 3, 4, 5, 6, 7, 8];
it('work with array', () => {
const array = Array.from(iterable);
const result = $.partition(array, (x) => x % 2 == 0);
assert.deepEqual(result, [[2, 4, 6, 8], [1, 3, 5, 7]]);
});
it('work with Set', () => {
const set = new Set(iterable);
const result = $.partition(set, (x) => x % 2 == 0);
assert.deepEqual(result, [[2, 4, 6, 8], [1, 3, 5, 7]]);
});
it('work with generator', () => {
function* oneToEight() {
for (let i = 1; i <= 8; i++) {
yield i;
}
}
const result = $.partition(oneToEight(), (x) => x % 2 == 0);
assert.deepEqual(result, [[2, 4, 6, 8], [1, 3, 5, 7]]);
});
});

0 comments on commit 457ec30

Please sign in to comment.