Skip to content

Instantly share code, notes, and snippets.

@passcod
Last active December 11, 2015 09:08
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save passcod/4577478 to your computer and use it in GitHub Desktop.
Save passcod/4577478 to your computer and use it in GitHub Desktop.
Gecko-style #toSource() shim
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 ", "}})"
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}}`
@passcod
Copy link
Author

passcod commented Jan 20, 2013

Failing with classes:

class A
  constructor: (@b) ->
    console.log 2

  privat = (c) -> 3
  public: (d) -> 4

test A
test new A 2
/** test A **/
// toSource2
(function A(b) {
    this.b = b;
    console.log(2);
  })

// toSource
function A(b) {
    this.b = b;
    console.log(2);
  }


/** test new A 2 **/
// toSource2
({b:2, public:(function (d) {
    return 4;
  })})

// toSource
({b:2})

But both get it wrong, so…?


For reference, this compiles to:

var A;

A = (function() {
  var privat;

  function A(b) {
    this.b = b;
    console.log(2);
  }

  privat = function(c) {
    return 3;
  };

  A.prototype["public"] = function(d) {
    return 4;
  };

  return A;

})();

test(A);
test(new A(2));

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