Skip to content

Commit

Permalink
Adds TakeWhile (#42)
Browse files Browse the repository at this point in the history
  • Loading branch information
jmeline authored and jreina committed Oct 6, 2018
1 parent 4ea61f2 commit 08bbc2a
Show file tree
Hide file tree
Showing 4 changed files with 48 additions and 3 deletions.
3 changes: 2 additions & 1 deletion index.d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ interface Array<T> {
Prepend<T>(element: T): Array<T>;
Reverse<T>(): Array<T>;
Select<T, U>(xform: (x: T) => U): Array<U>;
Where<T>(predicate: (X: T) => boolean): Array<T>;
TakeWhile<T>(predicate: (X: T) => boolean): Array<T>;
Union<T>(adder: Array<T>): Array<T>;
Where<T>(predicate: (X: T) => boolean): Array<T>;
}
6 changes: 4 additions & 2 deletions index.js
Original file line number Diff line number Diff line change
Expand Up @@ -3,17 +3,19 @@ const Last = require('./src/Last');
const Prepend = require('./src/Prepend');
const Reverse = require('./src/Reverse');
const Select = require('./src/Select');
const Where = require('./src/Where');
const TakeWhile = require('./src/TakeWhile');
const Union = require('./src/Union');
const Where = require('./src/Where');

const bindAll = function() {
Array.prototype.Aggregate = Aggregate;
Array.prototype.Last = Last;
Array.prototype.Prepend = Prepend;
Array.prototype.Reverse = Reverse;
Array.prototype.Select = Select;
Array.prototype.Where = Where;
Array.prototype.TakeWhile = TakeWhile;
Array.prototype.Union = Union;
Array.prototype.Where = Where;
};

module.exports = bindAll;
22 changes: 22 additions & 0 deletions src/TakeWhile.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
/**
* @template T
* @param {((x: T) => boolean)} predicate
* @returns {Array<T>}
*/

function TakeWhile(predicate) {
if (this.length === 0) {
throw 'source contains no elements';
}
const output = [];
for (let x of this) {
if (predicate(x)) {
output.push(x);
} else {
break;
}
}
return output;
}

module.exports = TakeWhile;
20 changes: 20 additions & 0 deletions test/TakeWhile.spec.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
const expect = require('chai').expect;
require('..')();

describe('Array#prototype#TakeWhile', function() {
it('Should return the first 4 numbers', function() {
const input = [1, 2, 3, 4, 5, 6];
const expected = [1, 2, 3, 4];
const predicate = x => x <= 4;
const actual = input.TakeWhile(predicate);
expect(actual).to.eql(expected);
});

it('Should throw an error when predicate is undefined', function() {
expect(() => [1, 2, 3].TakeWhile()).to.throw();
});

it('Should throw an error when source is null', function() {
expect(() => [].TakeWhile()).to.throw();
});
});

0 comments on commit 08bbc2a

Please sign in to comment.