Convert boolean array to integer in Typescript 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 =&gt; (d ? 1 : 0));
        // join the array to string
        const d3 = d2.join(&quot;&quot;);
        // 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(&quot;&quot;).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 =&gt; (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]

```
Binary Math
Using string to do integer maths is very slow. You can use bitwise operators to encode and decode bit fields.
Encode bool array to int
The first function sets the low bit depending on the boolean. Each iteration the bits set are shifted to the left. The result is that the first array item is the highest bit (bit 7) and the last day is the lowest bit (bit 1)
Decode int to bool array
The second uses bitwise AND &amp; to mask out all but the bit position required and adds a boolean to an array depending on the state of the bit.


// high bit is first item in days eg 0b1000000 is day[0]
function serializeDays(days) { 
     return days.reduce((bin, day) =&gt; (bin &lt;&lt; 1) + (!!day), 0);
} 

function parseDays(bitField) {
     var bit = 7, days = [];
     while (bit) { days.push((bitField &amp; (1 &lt;&lt; --bit)) !== 0) }
     return days;
}
    
      
console.log(serializeDays([true,false,true,false,true,false,true]).toString(2));      
console.log(parseDays(0b1010101).join(","));