Last active
December 25, 2015 16:19
-
-
Save zakjan/7004850 to your computer and use it in GitHub Desktop.
Object.toSource
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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