querystring.stringify is now more solid

* handles NaN and Infinity
* works with arrays from other contexts
This commit is contained in:
Jan Kassens
2010-07-18 22:16:43 +02:00
committed by Ryan Dahl
parent eda1edd07f
commit bb2acd5e75
2 changed files with 21 additions and 30 deletions

View File

@@ -29,21 +29,22 @@ QueryString.stringify = QueryString.encode = function (obj, sep, eq, munge, name
munge = typeof munge == "undefined" || munge;
sep = sep || "&";
eq = eq || "=";
if (obj == null || typeof obj == "function") {
var type = Object.prototype.toString.call(obj);
if (obj == null || type == "[object Function]" || type == "[object Number]" && !isFinite(obj)) {
return name ? QueryString.escape(name) + eq : "";
}
if (isBool(obj)) {
obj = +obj;
}
if (isNumber(obj) || isString(obj)) {
return QueryString.escape(name) + eq + QueryString.escape(obj);
}
if (isA(obj, [])) {
name = name + (munge ? "[]" : "");
return obj.map(function (item) {
return QueryString.stringify(item, sep, eq, munge, name);
}).join(sep);
switch (type) {
case '[object Boolean]':
obj = +obj; // fall through
case '[object Number]':
case '[object String]':
return QueryString.escape(name) + eq + QueryString.escape(obj);
case '[object Array]':
name = name + (munge ? "[]" : "");
return obj.map(function (item) {
return QueryString.stringify(item, sep, eq, munge, name);
}).join(sep);
}
// now we know it's an object.
@@ -109,20 +110,3 @@ QueryString.parse = QueryString.decode = function (qs, sep, eq) {
});
return obj;
};
function isA (thing, 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 isA(thing, true);
}
function isNumber (thing) {
return isA(thing, 0) && isFinite(thing);
}
function isString (thing) {
return isA(thing, "");
}