import isPlainObject from 'lodash.isplainobject';
import isFunction from 'lodash.isfunction';
import { default as isArray } from './is-array';
function safe(fn) {
return function () {
var args = [];
for (var _i = 0; _i < arguments.length; _i++) {
args[_i] = arguments[_i];
}
try {
// tslib 不支持
// eslint-disable-next-line prefer-spread
return fn.apply(null, args);
}
catch (error) {
return args[0];
}
};
}
function stringifyPrimitive(v) {
if (typeof v === 'string')
return v;
if (typeof v === 'number' && isFinite(v))
return v;
if (typeof v === 'boolean')
return v ? 'true' : 'false';
if (typeof v === 'object')
return JSON.stringify(v);
return '';
}
/**
* 将对象转换成 query string
*
* @param {object} obj 需要序列化成 URL query string 的对象。属性值支持数组。
* @param {string} sep 用于界定键值对的子字符串。默认为 '&'
* @param {string} eq 用于界定 key 和 value 的子字符串。默认为 '='
* @param {object} options 自定义编码行为
* @param {function} options.encodeURIComponent 用于自定义的 encodeURIComponent
* @returns {string}
*
* @example
*
* stringify({})
* // => ''
*
* stringify({key: 'value', undef: undefined })
* // => 'key=value&undef='
*/
function stringify(obj, options) {
if (options === void 0) { options = {}; }
if (!isPlainObject(obj)) {
return '';
}
var _a = options || {}, _b = _a.sep, sep = _b === void 0 ? '&' : _b, _c = _a.eq, eq = _c === void 0 ? '=' : _c;
var encode = safe(encodeURIComponent);
if (options && isFunction(options.encodeURIComponent)) {
// @ts-ignore TODO:
encode = safe(options.encodeURIComponent);
}
var keys = Object.keys(obj);
var len = keys.length;
var fields = '';
for (var i = 0; i < len; i++) {
var k = keys[i];
var v = obj[k];
var ks = encode(stringifyPrimitive(k));
ks += eq;
if (isArray(v)) {
var vlen = v.length;
if (vlen === 0)
continue;
for (var j = 0; j < vlen; j++) {
fields += ks;
fields += encode(stringifyPrimitive(v[j]));
if (j < vlen - 1) {
fields += sep;
}
}
}
else {
fields += ks;
fields += encode(stringifyPrimitive(v));
}
if (i < len - 1) {
fields += sep;
}
}
return fields;
}
export default stringify;
//# sourceMappingURL=stringify.js.map