Skip to content

Commit

Permalink
Adds FirstOrDefault (#64)
Browse files Browse the repository at this point in the history
  • Loading branch information
CooRay authored and jreina committed Oct 7, 2018
1 parent f7b64f5 commit 81110c5
Show file tree
Hide file tree
Showing 4 changed files with 38 additions and 0 deletions.
2 changes: 2 additions & 0 deletions index.d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,8 @@ interface Array<T> {
ElementAt<T>(index: number): T;
First<T>(): T;
First<T>(predicate: (x: T) => boolean): T;
FirstOrDefault<T>(): T;
FirstOrDefault<T>(pedicate: (x: T) => boolean): T;
GroupJoin<T, U, V, K>(
inner: Array<U>,
outerKeySelector: ((x: T) => K),
Expand Down
2 changes: 2 additions & 0 deletions index.js
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ const Any = require('./src/Any');
const Concat = require('./src/Concat');
const Count = require('./src/Count');
const ElementAt = require('./src/ElementAt');
const FirstOrDefault = require('./src/FirstOrDefault');
const Empty = require('./src/Empty')
const First = require('./src/First');
const GroupJoin = require('./src/GroupJoin');
Expand All @@ -27,6 +28,7 @@ const bindAll = function() {
Array.prototype.Concat = Concat;
Array.prototype.Count = Count;
Array.prototype.ElementAt = ElementAt;
Array.prototype.FirstOrDefault = FirstOrDefault;
Array.Empty = Empty;
Array.prototype.First = First;
Array.prototype.GroupJoin = GroupJoin;
Expand Down
10 changes: 10 additions & 0 deletions src/FirstOrDefault.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
/**
* @template T
* @param {((x: T) => boolean)} predicate
* @returns {T}
*/
function FirstOrDefault(predicate) {
if (predicate) return this.find(predicate);
return this[0];
}
module.exports = FirstOrDefault;
24 changes: 24 additions & 0 deletions test/FirstOrDefault.spec.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
const expect = require('chai').expect;
require('..')();

describe('Array#prototype#First', function() {
const input = [2, 4, 6, 8];
it('Should return the first value with no predicate passed', function() {
const expected = 2;
const actual = input.FirstOrDefault();
expect(actual).to.eql(expected);
});
it('Should return the first value matching predicate', function() {
const expected = 2;
const actual = input.FirstOrDefault(x => x % 2 === 0);
expect(actual).to.eql(expected);
});
it('Should return undefined when no matching element in array with values', function() {
const actual = input.FirstOrDefault(x => x === 1);
expect(actual).to.be.undefined;
});
it('Should return undefined when no matching element in empty array', function() {
const actual = [].FirstOrDefault();
expect(actual).to.be.undefined;
});
});

0 comments on commit 81110c5

Please sign in to comment.