Skip to content

Instantly share code, notes, and snippets.

@stephenscaff
Created August 6, 2023 17:32
Show Gist options
  • Save stephenscaff/64e93cbe2822b825f06e591471b78dc6 to your computer and use it in GitHub Desktop.
Save stephenscaff/64e93cbe2822b825f06e591471b78dc6 to your computer and use it in GitHub Desktop.
find.ts
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