// The following simplified code is partly taken from the AngularJS source code: // https://github.com/angular/angular.js/blob/master/src/auto/injector.js#L63
functioninject(fn, variablesToInject) { var FN_ARGS = /^function\s*[^\(]*\(\s*([^\)]*)\)/m; var FN_ARG_SPLIT = /,/; var FN_ARG = /^\s*(_?)(\S+?)\1\s*$/; var STRIP_COMMENTS = /((\/\/.*$)|(\/\*[\s\S]*?\*\/))/mg;
if (typeof fn === 'function' && fn.length) { var fnText = fn.toString(); // getting the source code of the function fnText = fnText.replace(STRIP_COMMENTS, ''); // stripping comments like function(/*string*/ a) {}
var matches = fnText.match(FN_ARGS); // finding arguments var argNames = matches[1].split(FN_ARG_SPLIT); // finding each argument name
var newArgs = []; for (var i = 0, l = argNames.length; i < l; i++) { var argName = argNames[i].trim();
if (!variablesToInject.hasOwnProperty(argName)) { // the argument cannot be injected thrownewError("Unknown argument: '" + argName + "'. This cannot be injected."); }
newArgs.push(variablesToInject[argName]); }
fn.apply(window, newArgs); } }
functionsum(x, y) { console.log(x + y); }
inject(sum, { x: 5, y: 6 }); // should print 11
inject(sum, { x: 13, y: 45 }); // should print 58
inject(sum, { x: 33, z: 1// we are missing 'y' }); // should throw an error: Unknown argument: 'y'. This cannot be injected.