qs-like
Version:
A tiny query string parsing and stringifying library
64 lines (55 loc) • 1.4 kB
JavaScript
/*
* qs-like.js v1.0.1
* (c) 2018-2019 Jesse Feng
* Released under the MIT License.
*/
;
var append = require('celia/_append');
var isObject = require('celia/isObject');
var forOwn = require('celia/_forOwn');
var _escape = require('./escape.js');
var stringify = JSON.stringify;
function convert(value, encode) {
switch (typeof value) {
case 'string':
return encode(value);
case 'number':
if (isNaN(value)) {
return '';
}
case 'boolean':
return value.toString();
case 'object':
return value === null ? '' : encode(stringify(value));
case 'undefined':
return '';
// case 'function':
// return encode(value.toString());
default:
return encode(value.toString());
}
}
var isArray = Array.isArray;
function stringify$1 (obj, sep, eq, options) {
if (isObject(obj)) {
sep = sep || '&';
eq = eq || '=';
options = options || {};
var encode = options.encodeURIComponent || _escape;
var arr = [];
forOwn(obj, function (value, key) {
if (key) {
if (isArray(value)) {
value.forEach(function (val) {
append(arr, key + eq + convert(val, encode));
});
} else {
append(arr, key + eq + convert(value, encode));
}
}
});
return arr.join(sep);
}
return '';
}
module.exports = stringify$1;