Skip to content

Instantly share code, notes, and snippets.

@snichme
Created October 14, 2015 18:48
Show Gist options
  • Save snichme/4d98f56cdbc9226764d7 to your computer and use it in GitHub Desktop.
Save snichme/4d98f56cdbc9226764d7 to your computer and use it in GitHub Desktop.
Dependency Injection in JavaScript
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