@igor.dvlpr/hook v1.1.0
๐ Table of contents
๐ต๐ผ Usage
Install it by executing:
npm i "@igor.dvlpr/hook"๐คน๐ผ API
!CAUTION This package provides ways of modifying the native prototype(s) of built-in JavaScript objects, use it only if you know what you're doing and with caution as it may cause unexpected results!
hook(): boolean
function hook(
proto: Prototype,
method: string,
handler: NativeMethodHook<Prototype, Method>,
replace: boolean = false
): booleanHooks onto a JavaScript prototype in order to extend, modify or completely replace a given method of it.
proto
A prototype, e.g. Array.prototype, Number.prototype, etc.
method
A method to hook onto, e.g. push of Array.prototype.
handler
A custom function to run when the hooked method is called. The function has the following signature:
(
this: Type,
native: Type[Method],
...args: any[]
) => ReturnType<Type[Method]>this will be resolved to the provided prototype.
native is the native method that's being overridden, with its original signature.
...args: any[] all other arguments passed after the native method.
ReturnType<Type[Method]> the return type of the handler is the same as the native method is.
replace
A Boolean indicating whether the prototype method should be replaced completely.
Defaults to false.
Returns a Boolean whether the hooking onto was successful.
โจ Examples
import { hook } from '@igor.dvlpr/hook'
hook(Array.prototype, 'unshift', function (native, x) {
// any code can be here,
// not just owned by the prototype
// you're hooking/replacing
native(512)
this.push(x / 2)
// must adhere to the original method's
// return type
// see https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/unshift#return_value
return this.length // returns 3
})
const array: number[] = []
array.unshift(256)
console.log(array) // [512, 256, 128]๐ Changelog
๐ Changelog is available here: CHANGELOG.md.
๐ชช License
Licensed under the MIT license which is available here, MIT license.
๐งฌ Related
๐ถ๏ธ Reads a JSON file into a Map. ๐ป
๐ฅ Removes HTML code from the given string. Can even extract text-only from the given an HTML string. โจ
๐ Formats the provided string as a comment, either a single or a multi line comment for the given programming language. ๐ป
๐ NormalizedString provides you with a String type with consistent line-endings, guaranteed. ๐ฎ
๐ก Parse, manage, compare and output SemVer-compatible version numbers. ๐ก
๐จ๐ปโ๐ป Author
Created by Igor Dimitrijeviฤ (@igorskyflyer).