-
Notifications
You must be signed in to change notification settings - Fork 15
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
Showing
4 changed files
with
38 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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; |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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; | ||
}); | ||
}); |