chill-patch: Stress-free Monkey Patching for JavaScript
chill-patch enables you to add methods to JS classes, with none of the problems of traditional monkey-patching.
const chillPatch = require('chill-patch')
const lastFunc = arr => arr[arr.length - 1]
const array = [1, 2, 3]
const last = chillPatch(Array, lastFunc, 'last')
array[last]()
You can use chill-patch
to use off-the-shelf this
-less functions as methods:
const toggleSet = require('toggle-set')
const set = new Set([1, 2, 3])
toggleSet(set, 1)
const toggle = chillPatch(Set, toggleSet)
set[toggle](4)
Install
npm install chill-patch
Uses
- Method-chaining-style syntax:
func3(func2(func1(instance)))
instance
[func1]()
[func2]()
[func3]()
instance
.method1()
.method2()
.method3()
const chillPatch = require('chill-patch')
const should = chillPatch(Object, require('should/as-function'))
const foo = {a: 2}
foo[should]().deepEqual({a: 2})
foo[should]().deepEqual({a: 3})
API
chillPatch(Klass, func, optionalDescription)
Klass
is an ES5-style or ES2015-style classfunc
is a function with any number of argumentsoptionalDescription
is used as the description
of the symbol.
Why it's Safe
chill-patch
is safe because the return value is a Symbol and symbols are guaranteed to be unique. That means that the only way to access the new method you created is to have access to the symbol.
The only way another programmer can get access to symbols on an object in another scope is if they are hellbent on doing so, in which case they know they are going off-roading.
When you add a property to a prototype using a symbol, it's hidden, so you can safely pass off the patched object to other parts of the codebase, without other programmers knowing its there or being affected by it.
Object.getOwnPropertyNames(Array.prototype)
Similar Tech in other Languages
Something Better
The JavaScript Pipeline Operator proposal accomplishes the same syntactic convenience more simply and elegantly. The following two expressions would be equivalent:
let result = exclaim(capitalize(doubleSay("hello")));
result
let result = "hello"
|> doubleSay
|> capitalize
|> exclaim;
result
from the pipeline operator proposal
The Pipeline Operator is from F#, is also implemented in Elm and is similar to Clojure's threading macro.