Skip to content

Instantly share code, notes, and snippets.

@supasympa
Created December 18, 2020 14:50
Show Gist options
  • Save supasympa/c130c7bd0ef8c5c0950b5cfb8627a68d to your computer and use it in GitHub Desktop.
Save supasympa/c130c7bd0ef8c5c0950b5cfb8627a68d to your computer and use it in GitHub Desktop.
binary-serialisation - some thoughts for feature flags
const reg = {
foo: true,
bar: false,
qux: true,
wc_123:true,
new_feature:true
};
function dec2bin(dec){
return (dec >>> 0).toString(2);
}
function bin2arr(bin/*:string*/){
return bin.split('').map(v => v==='1')
}
function bin2num(bin/*:string*/){
return parseInt( bin, 2 );
}
// console.log(dec2bin(999999999).split('').map(v => v==='1'));
// console.log(bin2num('111111111111111111111111111111'));
const register2bin = (register/*: {[key:string]:boolean} */) => {
return Object.values(register).map((value) => value? 1:0).join('');
}
console.log(register2bin(reg));
console.log(bin2num(register2bin(reg)));
const bin2register = (bin/*:string*/, keys) => {
return bin.split('').reduce((a, n, i) => { return {...a, ...{ [keys[i]]:(n==='1') } }; }, {});
}
console.log(bin2register('11111', Object.keys(reg)));
console.log(bin2register(dec2bin(23), Object.keys(reg)));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment