all files / js-difunc/ index.js

89.29% Statements 25/28
88.46% Branches 23/26
100% Functions 1/1
89.29% Lines 25/28
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46    12×     11×     10× 10×   10×       10× 36× 36× 15×   14× 21× 21× 12×                    
"use strict";
const esprima = require('esprima');
 
module.exports = function difunc(dependencies, func, thisArg) {
  if (typeof func !== 'function') {
    throw new Error(`${func} was not typeof function`);
  }
 
  if (!dependencies || typeof dependencies !== 'object') {
    throw new Error(`${dependencies} was not typeof 'object' or was falsey`);
  }
 
  const tokens = esprima.tokenize(func.toString());
  const params = [];
 
  if (tokens[0].type === 'Keyword') {
    tokens.shift();
    if (tokens[0].type === 'Identifier') {
      tokens.shift();
    }
  }
 
  for (let token, i = 0, len = tokens.length; i < len; i++) {
    token = tokens[i];
    if (token.type === 'Identifier') {
      if (!(token.value in dependencies)) {
        throw new Error(`${token.value} was not defined in dependencies`);
      }
      params.push(dependencies[token.value]);
    } else Eif (token.type === 'Punctuator') {
      if (token.value === '(' || token.value === ',') {
        continue;
      } else Iif(token.value === '{' || token.value === '[') {
        throw new Error('destructuring is not supported');
      } else Iif(token.value === '=') {
        throw new Error('default parameters are not supported');
      }
      break;
    } else {
      break;
    }
  }
 
  return func.apply(thisArg, params);
};