Skip to content

Instantly share code, notes, and snippets.

@ulidtko
Forked from soapie/repr.js
Last active October 29, 2023 12:22
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ulidtko/7e0a30eb05fafe8d6fd274716283d85f to your computer and use it in GitHub Desktop.
Save ulidtko/7e0a30eb05fafe8d6fd274716283d85f to your computer and use it in GitHub Desktop.
A repr function for JS
'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