Skip to content
This repository has been archived by the owner on Jan 16, 2024. It is now read-only.

Commit

Permalink
add arrayFind (implementation of Array.prototype.find)
Browse files Browse the repository at this point in the history
  • Loading branch information
vsiao committed Jan 28, 2015
1 parent a95f067 commit ac42cc9
Show file tree
Hide file tree
Showing 3 changed files with 78 additions and 0 deletions.
28 changes: 28 additions & 0 deletions src/arrayFind.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
/**
* Usage: import arrayFind = require("tsutil/arrayFind");
*
* arrayFind([1,2,3,4,5], (x) => x === 3);
*
* @param {Array<T>} list
* @param {(x: T) => boolean} predicate
* @param {Object} thisArg?
* @returns {T?}
*/
function arrayFind<T>(
list: T[],
predicate: (x: T, index: number, list: T[]) => boolean,
thisArg?: {}): T {

var length = list.length;
var value: T;
for (var i = 0; i < length; i++) {
value = list[i];
if (predicate.call(thisArg, value, i, list)) {
return value;
}
}
return undefined;
}

export = arrayFind;

1 change: 1 addition & 0 deletions src/index.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
/**
* TsUtil Exports
*/
export import arrayFind = require("./arrayFind");
export import Handle = require("./handle");
export import identity = require("./identity");
export import Optional = require("./optional");
Expand Down
49 changes: 49 additions & 0 deletions test/arrayFind_spec.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,49 @@
import chai = require("chai");
import tsutil = require("../src/index");

var arrayFind = tsutil.arrayFind;
var assert = chai.assert;

describe("arrayFind", () => {

var list: number[] = [5, 10, 15, 20];

it("should find item by predicate", function() {
var result = arrayFind(list, (x) => x === 15);
assert.equal(result, 15);
});

it("should return undefined when nothing matched", function() {
var result = arrayFind(list, (x) => x === -1);
assert.equal(result, undefined);
});

it("should receive all three parameters", function() {
arrayFind(list, (value, index, arr) => {
assert.equal(list[index], value);
assert.equal(list, arr);
return false;
});
});

it("should work with the context argument", function() {
var context = {};
arrayFind([1], function() {
assert.equal(this, context);
return false;
}, context);
});

it("should work with a sparse array", function() {
var obj = [1, , undefined];
assert.isFalse(1 in obj);
var seen: any[] = [];
var found = arrayFind(obj, (x) => {
seen.push(x);
return false;
});
assert.equal(found, undefined);
assert.sameMembers(seen, [1, undefined, undefined]);
});
});

0 comments on commit ac42cc9

Please sign in to comment.