Last active
March 18, 2018 04:06
-
-
Save diegolameira/ade3f8eb76d8759c296bb79cfb55f815 to your computer and use it in GitHub Desktop.
Binary Based Enum Read Sum
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 bingen(size) { | |
let c; | |
return Array.from({length: size}, (y, k) => c = (c||1) * 2); | |
} |
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
enum SuperTypes { | |
SUBSCRIBER = 2, | |
SPEAKER = 4, | |
MODERATOR = 8, | |
ADMIN = 16, | |
MASTER = 32, | |
} | |
const given = SuperTypes.SUBSCRIBER + SuperTypes.MODERATOR + SuperTypes.ADMIN + SuperTypes.MASTER; | |
const result = read(SuperTypes, given); | |
console.log(result); | |
/** | |
* Reads a given binary based Enum and a number then | |
* retrieves each enum that is part of the number | |
* @param _enum | |
* @param sum | |
* @returns [] | |
*/ | |
function read(_enum, sum: number) { | |
let next; | |
const found = []; | |
while ( sum > 0 ) | |
{ | |
next = findClosest(getEnumValues(_enum), sum); | |
sum = sum % next; | |
found.push(next); | |
} | |
return found.map(v => _enum[v]); | |
function findClosest(arr, x) { | |
return arr.reduce(function(prev, curr) { | |
return ( (Math.abs(curr - x) < Math.abs(prev - x) ) && curr <= x ? curr : prev); | |
}); | |
} | |
function getEnumValues(__enum) { | |
return Object.keys(__enum) | |
.filter(k => typeof __enum[k as any] !== "number") | |
.map(num => parseInt(num)); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment