I have the following toy class to encapsulate some bitwise functions:
class BitOp {
static set(num) {
return num;
}
static shiftR(num, n=1) {
return num >> n;
}
static shiftL(num, n=1) {
return num << n;
}
static toBin(num) {
console.log(num, '>', num.toString(2));
return num;
}
}
const
set = BitOp.set,
shiftR = BitOp.shiftR,
shiftL = BitOp.shiftL,
toBin = BitOp.toBin;
toBin(shiftL(set(44), 2));
I would like to see if I can use the above function and perhaps add a wrapper around a variable that calls it so that it can be used alternately to chain to gether method calls, such as like:
new BitOp().set(44).shiftL(2).toBin(); // or new BitOp(44).shiftL...
I know I can write a separate class for it, such as the following but I'd like to use a more compact and interesting approach!
class BitOp {
set(num) {
this.num = num;
return this;
}
shiftR(n=1) {
this.num >>= n;
return this;
}
shiftL(n=1) {
this.num <<= n;
return this;
}
toBin() {
console.log(this.num, '>', this.num.toString(2));
return this;
}
}
new BitOp().set(44).shiftL(2).toBin();