Last active
August 29, 2015 14:15
-
-
Save jbgutierrez/834ffae94a9bd3202bf2 to your computer and use it in GitHub Desktop.
Colaborative function patches
This file contains 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
Function::patch = (binding, fn) -> | |
unless fn | |
fn = binding | |
binding = @ | |
wrapped = (args...) -> | |
args.unshift (args...) -> | |
wrapped.previous.apply binding, args | |
fn.apply binding, args | |
wrapped.previous = @ | |
wrapped | |
Function::patches = -> | |
return [@] unless @previous | |
previous = @ | |
patches = (previous while previous = previous.previous) or [] | |
patches.unshift @ | |
console.log patches | |
patches | |
Function::reset = -> @patches().pop() | |
modules = | |
salutation: "Hla" | |
greet: (name) -> console.log "#{@salutation} #{name}" | |
modules.greet = modules.greet. | |
patch(modules, (previous, name) -> | |
console.log "before patches" | |
@salutation = "Hola" | |
previous name | |
console.log "after patches" | |
). | |
patch(modules, (previous, name) -> | |
console.log "before experiments" | |
@salutation = "Welcome" | |
previous name | |
console.log "after experiments" | |
). | |
patch(modules, (previous, name) -> | |
console.log "before marketing" | |
@salutation = "♡" | |
previous name | |
console.log "after marketing" | |
) | |
modules.greet "javi" #=> | |
# before marketing | |
# before experiments | |
# before patches | |
# Hola javi | |
# after patches | |
# after experiments | |
# after marketing | |
modules.greet = modules.greet.reset() | |
modules.greet "javi" #=> Hola javi |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment