vanilla_utility_query_index.js

/**
 * @module throttle
 * @description Converts an object to a url query string or vice-versa
 * @version 1.0.0
 * @param {object|string} object to encode or string to decode
 * @param {string} prefix for encoded string
 * @returns {object|string} returns encoded string or decoded object
 */

function encode(obj, pfx) {
	var k,
		i,
		tmp,
		str = ''

	for (k in obj) {
		if ((tmp = obj[k]) !== void 0) {
			if (Array.isArray(tmp)) {
				for (i = 0; i < tmp.length; i++) {
					str && (str += '&')
					str += encodeURIComponent(k) + '=' + encodeURIComponent(tmp[i])
				}
			} else {
				str && (str += '&')
				str += encodeURIComponent(k) + '=' + encodeURIComponent(tmp)
			}
		}
	}

	return (pfx || '') + str
}

function toValue(mix) {
	if (!mix) return ''
	var str = decodeURIComponent(mix)
	if (str === 'false') return false
	if (str === 'true') return true
	return +str * 0 === 0 ? +str : str
}

function decode(str) {
	var tmp,
		k,
		out = {},
		arr = str.split('&')

	while ((tmp = arr.shift())) {
		tmp = tmp.split('=')
		k = tmp.shift()
		if (out[k] !== void 0) {
			out[k] = [].concat(out[k], toValue(tmp.shift()))
		} else {
			out[k] = toValue(tmp.shift())
		}
	}

	return out
}

export function query(data, pfx) {
	return data.constructor === Object ? encode(data, pfx) : decode(data)
}