JSFiddle - React, Tailwind, and code Playground
JavaScript
const toInt = (val) => parseInt(val, 10);
const toBool = (val) => val === "true";
const toString = (val) => val;
const OPTIONS = [
{
name: 'width',
default: 2,
convert: toInt,
},
{
name: 'format',
default: 'auto',
convert: toString,
},
{
name: 'flat',
default: false,
convert: toBool,
},
];
const DEFAULTS = {};
const OPTIONS_MAP = new Map(OPTIONS.map(param => {
DEFAULTS[param.name] = param.default;
return [param.name, param];
}));
const test = {
width: '4',
format: 'CODE128',
flat: 'true',
};
function optionsFromStrings(options) {
Object.keys(options).forEach(key => {
const opt = OPTIONS_MAP.get(key);
if (opt && opt.convert) {
options[key] = opt.convert(options[key]);
}
});
return options;
}
console.log(optionsFromStrings(test));