Skip to content

Instantly share code, notes, and snippets.

@zakjan
Last active December 25, 2015 16:19
Show Gist options
  • Save zakjan/7004850 to your computer and use it in GitHub Desktop.
Save zakjan/7004850 to your computer and use it in GitHub Desktop.
Object.toSource
var toSource = function (value) {
function show (value) {
if (_.isUndefined(value)) {
value = "undefined";
} else if (_.isFunction(value)) {
value = "" + value;
var indentMatches = value.match(/^ +/mg);
if (!_.isEmpty(indentMatches)) {
var indentSize = Math.min.apply(null, _.map(indentMatches, function (x) { return x.length; }));
value = value.replace(new RegExp("^ {" + indentSize + "}", "mg"), "");
}
} else if (_.isString(value)) {
value = '"' + value + '"';
} else if (_.isArray(value)) {
value = _.isEmpty(value) ? "[]" : "[\n" + _.map(value, show).join(",\n").replace(/^/mg, " ") + "\n]";
} else if (_.isObject(value)) {
value = _.isEmpty(value) ? "{}" : "{\n" + _.map(value, function (value, key) { return key + ": " + show(value); }).join(",\n").replace(/^/mg, " ") + "\n}";
}
return value;
}
return show(value);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment