From 6ca19ad0cd01458053f4d3371a6037629ecf88ec Mon Sep 17 00:00:00 2001 From: Sami Samhuri Date: Sun, 29 May 2011 23:47:10 -0700 Subject: [PATCH] update repr --- lib/repr.js | 55 +++++++++++++++++++++++++++++++++-------------------- 1 file changed, 34 insertions(+), 21 deletions(-) diff --git a/lib/repr.js b/lib/repr.js index c92a566..c6f6d97 100644 --- a/lib/repr.js +++ b/lib/repr.js @@ -2,32 +2,45 @@ // Copyright 2010 - 2011 Sami Samhuri // readable string representations of values -exports.repr = function(x) { - if (x !== null && x !== undefined && typeof x.repr === 'function') return x.repr(); +exports.repr = repr; - if (x === null || x === undefined || - x instanceof Number || typeof x === 'number' || - x instanceof Boolean || typeof x === 'boolean' || - x instanceof RegExp || x.constructor === RegExp) - { - return String(x); - } +function repr(x) { + if (x !== null && x !== undefined && typeof x.repr === 'function') return x.repr(); - if (x instanceof String || typeof x === 'string') - return '"' + x.replace(/"/g, '\\"') + '"'; + var nativeToStringIsReadable = + x === null + || x === undefined + || x instanceof Number + || typeof x === 'number' + || x instanceof Boolean + || typeof x === 'boolean' + || x instanceof RegExp + || x.constructor === RegExp; - if (x instanceof Date || x.toUTCString) - return 'new Date(' + (+x) + ')'; // lame + if (nativeToStringIsReadable) { + return String(x); + } - if (Array.isArray(x)) - return '[' + x.map(repr).join(',') + ']'; + if (x instanceof String || typeof x === 'string') { + return '"' + x.replace(/"/g, '\\"') + '"'; + } - if (x instanceof Function || typeof x === 'function') - return x.toString(); + if (x instanceof Date || x.toUTCString) { + return 'new Date(' + (+x) + ')'; // lame + } - // TODO determine how far to go with this. should we include non-enumerable props too? - if (x instanceof Object || typeof x === 'object') - return '{' + Object.keys(x).map(function(k) { return repr(k) + ':' + repr(x[k]); }).join(',') + '}'; + if (Array.isArray(x)) { + return '[' + x.map(repr).join(',') + ']'; + } - throw new Error("don't know how to represent " + x); + if (x instanceof Function || typeof x === 'function') { + return x.toString(); + } + + // TODO determine how far to go with this. should we include non-enumerable props too? + if (x instanceof Object || typeof x === 'object') { + return '{' + Object.keys(x).map(function(k) { return repr(k) + ':' + repr(x[k]); }).join(',') + '}'; + } + + throw new Error("don't know how to represent " + x); };