Skip to content

Instantly share code, notes, and snippets.

@Capster
Forked from MattiasFestin/uneval.es6
Created December 12, 2016 17:52
Show Gist options
  • Save Capster/2c95ee602c75952cf5a09bd174fe5302 to your computer and use it in GitHub Desktop.
Save Capster/2c95ee602c75952cf5a09bd174fe5302 to your computer and use it in GitHub Desktop.
uneval "polyfill"
let uneval = (o, noNativeFns = true) => {
var retVal = '';
if (typeof o === 'object') {
if (Array.isArray(o)) {
retVal = '[' + o.map((el) => uneval(el)).join(',') + ']';
} else if (o instanceof RegExp) {
retVal = o.toString();
} else if (o instanceof Date) {
retVal = `new Date(${o})`;
} else if (o === null) {
retVal = 'null';
} else if (Number.isNaN(o)) {
retVal = 'NaN';
}else {
//[TODO] add support for defineProperty & getters & setters
retVal = '{' + Object.keys(o).map((k) => `"${k}":${uneval(o[k])}`).join(',') + '}';
}
} else if (typeof o === 'function') {
let isNative = o.toString().match(/^function \(\) \{ \[native code\] \}$/);
if (isNative && noNativeFns) {
throw new Error('No native functions is allowed');
}
retVal = `(${isNative ? o.name : o.toString()})`;
} else {
retVal = JSON.stringify(o);
}
return retVal;
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment