-
Notifications
You must be signed in to change notification settings - Fork 27
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Merge pull request #9 from johan/stringify
A nicer CSON.stringify
- Loading branch information
Showing
5 changed files
with
313 additions
and
12 deletions.
There are no files selected for viewing
This file contains 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
This file contains 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
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,125 @@ | ||
/* | ||
Copyright (c) 2014, Groupon, Inc. | ||
All rights reserved. | ||
Redistribution and use in source and binary forms, with or without | ||
modification, are permitted provided that the following conditions | ||
are met: | ||
Redistributions of source code must retain the above copyright notice, | ||
this list of conditions and the following disclaimer. | ||
Redistributions in binary form must reproduce the above copyright | ||
notice, this list of conditions and the following disclaimer in the | ||
documentation and/or other materials provided with the distribution. | ||
Neither the name of GROUPON nor the names of its contributors may be | ||
used to endorse or promote products derived from this software without | ||
specific prior written permission. | ||
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS | ||
IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED | ||
TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A | ||
PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT | ||
HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, | ||
SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED | ||
TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR | ||
PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF | ||
LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING | ||
NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS | ||
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. | ||
*/ | ||
|
||
// Generated by CoffeeScript 2.0.0-beta8 | ||
module.exports = function (obj, visitor, indent) { | ||
var indentLine, indentLines, jsIdentifierRE, n, newlineWrap, serialize, tripleQuotesRE; | ||
if (typeof obj === 'undefined' || typeof obj === 'function') | ||
return; | ||
indent = function () { | ||
switch (typeof indent) { | ||
case 'string': | ||
return indent.slice(0, 10); | ||
case 'number': | ||
n = Math.min(indent, 10); | ||
if (!in$(n, [ | ||
1, | ||
2, | ||
3, | ||
4, | ||
5, | ||
6, | ||
7, | ||
8, | ||
9, | ||
10 | ||
])) | ||
n = 0; | ||
return Array(n + 1).join(' '); | ||
default: | ||
return 0; | ||
} | ||
}.call(this); | ||
if (!indent) | ||
return JSON.stringify(obj, visitor, indent); | ||
indentLine = function (line) { | ||
return indent + line; | ||
}; | ||
indentLines = function (str) { | ||
return str && str.split('\n').map(indentLine).join('\n'); | ||
}; | ||
newlineWrap = function (str) { | ||
return str && '\n' + str + '\n'; | ||
}; | ||
jsIdentifierRE = /^[a-z_$][a-z0-9_$]*$/i; | ||
tripleQuotesRE = new RegExp("'''", 'g'); | ||
obj = JSON.parse(JSON.stringify(obj, visitor)); | ||
return (serialize = function (obj) { | ||
var array, key, keypairs, object, string, val; | ||
switch (typeof obj) { | ||
case 'boolean': | ||
return obj + ''; | ||
case 'number': | ||
if (isFinite(obj)) { | ||
return obj + ''; | ||
} else { | ||
return 'null'; | ||
} | ||
case 'string': | ||
if (obj.indexOf('\n') === -1) { | ||
return JSON.stringify(obj); | ||
} else { | ||
string = obj.replace(tripleQuotesRE, "\\'''"); | ||
string = newlineWrap(indentLines(string)); | ||
return "'''" + string + "'''"; | ||
} | ||
case 'object': | ||
if (obj === null) { | ||
return 'null'; | ||
} else if (Array.isArray(obj)) { | ||
array = obj.map(serialize).join('\n'); | ||
array = newlineWrap(indentLines(array)); | ||
return '[' + array + ']'; | ||
} else { | ||
keypairs = function (accum$) { | ||
for (key in obj) { | ||
val = obj[key]; | ||
if (!key.match(jsIdentifierRE)) | ||
key = JSON.stringify(key); | ||
val = serialize(val); | ||
accum$.push('' + key + ': ' + val); | ||
} | ||
return accum$; | ||
}.call(this, []); | ||
object = keypairs.join('\n'); | ||
object = newlineWrap(indentLines(object)); | ||
return '{' + object + '}'; | ||
} | ||
} | ||
})(obj); | ||
}; | ||
function in$(member, list) { | ||
for (var i = 0, length = list.length; i < length; ++i) | ||
if (i in list && list[i] === member) | ||
return true; | ||
return false; | ||
} |
This file contains 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
This file contains 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
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,69 @@ | ||
# There are multiple ways to express the same thing in CSON, so trying to | ||
# make `CSON.stringify(CSON.parse(str)) == str` work is doomed to fail | ||
# but we can at least make output look a lot nicer than JSON.stringify's. | ||
module.exports = (obj, visitor, indent) -> | ||
return undefined if typeof obj in ['undefined', 'function'] | ||
|
||
# pick an indent style much as JSON.stringify does, but limited to cson legals | ||
indent = switch typeof indent | ||
when 'string' then indent.slice 0, 10 | ||
|
||
when 'number' | ||
n = Math.min indent, 10 | ||
n = 0 unless n in [1..10] # do not bail on NaN and similar | ||
Array(n + 1).join ' ' | ||
|
||
else 0 | ||
|
||
return JSON.stringify obj, visitor, indent unless indent | ||
|
||
indentLine = (line) -> indent + line | ||
|
||
indentLines = (str) -> | ||
str and str.split('\n').map(indentLine).join('\n') | ||
|
||
newlineWrap = (str) -> | ||
str and "\n#{ str }\n" | ||
|
||
jsIdentifierRE = /^[a-z_$][a-z0-9_$]*$/i | ||
tripleQuotesRE = new RegExp "'''", 'g' # some syntax hilighters hate on /'''/g | ||
|
||
# have the native JSON serializer do visitor transforms & normalization for us | ||
obj = JSON.parse JSON.stringify obj, visitor | ||
|
||
do serialize = (obj) -> | ||
switch typeof obj | ||
when 'boolean' then obj + '' | ||
|
||
when 'number' | ||
if isFinite obj | ||
obj + '' | ||
else # NaN, Infinity and -Infinity | ||
'null' | ||
|
||
when 'string' | ||
if obj.indexOf('\n') is -1 | ||
JSON.stringify obj | ||
else | ||
string = obj.replace tripleQuotesRE, "\\'''" | ||
string = newlineWrap indentLines string | ||
"'''#{ string }'''" | ||
|
||
when 'object' | ||
if obj is null | ||
'null' | ||
|
||
else if Array.isArray obj | ||
array = obj.map(serialize).join '\n' | ||
array = newlineWrap indentLines array | ||
"[#{ array }]" | ||
|
||
else | ||
keypairs = for key, val of obj | ||
key = JSON.stringify key unless key.match jsIdentifierRE | ||
val = serialize val | ||
"#{ key }: #{ val }" | ||
|
||
object = keypairs.join '\n' | ||
object = newlineWrap indentLines object | ||
"{#{ object }}" |
This file contains 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
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -1,8 +1,122 @@ | ||
|
||
assert = require 'assertive' | ||
{ equal } = require 'assertive' | ||
|
||
CSON = require '../' | ||
cson = (obj, visitor, space = 2) -> CSON.stringify obj, visitor, space | ||
|
||
describe 'CSON.stringify', -> | ||
it 'works just like JSON.stringify', -> | ||
assert.equal '{"a":"b"}', CSON.stringify(a: 'b') | ||
it 'handles null', -> | ||
equal 'null', cson null | ||
|
||
it 'handles boolean values', -> | ||
equal 'true', cson true | ||
equal 'false', cson false | ||
|
||
it 'handles the empty object', -> | ||
equal '{}', cson {} | ||
|
||
it 'handles the empty array', -> | ||
equal '[]', cson [] | ||
|
||
it 'handles numbers', -> | ||
equal '0.42', cson 0.42 | ||
equal '42', cson 42 | ||
equal '1.2e+90', cson 1.2e+90 | ||
|
||
it 'handles single-line strings', -> | ||
equal '"hello!"', cson 'hello!' | ||
|
||
it 'handles multi-line strings', -> | ||
equal """ | ||
''' | ||
I am your average multi-line string, | ||
and I have a sneaky \\''' in here, too | ||
''' | ||
""", cson """ | ||
I am your average multi-line string, | ||
and I have a sneaky ''' in here, too | ||
""" | ||
|
||
it 'handles arrays', -> | ||
equal ''' | ||
[ | ||
[ | ||
1 | ||
] | ||
null | ||
[] | ||
{ | ||
a: "str" | ||
} | ||
] | ||
''', cson [ [1], null, [], a: 'str' ] | ||
|
||
it 'handles objects', -> | ||
equal ''' | ||
{ | ||
"": "empty" | ||
"non\\nidentifier": true | ||
default: false | ||
nested: { | ||
string: "too" | ||
} | ||
array: [ | ||
{} | ||
[] | ||
] | ||
} | ||
''', cson { | ||
'': 'empty' | ||
"non\nidentifier": true | ||
default: false | ||
nested: { | ||
string: 'too' | ||
} | ||
array: [ | ||
{} | ||
[] | ||
] | ||
} | ||
|
||
it 'handles NaN and +/-Infinity like JSON.stringify does', -> | ||
equal 'null', cson NaN | ||
equal 'null', cson +Infinity | ||
equal 'null', cson -Infinity | ||
|
||
it 'handles undefined like JSON.stringify does', -> | ||
equal undefined, cson undefined | ||
|
||
it 'handles functions like JSON.stringify does', -> | ||
equal undefined, cson -> | ||
|
||
it 'works just like JSON.stringify when asking for no indentation', -> | ||
equal '{"zeroed":0}', cson zeroed: 0, null, 0 | ||
equal '{"empty":""}', cson empty: '', null, '' | ||
|
||
it 'accepts no more than ten indentation steps, just like JSON.stringify', -> | ||
equal ''' | ||
{ | ||
"don't": "be silly, will'ya?" | ||
} | ||
''', cson {"don't": "be silly, will'ya?"}, null, Infinity | ||
|
||
it 'lets people that really want to indent with tabs', -> | ||
equal ''' | ||
{ | ||
\t\t"super-tabby": true | ||
} | ||
''', cson {'super-tabby': yes}, null, '\t\t' | ||
|
||
it 'is bug compatible with JSON.stringify for non-whitespace indention', -> | ||
equal ''' | ||
{ | ||
ecma-262strange: true | ||
} | ||
''', cson {strange: yes}, null, 'ecma-262' | ||
|
||
it 'handles visitor functions', -> | ||
equal ''' | ||
{ | ||
keep: 1 | ||
} | ||
''', cson {filter: 'me', keep: 1}, (k, v) -> v unless typeof v is 'string' |