Wednesday, September 13, 2017

Dig, dig, dig

One of the tasks that I've had to take up over the course of my career is digging into code. To automate that task a little, I've written a little JavaScript that turns functions into a recognizable object - one that has a 'name', 'params', and 'source'. While this isn't complete enough to include the type expected or whether the parameter is required or optional, it has proven useful in determining whether or not a specific function accepts a parameter.

This can easily be used when providing a wrapper function that simulates function overloading that's present in other languages, or to provide validation of a function call before the call is ever issued. I'm sure you can find other uses for it as well, just use your imagination.

To show how this works, I'm including the code here, along with a simple demo to show just how it works.

JavaScript
function functionParser(func) {   var obj = {       name: func.name,       params: [],       source: func.toString(),     },     tmp;   /* set the name */   obj.name = func.name;   try {     /* replace known elements in the source to get a recognizable string */     tmp = obj.source.substr(0, obj.source.indexOf('{'))                 .replace(obj.name, '')                 .replace(/\s*function\s*/, '')                 .replace(/^\s*|\s*$/g, '')                 .replace(/\(/g, '["')                 .replace(/\)/g, '"]')                 .replace(/,/g, '","');     /* turn the json string into an object */     tmp = JSON.parse(tmp);     /* loop through all the params and trim the string */     tmp.forEach(function(v, i) {         obj.params.push(v.replace(/^\s*|\s*$/g, ''));       });   } catch (ignore) {     // don't really do anything with the error   }   return obj; }


...and here's the example



If you see the use of this, feel free to copy it. It's pretty simple, but I'd appreciate if you'd include a bit of attribution if you do use it. Thanks.

Happy coding.

No comments:

Post a Comment