Skip to content

Instantly share code, notes, and snippets.

@kyleshevlin
Created March 19, 2020 23:03
Show Gist options
  • Save kyleshevlin/39e4e213e2c057a97684b1b9c38ebcd1 to your computer and use it in GitHub Desktop.
Save kyleshevlin/39e4e213e2c057a97684b1b9c38ebcd1 to your computer and use it in GitHub Desktop.
getBooleanTable
const getBooleanTable = number => Array(Math.pow(2, number))
.fill()
.map((_, idx) => idx)
.map(num => num.toString(2).padStart(number, '0'))
.map(stringOfBits =>
stringOfBits.split('').map(bit => Boolean(parseInt(bit)))
)
console.log(getBooleanTable(3))
// [
// [false, false, false],
// [false, false, true],
// [false, true, false],
// [false, true, true],
// [true, false, false],
// [true, false, true],
// [true, true, false],
// [true, true, true]
// ]
@rcreasi
Copy link

rcreasi commented Mar 23, 2020

No need to use strings to manipulate bits. A few bitwise operators will do.
Programming in C for years before switching to JavaScript has finally paid off 😂

const getBooleanTable = number =>
  Array(Math.pow(2, number))
    .fill()
    .map((_, i) =>
      Array(number)
        .fill()
        .map((_, j) => Boolean((i >> j) & 1))
    )

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment