Skip to content

Instantly share code, notes, and snippets.

@jacob414
Created December 9, 2010 11:17
Show Gist options
  • Save jacob414/734620 to your computer and use it in GitHub Desktop.
Save jacob414/734620 to your computer and use it in GitHub Desktop.
Quick and dirty Javascript repr() function using CoffeeScript
repr = (o, depth=0, max=2) ->
if depth > max
'<..>'
else
switch typeof o
when 'string' then "\"#{o.replace /"/g, '\\"'}\""
when 'function' then 'function'
when 'object'
if o is null then 'null'
if _.isArray o
'[' + [''+repr(e, depth + 1, max) for e in o] + ']'
else
'{' + [''+k+':'+repr(o[k], depth + 1, max) for k in _.keys(o)] + '}'
when 'undefined' then 'undefined'
else o
@jacob414
Copy link
Author

jacob414 commented Jul 5, 2012

NB: Requires Underscore.js

@michaelficarra
Copy link

when 'string' then "\"#{o.replace /"/g, '\\"'}\""

@jacob414
Copy link
Author

jacob414 commented Jul 5, 2012

Ah, nice one! Integrated.

@collinanderson
Copy link

showing \n and \r in strings would be nice.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment