-
-
Save ulidtko/7e0a30eb05fafe8d6fd274716283d85f to your computer and use it in GitHub Desktop.
A repr function for JS
This file contains hidden or 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
'use strict'; | |
/* Python-like repr() formatter for JS types, with recursion limit. */ | |
/* Adapted from https://gist.github.com/soapie/6407618 */ | |
function repr(x, max, depth) { | |
var ELIDED = "[..]"; | |
if (depth === undefined) depth = 0; | |
if (max === undefined) max = 2; | |
if (isPrim(x)) | |
return showPrim(x); | |
if (typeof x === 'function') | |
return 'function'; | |
if (Array.isArray(x)) | |
return showArray(x, depth, max); | |
if (x.constructor === Object) | |
return showObj(x, depth, max); | |
if (x.constructor === String) | |
return showPrim(x.toString()); | |
return x.toString(); | |
function isPrim(x) { | |
return x === null || /^[snbu]/.test(typeof x) | |
} | |
function showPrim(x) { | |
var t = typeof x; | |
if (t === 'string') | |
return JSON.stringify(x); | |
if (t === 'number' || t === 'boolean') | |
return x.toString(); | |
if (x === null) | |
return 'null'; | |
if (t === 'undefined') | |
return 'undefined'; | |
} | |
function showArray(arr, depth, max) { | |
if (depth >= max) return ELIDED; | |
var i, r = '['; | |
// for loop instead of forEach to correctly handle sparse arrays | |
for (i = 0; i < arr.length; i += 1) { | |
if (i !== 0) r += ', '; | |
// check if arr[i] is undefined... there's a distinction between | |
// arr[i] being set to undefined and not being set at all | |
if (arr.hasOwnProperty(i.toString())) { | |
r += repr(arr[i], depth + 1, max); | |
} | |
} | |
return r + ']' | |
} | |
function showObj(o, depth, max) { | |
if (depth >= max) return ELIDED; | |
var r = '{'; | |
Object.keys(o).forEach(function (key, ix) { | |
if (ix !== 0) r += ', '; | |
r += key + ': ' + repr(o[key], depth + 1, max); | |
}) | |
return r + '}' | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment