Last active
February 26, 2019 13:24
-
-
Save thisredone/783407f9aacc496c4c13e4076bca7d63 to your computer and use it in GitHub Desktop.
Some usefull extensions
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# automatic bind | |
Object.defineProperty Object.prototype, '_bind', | |
enumerable: false | |
get: -> | |
new Proxy this, | |
get: (thing, prop) => | |
thing[prop].bind(thing) | |
# Usage | |
foo.on 'thing', console._bind.log | |
Function::curry = (params...) -> | |
(rest...) => this(params..., rest...) | |
# Usage | |
foo.on 'thing', log.curry('A thing:') | |
# shorthand for retreiving props + bonus is, isnt | |
_ = _it = new Proxy {}, | |
get: (_, prop) -> | |
retrieve = (props...) -> | |
fn = (obj) -> | |
props.reduce ((obj, prop) -> obj[prop]), obj | |
if props.last() in ['is', 'isnt'] | |
prop = props.pop() | |
switch prop | |
when 'is' then (val) -> (obj) -> fn(obj) is val | |
when 'isnt' then (val) -> (obj) -> fn(obj) isnt val | |
else | |
new Proxy fn, | |
get: (_, prop) -> retrieve(props..., prop) | |
retrieve(prop) | |
# Usage | |
foo.map _.some.field | |
bar.find _.some.thing.is 'foo' | |
# Same as above but with function calling | |
global._fn = new Proxy {}, | |
get: (_, prop) -> | |
retrieve = (props...) -> | |
fn = (myArgs...) -> (obj, baseArgs...) -> | |
(props.reduce ((obj, prop) -> obj[prop]), obj).call(obj, myArgs..., baseArgs...) | |
new Proxy fn, | |
get: (_, prop) -> retrieve(props..., prop) | |
retrieve(prop) | |
# Usage | |
foos.map _fn.some.func() # func will be called with 1.. args that .map gave it | |
foos.map _fn.some.func('firstArg') # provided args will come first | |
# Dynamic getter | |
Object.defineProperty Object.prototype, '_get', | |
enumerable: false | |
get: -> | |
parent = this | |
new Proxy parent, | |
get: (thing, childName) => | |
new Proxy thing, | |
get: (_, prop, receiver) -> Reflect.get(parent[childName], prop, receiver) | |
set: (_, prop, receiver) -> Reflect.set(parent[childName], prop, receiver) | |
# Usage | |
objects = everChanging: { foo: 'bar' } | |
referencer = alwaysFreshObject: objects._get.everChanging | |
console.log referencer.alwaysFreshObject.foo # bar | |
objects.everChanging = { bar: 'foo' } | |
console.log referencer.alwaysFreshObject.bar # foo |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment