UNPKG

jsedn

Version:

js implementation of edn

128 lines (120 loc) 2.97 kB
// Generated by CoffeeScript 1.6.1 (function() { var encode, encodeHandlers, encodeJson, tokenHandlers, type; type = require("./type"); tokenHandlers = require("./tokens").tokenHandlers; encodeHandlers = { array: { test: function(obj) { return type(obj) === "array"; }, action: function(obj) { var v; return "[" + (((function() { var _i, _len, _results; _results = []; for (_i = 0, _len = obj.length; _i < _len; _i++) { v = obj[_i]; _results.push(encode(v)); } return _results; })()).join(" ")) + "]"; } }, integer: { test: function(obj) { return type(obj) === "number" && tokenHandlers.integer.pattern.test(obj); }, action: function(obj) { return parseInt(obj); } }, float: { test: function(obj) { return type(obj) === "number" && tokenHandlers.float.pattern.test(obj); }, action: function(obj) { return parseFloat(obj); } }, string: { test: function(obj) { return type(obj) === "string"; }, action: function(obj) { return "\"" + (obj.toString().replace(/"|\\/g, '\\$&')) + "\""; } }, boolean: { test: function(obj) { return type(obj) === "boolean"; }, action: function(obj) { if (obj) { return "true"; } else { return "false"; } } }, "null": { test: function(obj) { return type(obj) === "null"; }, action: function(obj) { return "nil"; } }, date: { test: function(obj) { return type(obj) === "date"; }, action: function(obj) { return "#inst \"" + (obj.toISOString()) + "\""; } }, object: { test: function(obj) { return type(obj) === "object"; }, action: function(obj) { var k, result, v; result = []; for (k in obj) { v = obj[k]; result.push(encode(k)); result.push(encode(v)); } return "{" + (result.join(" ")) + "}"; } } }; encode = function(obj) { var handler, name; if ((obj != null ? obj.ednEncode : void 0) != null) { return obj.ednEncode(); } for (name in encodeHandlers) { handler = encodeHandlers[name]; if (handler.test(obj)) { return handler.action(obj); } } throw "unhandled encoding for " + (JSON.stringify(obj)); }; encodeJson = function(obj, prettyPrint) { if (obj.jsonEncode != null) { return encodeJson(obj.jsonEncode(), prettyPrint); } if (prettyPrint) { return JSON.stringify(obj, null, 4); } else { return JSON.stringify(obj); } }; module.exports = { encodeHandlers: encodeHandlers, encode: encode, encodeJson: encodeJson }; }).call(this);