Repository URL to install this package:
Version:
1.2.13 ▾
|
/**
* 1. @todo import from get or at least `get`
* 2. @todo this export should be a preset of exotic, used elsewhere
*/
import get from 'lodash/get'
import forOwn from 'lodash/forOwn'
import {
isNaN,
isNaN as isNotEhNumber,
toEmpty,
isEmpty,
isUndefined,
isNull,
EMPTY_STRING,
isNil,
isObj,
isArray,
isNumber,
isString,
toBoolean,
toString,
isSafeInteger,
toNumber,
toArray,
toObject,
isBoolean,
isFunction,
hasDecimals,
isBuiltIn,
// toFloat,
} from 'exotic'
const toFloat = (x: any): number => parseInt(x, 10)
/* eslint-disable max-statements */
function autofixComplex(response, fallbackValue = undefined) {
const coerced = toEmpty(response)
forOwn(response, (value, key) => {
// @todo fallback
coerced[key] = autofixTypes(value, get(response, key, ''))
})
if (isArray(response)) {
return toArray(coerced)
} else {
return toObject(coerced)
}
}
function autofixTypes(response, fallbackValue = undefined) {
if (isNil(response)) {
return ''
}
if (isBuiltIn(response)) {
return toEmpty(response)
}
if (isFunction(response)) {
return response
}
if (hasDecimals(response)) {
const asFloat = isSafeInteger(response) ? toFloat(response) : 0
if (isNaN(asFloat) && asFloat !== 0) {
return asFloat
} else if (response > 0) {
return response
} else {
return `${response}`
}
// return isSafeInteger(response) ? toFloat(response) : response || 0.00
}
if (isNumber(response)) {
return isSafeInteger(response as number)
? toNumber(response)
: `${response}`
// return toNumber(response)
}
if (isBoolean(response)) {
return toBoolean(response)
}
if (isString(response)) {
return `${response}`
// return toString(response)
}
if (isObj(response)) {
return autofixComplex(response, fallbackValue)
}
throw new TypeError('missing some data! ' + JSON.stringify(response))
}
// @todo could also clone...
function autofixSafe(response, fallbackValue = undefined) {
if (isNaN(response)) {
return -0
}
// main functionality here
if (isNull(response) || isUndefined(response)) {
return ''
}
if (isBuiltIn(response)) {
return toEmpty(response)
}
if (isFunction(response)) {
return response
}
// and if the number is low... beyond MAX_SAFE_INTEGER
// if (isNumber(response)) {
// return toNumber(response)
// }
if (isBoolean(response)) {
return toBoolean(response)
}
if (isString(response)) {
return `${response}`
// return toString(response)
}
if (isObj(response)) {
return autofixComplex(response, fallbackValue)
}
throw new TypeError('missing some data! ' + JSON.stringify(response))
}
export { autofixSafe }
export { autofixComplex, autofixTypes }
export { autofixTypes as autofix }
export default autofixTypes