chill-patch
v1.3.1
Published
Stress-free monkey-patching
Downloads
18
Maintainers
Readme
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]
// safely add a method to `Array`
const last = chillPatch(Array, lastFunc, 'last')
// call the new method!
array[last]() //=> 3
You can use chill-patch
to use off-the-shelf this
-less functions as methods:
// Using toggle-set without chill-patch
const toggleSet = require('toggle-set')
const set = new Set([1, 2, 3])
toggleSet(set, 1) // Set([2, 3])
// Using toggle-set with chill-patch
const toggle = chillPatch(Set, toggleSet)
set[toggle](4) // Set([1, 2, 3, 4])
Install
npm install chill-patch
Uses
- Method-chaining-style syntax:
// can adapt functions like this:
func3(func2(func1(instance)))
// and chain them like this:
instance
[func1]()
[func2]()
[func3]()
// which is very similar to method chaining
instance
.method1()
.method2()
.method3()
- testing
const chillPatch = require('chill-patch')
const should = chillPatch(Object, require('should/as-function'))
const foo = {a: 2}
foo[should]().deepEqual({a: 2}) // succeeds
foo[should]().deepEqual({a: 3}) // fails
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 thedescription
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.
// after the above code is run, there is no change to the `ownPropertyNames` of the patched class
Object.getOwnPropertyNames(Array.prototype) // doesn't include anything new!
Similar Tech in other Languages
Scala Implicit Conversions
Objective-C Categories
Haskell Typeclasses and Rust Traits
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 //=> "Hello, hello!"
let result = "hello"
|> doubleSay
|> capitalize
|> exclaim;
result //=> "Hello, hello!"
The Pipeline Operator is from F#, is also implemented in Elm and is similar to Clojure's threading macro.