I want to preserve the undefined if pinned is actually undefined, otherwise, I want to set the value across the equals sign to 1 if pinned is true and 0 if it's false. I came up with this that works, but I keep looking at it and it seems like it should be simpler.
const resultingValue = pinned === undefined ? undefined : pinned ? 1 : 0;
What I'm wanting is:
if pinned is undefined, return undefined if pinned is true, return 1 if pinned is false, return 0 otherwise, return 0;
You could check type and return either a number of boolean or undefined.
const
resultingValue = typeof pinned === 'boolean'
? +pinned
: undefined;
Works for: true, false, undefined, 0, 1
const resultingValue = +pinned + 1 ? +pinned: undefined;
Use a lookup table for each value. The undefined can be omitted since it is going to produce undefined by default:
const lookup = {true: 1, false: 0};
const convert = value =>
lookup[value];
console.log(convert(true));
console.log(convert(false));
console.log(convert(undefined));
console.log(convert());
This can be shortened to a single function, if desired:
const convert = value =>
({true: 1, false: 0}[value]);
console.log(convert(true));
console.log(convert(false));
console.log(convert(undefined));
console.log(convert());