Bitwise operators part 10

Hey guys, it’s been a long time! I was too busy in my personal life, sorry! But, I’m on vacations, and I’ll finish this series, and I want to share with you more exciting things, and they will be shorter, I promise!

We almost finish the things on part 9! Let’s finish now and move on to the UI!

Finishing the stateManager.js

For our UI works appropriately, we must create more two methods in the state manager:

getStates()

If do you remember our UI, as soon as we create a new state, it will be displayed in a multi-select control, so, we need to retrieve all states.

To do this, we must retrieve the object, filter by its type and store it in an array.

function getItemsByType(type) {
  const localStorageObject = lsManager.getObject();
  let typeArray = [];
  for (const key in localStorageObject) {
    if (localStorageObject.hasOwnProperty(key)) {
      const element = JSON.parse(localStorageObject[key]);
      if (element.type === type.toLowerCase()) {
        const temp = {};
        temp.state = key;
        temp.value = element.value;
        typeArray.push(temp);
      }
    }
  }

  return typeArray;
}

Now, it’s pretty easy to return all states:

getStates() {
  return getItemsByType('state');
}

getRules()

It’s the exactly same situation! Let’s get the items by its type, but this time, we’ll pass ‘rule’ as argument.

getRules() {
  return getItemsByType('rule');
}

The final stateManager.js

This is the final code!

import { LocalStoreManager } from '../dataAccess/localStoreManager.js';

const currentState = { stateName: '', value: -1 };

const lsManager = new LocalStoreManager();

function getItemsByType(type) {
  const localStorageObject = lsManager.getObject();
  let typeArray = [];
  for (const key in localStorageObject) {
    if (localStorageObject.hasOwnProperty(key)) {
      const element = JSON.parse(localStorageObject[key]);
      if (element.type === type.toLowerCase()) {
        const temp = {};
        temp.state = key;
        temp.value = element.value;
        typeArray.push(temp);
      }
    }
  }

  return typeArray;
}

function nextValue() {
  let keys = lsManager.getKeys();
  const i = 1 << keys.length;
  return i;
}

export class StateManager {
  getStates() {
    return getItemsByType('state');
  }

  set currentState(stateName) {
    const keys = lsManager.getKeys();
    const i = keys.indexOf(stateName);
    if (i === -1) {
      throw new Error(`There is no state '${stateName}'`);
    }

    const stateObj = lsManager.getObject();
    const state = JSON.parse(stateObj[stateName]);

    if (state.type !== 'state') {
      throw new Error(`The '${stateName}' is not a valid state`);
    }

    console.log('previous state name', currentState);
    currentState.stateName = stateName;
    currentState.value = state.value;
    console.log('current state name', currentState);
  }

  get currentState() {
    return currentState;
  }

  createState(stateName) {
    lsManager.saveObject(
      stateName,
      JSON.stringify({ type: 'state', value: nextValue() }),
    );
  }

  createBitwiseOrRule(ruleName, stateArray) {
    let value = undefined;

    const lsObject = lsManager.getObject();
    stateArray.forEach(memberName => {
      const obj = JSON.parse(lsObject[memberName]);
      if (obj.type === 'state') {
        value = value | obj.value;
      }
    });

    lsManager.saveObject(ruleName, JSON.stringify({ type: 'rule', value }));
  }

  getRules() {
    return getItemsByType('rule');
  }

  clearAllData() {
    lsManager.clearData();
    currentState.stateName = '';
    currentState.value = -1;
  }

  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);
  }
}

Now, we finally are able to code the UI!

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