Created
October 14, 2015 18:48
-
-
Save snichme/4d98f56cdbc9226764d7 to your computer and use it in GitHub Desktop.
Dependency Injection in JavaScript
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
var di = (function Dein() { | |
var FN_ARGS = /^function\s*[^\(]*\(\s*([^\)]*)\)/m; | |
var FN_ARG_SPLIT = /,/; | |
var FN_ARG = /^\s*(_?)(\S+?)\1\s*$/; | |
var STRIP_COMMENTS = /((\/\/.*$)|(\/\*[\s\S]*?\*\/))/mg; | |
var _register = {}; | |
function anno(fn, strictDi, name) { | |
var fnText, argDecl, args; | |
if (fn.length) { | |
fnText = fn.toString().replace(STRIP_COMMENTS, ''); | |
argDecl = fnText.match(FN_ARGS); | |
args = argDecl[1].split(FN_ARG_SPLIT); | |
return args.map(function(arg) { | |
return arg.trim(); | |
}); | |
} | |
return []; | |
} | |
function fnName(fn) { | |
return fn.name; | |
} | |
function register(fn) { | |
var name = fnName(fn); | |
_register[name] = fn; | |
} | |
function resolve(fn) { | |
var args = anno(fn); | |
var a = args.map(function(name) { | |
var f = _register[name]; | |
return resolve(f); | |
}); | |
return fn.apply(null, a); | |
} | |
resolve.register = register; | |
return resolve; | |
}()); | |
di.register(function dbconfig() { | |
return { | |
host: 'localhost', | |
port: 1337 | |
}; | |
}); | |
di.register(function db(dbconfig) { | |
return function(user, pw) { | |
console.log(dbconfig, user, pw); | |
return true; | |
}; | |
}); | |
di.register(function log() { | |
return function(str) { | |
console.log(str); | |
}; | |
}); | |
function app(log, db) { | |
return function() { | |
if(db('user', 'pw')) { | |
log('connected!'); | |
} else { | |
log('could not connect'); | |
} | |
}; | |
} | |
var a = di(app); | |
a(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment