From 47a7468fa25f6a1c4edbfe6a436a39fc221506e3 Mon Sep 17 00:00:00 2001 From: Isaiah Odhner Date: Fri, 1 May 2015 19:02:52 -0400 Subject: [PATCH] Simplify module pattern, util, and improve existing error handling --- lib/cereal.js | 29 ++++++++++------------------- 1 file changed, 10 insertions(+), 19 deletions(-) diff --git a/lib/cereal.js b/lib/cereal.js index 4e3da80..ef1f5ed 100644 --- a/lib/cereal.js +++ b/lib/cereal.js @@ -1,4 +1,4 @@ -/*global exports */ +/*global module */ /*jslint browser: true, devel: true */ var Cereal; @@ -6,15 +6,9 @@ var Cereal; (function (window) { 'use strict'; - var util, cereal; - - util = (function () { - return { - isPrimitive: function (obj) { - return obj !== Object(obj); - } - }; - }()); + var isPrimitive = function (obj) { + return obj !== Object(obj); + }; (function () { var undef = 0, @@ -48,7 +42,7 @@ var Cereal; target[0] = undef; } else if (null === obj) { target[0] = nu; - } else if (util.isPrimitive(obj)) { + } else if (isPrimitive(obj)) { target[0] = prim; target[1] = obj; } else { @@ -123,18 +117,18 @@ var Cereal; case ref: target[field] = seen[item[3]]; if (target[field] === undefined) { - throw "Decoding error"; + throw new Error("Decoding error: referenced object not found"); } break; default: - throw "Decoding error"; + throw new Error("Decoding error: unhandled object type code " + item[2]); } } return root.value; }; - cereal = { + Cereal = { stringify: function (obj) { return JSON.stringify(jsonify(obj)); }, @@ -145,11 +139,8 @@ var Cereal; }; }()); - if (typeof exports === "undefined") { - Cereal = cereal; - } else { - exports.stringify = cereal.stringify; - exports.parse = cereal.parse; + if (typeof module !== "undefined") { + module.exports = Cereal; } }(this));