param-serializer.js

/**
 * @function modules:Util#serialize
 * @param  {object} a a javascript object
 * @return {string} the jquery-like querystring to send to the api
 * @description
 *   Ripped from https://github.com/knowledgecode/jquery-param
 */

/* istanbul ignore next */
function serialize(a) {
	const s = [];
	const rbracket = /\[\]$/;
	const isArray = function(obj) {
		return Object.prototype.toString.call(obj) === '[object Array]';
	};

	function add(k, v) {
		v = typeof v === 'function' ? v() : v === null ? '' : v === undefined ? '' : v;
		s[s.length] = encodeURIComponent(k) + '=' + encodeURIComponent(v);
	}

	function buildParams(prefix, obj) {
		let i;
		let len;
		let key;

		if (prefix) {
			if (isArray(obj)) {
				for (i = 0, len = obj.length; i < len; i++) {
					if (rbracket.test(prefix)) {
						add(prefix, obj[i]);
					} else {
						buildParams(prefix + '[' + (typeof obj[i] === 'object' ? i : '') + ']', obj[i]);
					}
				}
			} else if (obj && String(obj) === '[object Object]') {
				for (key in obj) {
					buildParams(prefix + '[' + key + ']', obj[key]);
				}
			} else {
				add(prefix, obj);
			}
		} else if (isArray(obj)) {
			for (i = 0, len = obj.length; i < len; i++) {
				add(obj[i].name, obj[i].value);
			}
		} else {
			for (key in obj) {
				buildParams(key, obj[key]);
			}
		}
		return s;
	}

	return decodeURIComponent(buildParams('', a).join('&').replace(/%20/g, '+'));
}

module.exports = serialize;