UNPKG

jka-core

Version:

Library for working with Jedi Academy servers

56 lines (55 loc) 1.73 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.Bitfield = void 0; class Bitfield { constructor(num, size, keys) { let numBinaryString = num.toString(2); const dif = size - numBinaryString.length; if (dif) { numBinaryString = `${('0').repeat(dif)}${numBinaryString}`; } this._bits = numBinaryString.split('').map(x => x === '1'); this._keys = keys.concat().reverse(); } get decimal() { return parseInt(this._bits .map(x => x ? '1' : '0') .join(''), 2); } get binary() { return this._bits .map(x => x ? '1' : '0') .join(''); } get list() { return this._bits.reduce((acc, el, i) => (Object.assign(Object.assign({}, acc), { [this._keys[i]]: el })), {}); } /** * Sets key of bitfield to specific parameter * @param key The key which should be set * @param value The value which should be used for setting up * @returns True if succeed, false if there is no such key */ set(key, value) { const index = this._keys.findIndex((el) => el === key); if (index === -1) { return false; } else { this._bits[index] = value; return true; } } /** * Gets the current value of the key of the bitfield * @param key The key which should be taken * @returns The value of the key or null, if there is no such key */ get(key) { const index = this._keys.findIndex((el) => el === key); return index === -1 ? null : this._bits[index]; } } exports.Bitfield = Bitfield;