Bitwise operator part 9

Is comming to an end! With this part, we’ll finish the logic and we’ll start the UI. This post is about checking the states, the rules and test if, given a specific state, it is allowed to do something when you consult the rule.

Our example has this states:

loaded:  1 (00000001)
playing: 2 (00000010)
paused:  4 (00000100)
stoped:  8 (00001000)

Example, the system has a rule named ‘canPlay’, and it tells that, it can play if the state is: loaded (1) or stoped (8) or paused (4), or, 1|4|8, which is 13 (00001101).

The app also has a rule named ‘canStop’, which is the Bitwise Or of these states: playing or pause, or, 2|4, whis is 6 (00000110).

Assuming the application status is loaded (1 or 00000001), it can play?

Can play while loaded?
00000001 < Current state (loaded)
00001101 < canPlay rule
--------
00000001 < 1, or, true

And about the rule canStop?

00000001 < Current state (loaded)
00000110 < canStop rule
--------
00000000 < 0, or, false

The checkRule method

The method basically receives a ruleName and:

  1. Retrieves the current state value;
  2. Retrieves the rule object by its name;
  3. Evaluates the current state and the rule value using the bitwise and operator.

Note that we are using the ‘toString base 2’ to log the value, so, it’ll be easy to you check the bitwise operator working!

It also important note that we are parsing the string returned to a JSON, since we store it as a string in the localStore.

During the posts, we explain all the details, so, at this time, reading the code below you’ll be able to understand what is going on!

checkRule(ruleName) {
    const currentStateValue = currentState.value;
    if (currentStateValue) {
      console.log(
        `currentStateValue is ${currentStateValue}, or`,
        currentStateValue.toString(2)
      );
    }

    const ruleObject = JSON.parse(lsManager.getObjectByKey(ruleName));
    if (ruleObject) {
      console.log(
        `ruleObject is ${ruleObject.value}, or`,
        ruleObject.value.toString(2)
      );
    }
    if (ruleObject.type !== 'rule') {
      throw new Error(`The '${ruleName}' is not a valid rule`);
    }

    if (currentStateValue && ruleObject.value) {
      console.log('checking result:', currentStateValue & ruleObject.value);
    }

    return Boolean(currentStateValue & ruleObject.value);
  }

Testing the method

This will be our last test without the interface! Let’s use the same code written in the previous post with slight modifications to invoke the checkRule method:

import { StateManager } from '../businessLogic/stateManager.js';

const sm = new StateManager();

sm.clearAllData();

sm.createState('MyFrstState');
sm.createState('MyScndState');
sm.createState('MyThrdState');

sm.createBitwiseOrRule('frstOrThrd', ['MyFrstState', 'MyThrdState']);

sm.currentState = 'MyFrstState';
console.log('Checking rule frstOrThrd:', sm.checkRule('frstOrThrd'));

sm.currentState = 'MyScndState';
console.log('Checking rule frstOrThrd:', sm.checkRule('frstOrThrd'));

You create the states and one rule, now it’s time to check is everything is working!

Debugging

On the line 13, we set the status (see image below) and on 14 we will invoke the checkRule method.

Step 01

In the method, note the rule name and the current state value.

Step 02

Now, the rule object is retrieved by its name and parsed to a JSON.

Step 03

Finally, the values are evaluated using the Bitwise And Operator and its result is returned as a boolean, in this case, the result is true!

Step 04
The retun is true

Now, we’ll change the current status to ‘MyScndState’ and invoke the checkRule again. This way, the return will be false, as the rules allows only the 1st and the 3rd!

Note the logs in the image below.

The retun is false

One more thing…

The method name ‘checkRule’ isn’t clear enough, so, let’s change it to ‘thisRulePermits(string ruleName)’. The usage will be easyer to read/understand:

“If this rule permits, do this!”

I think is better! What you think?

Happy coding!

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s