Skip to content

Instantly share code, notes, and snippets.

@HerringtonDarkholme
Created June 23, 2014 17:32
Show Gist options
  • Save HerringtonDarkholme/2752495bacc2d0175692 to your computer and use it in GitHub Desktop.
Save HerringtonDarkholme/2752495bacc2d0175692 to your computer and use it in GitHub Desktop.
{isArray, isFunc} = require('./util')
class Extractor
FN_ARGS = ///
^function # function
\s* # optional white
[^\(]* # function name
\( # left paren
\s*
([^\)]*) #params
\) # right paren
///m
COMMENT = ///
\/\*[\s\S]*?\*\/ # block comment
| \/\/.*$ # linewise comment
///mg
FN_ARG_SPLIT = /,/
FN_ARG = /^\s*(\S+)\s*$/mg
annotate = (func) ->
if not isFunc(func)
throw new Error('need function')
fnText = func.toString().replace(COMMENT, '')
params = fnText.match(FN_ARGS)[1]
(param.trim() for param in params.split(FN_ARG_SPLIT))
constructor: (@ctor) ->
@annotation = null
@unapply = null
annotation = @ctor::unapply
if not annotation?
@annotation = annotate(@ctor)
else if isArray(annotation)
@annotation = annotation
else if isFunc(annotation)
@unapply = annotation
extract = (ctor) ->
extractor = new Extractor(ctor)
F = (args...) ->
return extractor if not @ instanceof ctor
ctor.apply(this, args)
F extends ctor
F
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment