Chromium Code Reviews| Index: src/d8.js |
| diff --git a/src/d8.js b/src/d8.js |
| index 6a4ecb73304726203d037ddf38891a6bdb7a2fa1..0676fac2d7b05bcc83a153d6ca57c8500a8afa72 100644 |
| --- a/src/d8.js |
| +++ b/src/d8.js |
| @@ -2194,3 +2194,54 @@ function SimpleArrayToJSON_(array) { |
| json += ']'; |
| return json; |
| } |
| + |
| + |
| +// A more universal stringify that supports more types than JSON. |
| +// Used by the d8 shell to output results. |
| +var stringifyDepthLimit = 12; // To avoid crashing on cyclic objects |
|
Yang
2013/03/12 12:56:41
You could also use a stack to detect cycles.
rossberg
2013/03/18 14:03:07
I'd need an object set to do it properly, which I
|
| + |
| +function Stringify(x, depth) { |
| + if (depth === undefined) |
| + depth = stringifyDepthLimit; |
| + else if (depth === 0) |
| + return "*"; |
| + switch (typeof x) { |
| + case "undefined": |
| + return "undefined"; |
| + case "boolean": |
| + case "number": |
| + case "function": |
| + return x.toString(); |
| + case "string": |
| + return "\"" + x.toString() + "\""; |
| + case "object": |
| + if (x === null) return "null"; |
| + if (x.constructor.name === "Array") { |
| + var elems = []; |
| + for (var i = 0; i < x.length; ++i) { |
| + elems.push(x.hasOwnProperty(i) ? Stringify(x[i], depth - 1) : ""); |
|
Yang
2013/03/12 12:56:41
Would it make sense to try to avoid monkey-patched
rossberg
2013/03/18 14:03:07
There are many ways in which this code could break
|
| + } |
| + return "[" + elems.join(", ") + "]"; |
| + } |
| + if (String(x) !== "[object Object]") return String(x); |
| + var props = []; |
| + for (var name in x) { |
| + var desc = Object.getOwnPropertyDescriptor(x, name); |
| + if (desc === undefined) continue; |
| + if ("value" in desc) { |
| + props.push(name + ": " + Stringify(desc.value, depth - 1)); |
| + } |
| + if ("get" in desc) { |
| + var getter = desc.get.toString(); |
| + props.push("get " + name + getter.slice(getter.indexOf('('))); |
| + } |
| + if ("set" in desc) { |
| + var setter = desc.set.toString(); |
| + props.push("set " + name + setter.slice(setter.indexOf('('))); |
| + } |
| + } |
| + return "{" + props.join(", ") + "}"; |
| + default: |
| + return "[crazy non-standard shit]"; |
| + } |
| +} |