Skip to content

Instantly share code, notes, and snippets.

@cheesits456

cheesits456/uneval.js

Forked from cho45/uneval.js
Last active Jan 12, 2020
Embed
What would you like to do?
Stringify multiple JS Object Types
function uneval(o) {
switch (typeof o) {
case "undefined": return "(void 0)";
case "boolean": return String(o);
case "number": return String(o);
case "string": return `"${o.replace(/\W/gi, function(_) { return `\\u${(0x10000 + _.charCodeAt(0)).toString(16).slice(1)}` })}"`;
case "function": return `(${o.toString()})`;
case "object":
if (o == null) return "null";
let ret, type = Object.prototype.toString.call(o).match(/\[object (.+)\]/);
if (!type) throw TypeError(`unknown type: ${o}`);
switch (type[1]) {
case "Array":
ret = [];
for (let i = 0, l = o.length; i < l; ret.push(arguments.callee(o[i++])));
return `[${ret.join(",")}]`;
case "Object":
ret = [];
for (let i in o) {
if (o.hasOwnProperty(i)) ret.push(`${arguments.callee(i)}:${arguments.callee(o[i])}`);
};
return `({${ret.join(",")}})`;
case "Number": return `(new Number(${o}))`;
case "String": return `(new String(${arguments.callee(o)}))`;
case "Date": return `(new Date(${o.getTime()}))`;
case "Error": return `(new Error('${o.message.replace(/\W/gi, function(_) { return `\\u${(0x10000 + _.charCodeAt(0)).toString(16).slice(1)}` })}'))`;
default:
if (o.toSource) return o.toSource();
throw TypeError(`unknown type: ${o}`);
}
}
return "";
}
/*
Using eval() on the return value will return the same thing as the original input
input | return value | eval(return value)
-------------------------------|-------------------------------------|---------------------------------
true | 'true' | true
42 | '42' | 42
"Hello World" | '"Hello\u002c\u0020World\u0021"' | 'Hello, World!'
function a(b){return b} | '(function a(b){return b})' | function a(b){return b}
["one", 2, "three"] | '["one",2,"three"]' | [ 'one', 2, 'three' ]
{key: "value", key2: "value2"} | '({"key":"value","key2":"value2"})' | { key: 'value', key2: 'value2' }
*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.