Skip to content

Instantly share code, notes, and snippets.

@jpillora
Last active April 30, 2018 01:21
Show Gist options
  • Save jpillora/5667454 to your computer and use it in GitHub Desktop.
Save jpillora/5667454 to your computer and use it in GitHub Desktop.
Micro JavaScript Dependancy Injection.Written in CoffeeScript / JS.This is *approximately* how AngularJS works.
# Micro JavaScript Dependancy Injection
define = (name, val) ->
#init modules map if missing
define.mods = define.mods or {}
#store 'name'
define.mods[name] = val
inject = (fn) ->
#regex match on function.toString()
m = fn.toString().match /function\s(\w+)?\((.*)\)/
throw "Function parse failed" unless m
#prepare arguments
args = []
#loop through function parameter names
for name in m[2].split(", ")
continue unless name
#look for module with 'name'
m = define.mods[name]
throw "Missing '#{name}' module" unless m
#add to arguments
args.push m
#call function with arguments
fn.apply this, args
#example usage
define 'a', 42
define 'b', 21
define 'c', 7
inject -> print "no-args" #no-args
inject (b) -> print b #21
inject (a,b,c) -> print a+b-c #56
// Micro JavaScript Dependancy Injection
var define = function(name, val) {
//init modules map if missing
define.mods = define.mods || {};
//store 'name'
return define.mods[name] = val;
};
var inject = function(fn) {
var args, m, name, i, params;
//regex match on function.toString()
m = fn.toString().match(/function\s(\w+)?\((.*)\)/);
if (!m) throw "Function parse failed";
//prepare arguments
args = [];
params = m[2].split(", ");
//loop through function parameter names
for (i = 0; i < params.length; i++) {
name = params[i];
if (!name)continue;
//look for module with 'name'
m = define.mods[name];
if (!m) throw "Missing '" + name + "' module";
//add to arguments
args.push(m);
}
//call function with arguments
return fn.apply(this, args);
};
//example usage
define('a', 42);
define('b', 21);
define('c', 7);
inject(function() {
return print("no-args");
});
inject(function(b) {
return print(b); //21
});
inject(function(a, b, c) {
return print(a + b - c); //56
});
@andreypopp
Copy link

As Function.toString() is defined lexically (and so statically), I think it would be nice also to have such thing implemented as a source code transform.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment