Skip to content

Instantly share code, notes, and snippets.

@jsmaker
Created June 27, 2012 13:02
Show Gist options
  • Save jsmaker/3003944 to your computer and use it in GitHub Desktop.
Save jsmaker/3003944 to your computer and use it in GitHub Desktop.
toCode returns the object as code string
function toCode(o, name) {
name = name || 'code';
var cache = [o];
var toCode = function (o, name) {
if (typeof o === 'string') {
return "'" + o + "'";
}
if (o instanceof Array) {
return toCode.arrayToCode(o, name);
}
return toCode.objectToCode(o, name);
}
toCode.baseOnType = function (op, name) {
var index = cache.indexOf(op);
if (~index) {
console.log('"' + name + '"');
return name;
}
cache.push(op);
var type = typeof op;
if (type === 'function') {
return op.toString().replace('{ [native code] }', '{ "[native code]" }');
}
if (type === 'string') {
return "'" + op + "'";
}
if (op instanceof Array) {
return toCode.arrayToCode(op, name);
}
if (op instanceof Object) {
return toCode.objectToCode(op, name);
}
if (op === undefined) {return 'undefined'}
if (op === null) {return 'null'}
return op.toString && op.toString() || "''";
};
toCode.arrayToCode = function (a, name) {
var as = '[';
for (var i = 0; i < a.length; i++) {
as += (i !== 0 ? ', ' : '') + toCode.baseOnType(a[i], name + '["' + i + '"]');
}
as += ']';
return as;
};
toCode.objectToCode = function (o, name) {
var os = '{';
var i = 0;
for (var p in o) {
os += (i++ !== 0 ? ', ' : '') + p + ': ' + toCode.baseOnType(o[p], name + '["' + p + '"]');
}
os += '}';
return os;
};
return 'var ' + name + ' = ' + toCode(o, name);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment