Created
October 24, 2017 09:10
-
-
Save vesparny/b6322d7203ab56868ca3a5df89f61e9e to your computer and use it in GitHub Desktop.
bitwise JavaScript
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// how we calculate selectedDays | |
const days = _.range(0, 7).map((i) => { | |
return { | |
value: Math.pow(2, i) | |
} | |
}) | |
console.log(days) | |
const selectedDays = { | |
"1": true, // sunday | |
"2": true, // monday | |
"4": true, // tuesday | |
"8": true, // wednesday | |
"16": true, // thursday | |
"32": true, // friday | |
"64": true // saturday | |
} | |
function calculateValue () { | |
return Object.keys(selectedDays) | |
// filter out falsy values | |
.filter(el => selectedDays[el]) | |
// sum them up | |
.reduce((acc, val) => acc + Number(val), 0) | |
} | |
function createSelectedDaysObjectFromCalculatedValue(value) { | |
return _.range(0, 7).reduce((acc, val, i) => { | |
const dayValue = Math.pow(2, i) | |
acc[dayValue] = (value & dayValue) !== 0 | |
return acc | |
}, {}) | |
} | |
console.log( | |
'The calculated value is: ', | |
calculateValue() | |
) | |
console.log( | |
'The source object is: ', | |
createSelectedDaysObjectFromCalculatedValue(0) | |
) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment