Last active
December 11, 2015 09:08
-
-
Save passcod/4577478 to your computer and use it in GitHub Desktop.
Gecko-style #toSource() shim
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
toSource2 = (data) -> | |
typ = typeof data | |
if typ == "number" and isNaN data | |
"NaN" | |
else if ["string", "number", "boolean"].indexOf(typ) != -1 | |
JSON.stringify data | |
else if typ == "function" | |
"(#{data.toString()})" | |
else if data instanceof Array | |
"[#{data.map(toSource2).join(", ")}]" | |
else if data == null | |
"null" | |
else if data instanceof RegExp | |
data.toString() | |
else if data instanceof Date | |
"(new Date(#{+data}))" | |
else if data instanceof Object | |
ret = [] | |
for k,v of data | |
ret.push "#{k}:#{toSource2 v}" | |
if ret.length == 0 and JSON.stringify(data) != "{}" | |
data.toString() | |
else | |
"({#{ret.join ", "}})" |
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
test = (data, s2) -> | |
s1 = toSource2(data) | |
s2 ||= data.toSource() | |
vv = s1 == s2 | |
if vv | |
console.info "Passed: #{data}" | |
else | |
console.warn "Failed: #{data}" | |
console.log s1 | |
console.log s2 | |
# Tests | |
console.clear() | |
test "string", '"string"' | |
test 12345, "12345" | |
test true, "true" | |
test false, "false" | |
test "", '""' | |
test 0, "0" | |
test 0/0, "NaN" | |
test [] | |
test [1,2,3] | |
test [false, NaN, null] | |
test [true, 1] | |
test ["abcd", "efgh"] | |
test /abcd/ig | |
test new Date | |
test {} | |
test {a:1} | |
test {length:2} | |
test {a:2,b:"c",d:true,e:false} | |
test (a) -> b() | |
test `function a(b) {{a:2}}` |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Failing with classes:
But both get it wrong, so…?
For reference, this compiles to: