Created
April 12, 2024 14:27
-
-
Save cabb/eea8a67e87a2b81b369aaf93a793c67b to your computer and use it in GitHub Desktop.
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
function bitwiseMapTo(valueMap, key) { | |
if (!Array.isArray(valueMap) || typeof key !== 'number' || isNaN(key)) { | |
return null; | |
} | |
// why loop is used: because it has to be an ordered list for bitwise compare | |
let length = valueMap.length; | |
for (let i = 0; i < length; i++) { | |
const item = valueMap[i]; | |
// Ensure item has at least two elements and the bitwise comparison holds | |
if (item.length > 1 && (item[0] & key) === item[0]) { | |
return item[1]; | |
} | |
} | |
return null; | |
} | |
// Example usage | |
const statusMap = [ | |
[0x08, "Error State"], // This bit (0x08) must be checked first; highest priority. | |
[0x04, "Network Connected"], | |
[0x02, "Passed Self-Tests"], | |
[0x01, "Powered On"] // This is the lowest priority state. | |
]; | |
const result = bitwiseMapTo(statusMap, 0x05); | |
console.log(result); // Expected output: "Network Connected" |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment