Skip to content

Commit

Permalink
feat(arrays): add find/findIndex()
Browse files Browse the repository at this point in the history
  • Loading branch information
postspectacular committed Feb 14, 2019
1 parent 51959b7 commit 0007152
Show file tree
Hide file tree
Showing 2 changed files with 33 additions and 0 deletions.
32 changes: 32 additions & 0 deletions packages/arrays/src/find.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
import { Predicate2 } from "@thi.ng/api";
import { equiv as _equiv } from "@thi.ng/equiv";

/**
* Similar to `Array.find()`, but uses thi.ng/equiv as default
* predicate.
*
* @param src
* @param x
* @param equiv
*/
export const find =
<T>(src: ArrayLike<T>, x: T, equiv: Predicate2<T> = _equiv) => {
const i = findIndex(src, x, equiv);
return i !== -1 ? src[i] : undefined;
};

/**
* Similar to `Array.findIndex()`, but uses thi.ng/equiv as default
* predicate.
*
* @param src
* @param x
* @param equiv
*/
export const findIndex =
<T>(src: ArrayLike<T>, x: T, equiv: Predicate2<T> = _equiv) => {
for (let i = src.length; --i >= 0;) {
if (equiv(x, src[i])) return i;
}
return -1;
};
1 change: 1 addition & 0 deletions packages/arrays/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ export * from "./binary-search";
export * from "./ends-with";
export * from "./ensure-array";
export * from "./ensure-iterable";
export * from "./find";
export * from "./fuzzy-match";
export * from "./peek";
export * from "./shuffle";
Expand Down

0 comments on commit 0007152

Please sign in to comment.