Repository URL to install this package:
|
Version:
1.1.10 ▾
|
function simpleAutofix(OBJ_TO_FIX) {
const isTruish = x =>
x === true || x === 'true' || (/^["|']?true["|']?$/).test(x)
const isFalsish = x =>
x === false || x === 'false' || (/^["|']?false["|']?$/).test(x)
const isBoolean = x => isFalsish(x) || isTruish(x)
function isNumberLike(x) {
if (typeof x === 'number') return true
if (/^0x[0-9a-f]+$/i.test(x) === true) return true
return (/^[-+]?(?:\d+(?:\.\d*)?|\.\d+)(e[-+]?\d+)?$/).test(x)
}
// @NOTE beginning & end tests on null are safety for server
const isNil = x =>
x === null ||
x === undefined ||
(/^["|']?null["|']?$/i).test(x) ||
(/undefined/i).test(x)
Object.keys(OBJ_TO_FIX).forEach(key => {
const value = OBJ_TO_FIX[key]
if (isBoolean(value)) {
OBJ_TO_FIX[key] = Boolean(value)
}
if (isNumberLike(value)) {
OBJ_TO_FIX[key] = Number(value)
}
if (isNil(value)) {
OBJ_TO_FIX[key] = undefined
}
})
}
function invariantAutofix() {
const simpleInput = {
stringToNumber: '1',
decimalToNumber: '10.10',
stringyToBoolean: 'true',
nullToUndefined: null,
quotedNullToUndefined: '"null"',
quotedToBoolean: '"true"',
}
simpleAutofix(simpleInput)
const simpleExpect = {
stringToNumber: 1,
decimalToNumber: 10.1,
stringyToBoolean: true,
nullToUndefined: undefined,
quotedNullToUndefined: undefined,
quotedToBoolean: true,
}
console.assert(
Object.keys(simpleExpect)
.map(key => simpleInput[key] === simpleExpect[key])
.every(Boolean) === true
)
}
invariantAutofix()
module.exports = simpleAutofix