normalify
Version:
Normalize different variable value types - e.g. `"1"` becomes `1`
64 lines (63 loc) • 1.76 kB
JavaScript
;
/* eslint no-use-before-define:0 */
Object.defineProperty(exports, "__esModule", { value: true });
exports.normalifyString = exports.normalifyObject = void 0;
/**
* Convert the input from its source type into its actual type
* @param input
*/
function normalify(input) {
const result = normalifyObject(input);
if (result !== input)
return result;
return normalifyString(input);
}
exports.default = normalify;
/**
* Convert the input object and its nested values into their actual types
* @param input
*/
function normalifyObject(input) {
if (typeof input === 'object') {
for (const key in input) {
if (input.hasOwnProperty(key)) {
const value = input[key];
const result = normalify(value);
// http://jsperf.com/pre-check
if (result !== value) {
input[key] = result;
}
}
}
}
return input;
}
exports.normalifyObject = normalifyObject;
/**
* Convert the input from its source type into its actual type
* @param input
*/
function normalifyString(input) {
if (typeof input === 'string') {
if (input === 'NaN' || input === '"NaN"' || input === "'NaN'") {
return NaN;
}
try {
if (input.startsWith("'") && input.endsWith("'")) {
input = '"' + input.slice(1, -1) + '"';
}
const result = JSON.parse(input);
if (result !== input) {
return normalify(result);
}
return result;
}
catch (err) {
return input;
}
}
else {
return input;
}
}
exports.normalifyString = normalifyString;