A few useful applications of the Bitwise
operators.
Do you know further functions, using those operators ??
const Integer =
a =>
~~a
const even =
a =>
Boolean(~a & 1)
const double =
a =>
a << 1
const halve =
a =>
a >> 1
// Since Node 10, we're using Mocha.
// You can use `chai` for assertions.
const chai = require("chai");
const assert = chai.assert;
// Uncomment the following line to disable truncating failure messages for deep equals, do:
// chai.config.truncateThreshold = 0;
// Since Node 12, we no longer include assertions from our deprecated custom test framework by default.
// Uncomment the following to use the old assertions:
const Test = require("@codewars/test-compat")
const random =
min =>
max =>
Math.floor(Math.random() * (+max + 1 - +min)) + +min
const randomInts =
count =>
min =>
max =>
[..."0".repeat(count)].map(() => random(min)(max))
const _100Ints = randomInts(100)
describe("Applied Bitwise Operators", function() {
it("The Integer function should truncate Floats and just give back the integer part", function() {
Test.assertEquals(Integer(3.14159), 3)
Test.assertEquals(Integer(187.9876 + 99.04), 287)
Test.assertEquals(Integer(13 / 2), 6)
Test.assertEquals(Integer(69 / 12), 5)
})
it("The even function checks if an integer is divisible by 2", function() {
Test.assertEquals(even(0), true)
Test.assertEquals(even(1), false)
Test.assertEquals(even(2137), false)
Test.assertEquals(even(1334 ** 65), true)
})
it("Doubling, and then halving some number, should give back the initial value", function() {
_100Ints(Integer(Number.MIN_SAFE_INTEGER) - 1)(Integer(Number.MAX_SAFE_INTEGER) - 1)
.forEach(input => Test.assertEquals(halve(double(input)), input))
})
})