Skip to content

Instantly share code, notes, and snippets.

@cabb
Created April 12, 2024 14:27
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save cabb/eea8a67e87a2b81b369aaf93a793c67b to your computer and use it in GitHub Desktop.
Save cabb/eea8a67e87a2b81b369aaf93a793c67b to your computer and use it in GitHub Desktop.
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