Skip to content

Instantly share code, notes, and snippets.

@jbgutierrez
Last active August 29, 2015 14:15
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jbgutierrez/834ffae94a9bd3202bf2 to your computer and use it in GitHub Desktop.
Save jbgutierrez/834ffae94a9bd3202bf2 to your computer and use it in GitHub Desktop.
Colaborative function patches
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