Refactored isA, isBool, etc functions to use some of ES5 goodness.
authorDmitry Baranovskiy <Dmitry@Baranovskiy.com>
Mon, 28 Jun 2010 01:57:11 +0000 (11:57 +1000)
committerRyan Dahl <ry@tinyclouds.org>
Wed, 30 Jun 2010 02:22:28 +0000 (19:22 -0700)
lib/querystring.js

index eb415bc..e3b75ba 100644 (file)
@@ -26,10 +26,10 @@ var stack = [];
  * @static
  */
 QueryString.stringify = QueryString.encode = function (obj, sep, eq, munge, name) {
-  munge = typeof(munge) == "undefined" ? true : munge;
+  munge = typeof(munge) == "undefined" || munge;
   sep = sep || "&";
   eq = eq || "=";
-  if (isA(obj, null) || isA(obj, undefined) || typeof(obj) === 'function') {
+  if (obj == null || typeof(obj) === 'function') {
     return name ? QueryString.escape(name) + eq : '';
   }
 
@@ -75,7 +75,7 @@ QueryString.parse = QueryString.decode = function (qs, sep, eq) {
   return (qs || '')
     .split(sep||"&")
     .map(pieceParser(eq||"="))
-    .reduce(mergeParams)
+    .reduce(mergeParams);
 };
 
 // Parse a key=val string.
@@ -127,7 +127,7 @@ function mergeParams (params, addition) {
     // else merge them as objects, which is a little more complex
     : mergeObjects(params, addition)
   );
-};
+}
 
 // Merge two *objects* together. If this is called, we've already ruled
 // out the simple cases, and need to do a loop.
@@ -140,34 +140,21 @@ function mergeObjects (params, addition) {
     }
   }
   return params;
-};
+}
 
-// duck typing
 function isA (thing, canon) {
-  return (
-    // truthiness. you can feel it in your gut.
-    (!thing === !canon)
-    // typeof is usually "object"
-    && typeof(thing) === typeof(canon)
-    // check the constructor
-    && Object.prototype.toString.call(thing) === Object.prototype.toString.call(canon)
-  );
-};
+    // special case for null and undefined
+    if (thing == null || canon == null) {
+        return thing === canon;
+    }
+    return Object.getPrototypeOf(Object(thing)) == Object.getPrototypeOf(Object(canon));
+}
 function isBool (thing) {
-  return (
-    typeof(thing) === "boolean"
-    || isA(thing, new Boolean(thing))
-  );
-};
+    return isA(thing, true);
+}
 function isNumber (thing) {
-  return (
-    typeof(thing) === "number"
-    || isA(thing, new Number(thing))
-  ) && isFinite(thing);
-};
+    return isA(thing, 0) && isFinite(thing);
+}
 function isString (thing) {
-  return (
-    typeof(thing) === "string"
-    || isA(thing, new String(thing))
-  );
-};
+    return isA(thing, "");
+}