Skip to content

Instantly share code, notes, and snippets.

@jacob414
Created December 9, 2010 11:17
Show Gist options
  • Select an option

  • Save jacob414/734620 to your computer and use it in GitHub Desktop.

Select an option

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

jacob414 commented Jul 5, 2012

Copy link
Copy Markdown
Author

NB: Requires Underscore.js

@michaelficarra

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

@jacob414

jacob414 commented Jul 5, 2012

Copy link
Copy Markdown
Author

Ah, nice one! Integrated.

@collinanderson

Copy link
Copy Markdown

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