Skip to content

Instantly share code, notes, and snippets.

@diegolameira
Last active March 18, 2018 04:06
Show Gist options
  • Save diegolameira/ade3f8eb76d8759c296bb79cfb55f815 to your computer and use it in GitHub Desktop.
Save diegolameira/ade3f8eb76d8759c296bb79cfb55f815 to your computer and use it in GitHub Desktop.
Binary Based Enum Read Sum
function bingen(size) {
let c;
return Array.from({length: size}, (y, k) => c = (c||1) * 2);
}
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