Created
August 6, 2023 17:32
-
-
Save stephenscaff/64e93cbe2822b825f06e591471b78dc6 to your computer and use it in GitHub Desktop.
find.ts
This file contains hidden or 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
export default function findInArray<T>( | |
arr: T[], | |
callback: (element: T, index: number, array: T[]) => boolean | |
): T | undefined { | |
if (typeof callback !== 'function') { | |
throw new TypeError('callback must be a function') | |
} | |
const list = Object(arr) | |
// Makes sure it always has a positive integer as length. | |
const length = list.length >>> 0 | |
const thisArg = arguments[2] | |
for (let i = 0; i < length; i++) { | |
const element = list[i] | |
if (callback.call(thisArg, element, i, list)) { | |
return element | |
} | |
} | |
return undefined | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment