I have a database object that has a field called workdays, it's a array boolean that contains 7 elements representing whether the user is active on the corresponding day.
I need to save this array into the database, I thought the bets way would be to convert the boolean array into a integer (bits) array and convert that into an integer which can be saved in the DB.
this is what I came up with, but I feel like I'm doing it the unnecessarily long way.
How can this be improved upon ?
function serializeDays(days: boolean[]): number {
// use (days || []) to avoid null pointer exception
// concat it with Array(7).fill(false) to fill in missing values
const d1 = (days || []).concat(Array(7).fill(false)).slice(0, 7);
// map the boolean values to int values
const d2 = d1.map(d => (d ? 1 : 0));
// join the array to string
const d3 = d2.join("");
// parse the string into base 10 from base 2
const n = parseInt(d3, 2);
return n;
}
function parseDays(days: number): boolean[] {
// use (days || 0) to avoid null pointer exception
// convert the base 10 integer into base 2
const d1 = (days || 0).toString(2);
// split the string into an array
// reverse it, concat it with Array(7).fill(0), reverse it again
// this is just to zerofill the array from the left side
const d2 = d1.split("").reverse().concat(Array(7).fill(0)).slice(0, 7).reverse();
// parse the values from strings to actual integers to boolean
const d3 = d2.map(d => (parseInt(d, 10) ? true : false));
return d3;
}
// monday to friday
serializeDays([true, true, true, true, true, false, false]); // outputs 124
parseDays(124); // outputs [true, true, true, true, true, false, false]
```