JSFiddle - React, Tailwind, and code Playground

by Simon060694

JavaScript

function getArrowFunctionBody(f) {
  const matches1 = f.toString().match(/function[^{]+\{([\s\S]*)\}$/);
  if (matches1) return f[1];
  const matches = f.toString().match(/^(?:\s*\(?(?:\s*\w*\s*,?\s*)*\)?\s*?=>\s*){?([\s\S]*)}?$/);
  if (!matches) {
    return null;
  }

  const firstPass = matches[1];

  // Needed because the RegExp doesn't handle the last '}'.
  const secondPass =
    (firstPass.match(/{/g) || []).length === (firstPass.match(/}/g) || []).length - 1
      ? firstPass.slice(0, firstPass.lastIndexOf('}'))
      : firstPass;

  return secondPass;
}

const resource = function(baseUrl, baseCallback) {
  const x = {
    getArrowFunctionBody,
    resourceGlobal: resource,
    beforeGlobal: (...args) => {
      for(let i=0;i<beforeList.length;i++){
        beforeList[i](...args);
      } 
    },
    getGlobal: (url, callback) => {
      callback(url);
    },
    beforeList: 'new Array()',
    before: callback => beforeList.push(callback),
    get: callback => {
      getGlobal(baseUrl, async (req, res) => {
        await beforeGlobal(req, res);
        await callback(req, res);
      });
    },
    resource: (url, callback) => {
      resourceGlobal(baseUrl + url, callback);
    },
    toString: function() {
      let res = '';
      const keys = Object.keys(this);
      for (let i = 0; i < keys.length; i++) {
        res += 'let ' + keys[i] + '=' + this[keys[i]].toString() + ';';
      }
      return res;
    }
  };
  const funcBody = getArrowFunctionBody(baseCallback);
  const body =  x.toString() + ';' + funcBody;

  const tempBasic = new Function('baseUrl', body);
  const funct = tempBasic.call(x, baseUrl);
};

resource('/test', () => {
  before(() => {
    console.log('before1 was called');
  });
  get(url => {
    console.log('Expect /test', url);
  });

  resource('/subTest', () => {
    get(url => {
      console.log('Expect /test/subTest', url);
    });
  });
});