Today I Learned - Rocky Kev

TIL converting Booleans to Numbers

POSTED ON:

TAGS:

This helper is great for APIs. Not every language parses true/false the same. But every language knows that 0 is false, and 1 is true.

Boolean To Number

// helper
const booleanToNumber = (object) => {
for (const key in object) {
if (typeof object[key] === "boolean") {
object[key] = object[key] === false ? 0 : 1;
}
}

return object;
};

// example
const user = {
firstName: 'Jar Jar',
lastName: 'Binks',
isJedi: false,
isAlliance: true
}

console.log(booleanToNumber(user));
// {firstName: 'Jar Jar', lastName: 'Binks', isJedi: 0, isAlliance: 1}

Via
7 JavaScript Functions to Master Objects Manipulation and Make Your Code Cleaner


Related TILs

Tagged:

TIL converting Booleans to Numbers

This helper is great for APIs. Not every language parses true/false the same. But every language knows that 0 is false, and 1 is true.

TIL Avoiding dependencies in your helper functions

Impure functions for helpers? What is this... 1999?

TIL Avoiding dependencies in your helper functions

Impure functions for helpers? What is this... 1999?