Repository URL to install this package:
|
Version:
5.0.2 ▾
|
import qs from 'query-string'
import { isNil, isString, isArray, isObj } from 'exotic'
import { stringify } from 'chain-able-lego'
const MATCH_NON_ALPHANUMERIC = /\w+/gim
const stripNonAlphaNumeric = (x: string | any): string => {
if (isString(x)) {
return x.replace(MATCH_NON_ALPHANUMERIC, '')
} else {
return ''
}
}
// @todo 1 for component 1 for uri
// (uri is for absolute url, component is for parts of url)
function isURIEncoded(x: any = ''): x is string {
if (isString(x) === false) {
return false
}
const decoded = decodeURIComponent(x)
if (decoded === x) {
return false
} else {
return true
}
}
/**
* @todo one of the final todos is `{}` around nested objects
*/
function fromObjToStringifiedWithoutQuotes(to, first = true) {
// const stringified = stringify(to)
// const withoutQuotes = stringified.replace(/\"([^(\")"]+)\":/g, '$1:')
// recursive tail call object serialization according to JSON standard
// ...but without quotes around the keys
const IS_ARRAY = isArray(to)
const separator = first === true ? '=' : ':'
// top level entries should be & for routing, nested is for parsing
const symbol = IS_ARRAY || first === false ? ',' : '&'
const result = Object.keys(to)
.map(key => {
// prevent going too deep
const value =
first === false
? // @todo if not primitive at not top value...
// @example if this is bool don't want stringy bool
stringify(to[key])
: // only serialize objects
isObj(to[key])
? fromObjToStringifiedWithoutQuotes(to[key], false)
: to[key]
return IS_ARRAY === true || isNil(value) || isNil(to[key])
? value
: `${key}${separator}${value}`
})
.filter(value => value !== undefined)
.join(symbol)
if (IS_ARRAY === true) {
return `[${result}]`
} else if (first === false) {
return `{${result}}`
} else {
return result
}
}
// @note - this slices first and last off
// fromObjToGoodLookingParams
function goodLookingStringify(to) {
if (isObj(to) === false) {
return qs.stringify(to)
}
// const stringified = stringify(to).replace(/\\/gmi, '')
const stringified = fromObjToStringifiedWithoutQuotes(to)
// [eh] => eh
// {eh: []} => eh: []
// ...
// @note - this ends up making it insane
// const prettier = stringified.slice(1, stringified.length - 1)
// console.log('___goodLookingStringify___', prettier)
// return prettier
return stringified
// return qs.stringify(prettier)
// return fromObjToSearchParamsString(to)
// return fromObjToStringifiedWithoutQuotes(to)
}
/**
* @todo @perf @dedupe
* @description how many times have I/anyone written this
*/
const parseJSON = (x: string): any => {
try {
const parsed = JSON.parse(x)
return parsed
} catch (syntaxException) {
return x
}
}
export { parseJSON, stripNonAlphaNumeric, isURIEncoded, goodLookingStringify }