UNPKG

isaacscript-common

Version:

Helper functions and features for IsaacScript mods.

83 lines (82 loc) 2.72 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.arrayToBitFlags = arrayToBitFlags; exports.convertBinaryToDecimal = convertBinaryToDecimal; exports.convertDecimalToBinary = convertDecimalToBinary; exports.countSetBits = countSetBits; exports.getKBitOfN = getKBitOfN; exports.getNumBitsOfN = getNumBitsOfN; exports.setToBitFlags = setToBitFlags; const flag_1 = require("./flag"); const types_1 = require("./types"); const utils_1 = require("./utils"); /** Helper function to convert a set of flags to a single `BitFlags` object. */ function arrayToBitFlags(array) { let flags = 0; for (const flag of array) { flags = (0, flag_1.addFlag)(flags, flag); } return flags; } /** Helper function to convert an array of bits to the resulting decimal number. */ function convertBinaryToDecimal(bits) { const bitsString = bits.join(""); return Number.parseInt(bitsString, 2); } /** * Helper function to convert a number to an array of bits. * * @param num The number to convert. * @param minLength Optional. Equal to the minimum amount of bits that should be returned. If the * converted number of bits is below this number, 0's will be padded to the left * side until the minimum length is met. Default is undefined (which will not cause * any padding). */ function convertDecimalToBinary(num, minLength) { const bits = []; const bitsString = num.toString(2); for (const bitString of bitsString) { const bit = (0, types_1.parseIntSafe)(bitString); (0, utils_1.assertDefined)(bit, `Failed to convert the following number to binary: ${num}`); bits.push(bit); } if (minLength !== undefined) { while (bits.length < minLength) { bits.unshift(0); } } return bits; } /** * Helper function to count the number of bits that are set to 1 in a binary representation of a * number. */ function countSetBits(num) { let count = 0; while (num > 0) { num &= num - 1; count++; } return count; } /** Helper function to get the value of a specific but in a binary representation of a number. */ function getKBitOfN(k, n) { return (n >>> k) & 1; } /** Helper function to get the number of bits in a binary representation of a number. */ function getNumBitsOfN(n) { let numBits = 0; while (n > 0) { numBits++; n >>>= 1; } return numBits; } /** Helper function to convert a set of flags to a single `BitFlags` object. */ function setToBitFlags(set) { let flags = 0; for (const flag of set) { flags = (0, flag_1.addFlag)(flags, flag); } return flags; }