Skip to content

Instantly share code, notes, and snippets.

@kuanyui
Last active December 1, 2020 08:04
Show Gist options
  • Save kuanyui/4a532f563b7b51c503477104c870b64b to your computer and use it in GitHub Desktop.
Save kuanyui/4a532f563b7b51c503477104c870b64b to your computer and use it in GitHub Desktop.
Some small type-awared utils for TypeScript.
export { }
declare global {
interface Array<T> {
/** Return the last element of this array. */
last (): T | undefined
/** Delete the first element from this array. If delete success, return true. */
delete (elem: T): boolean
/** Delete the first element satisfying the @param fn. If delete success, return true. */
deleteIf (fn: (elem: T) => boolean): boolean
}
}
Array.prototype.last = function () {
return this[this.length - 1]
}
Array.prototype.delete = function <T> (elem: T): boolean {
const i = this.indexOf(elem)
if (i === -1) { return false }
this.splice(i, 1)
return true
}
Array.prototype.deleteIf = function <T>(fn: (x: T) => boolean): boolean {
const i = this.findIndex(fn)
if (i === -1) { return false }
this.splice(i, 1)
return true
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment