Khairul Habib
Khairul Habib

Reputation: 471

is there any simplest way to calculate a recurring day?

i have a recurring data that received from database in number format.

and i have checkbox which show day with this value:

[64, 32, 16, 8, 4, 2, 1] // monday to sunday

and this is how i redefined them into checklist so that i can show in checkbox.:

switch (recurring) {
        case 127:
          this.checkedList = [64, 32, 16, 8, 4, 2, 1];
          break;
        case 126:
          this.checkedList = [64, 32, 16, 8, 4, 2];
          break;
        case 125:
          this.checkedList = [64, 32, 16, 8, 4, 1];
          break;
        case......
        default:
          this.checkedList = [recurring];
      }

but i think that's not a good practice because it'll take long code to execute the result. is there any way i could transform it to be more simple?

Upvotes: 0

Views: 93

Answers (1)

user229044
user229044

Reputation: 239311

These are powers of two, meant to be used in a bit field.

You are meant to tell whether a given date is "checked" using bitwise operator &.

const SUNDAY   = 64; // 0100 0000
const SATURDAY = 32; // 0010 0000
const FRIDAY   = 16; // 0001 0000
const THURSDAY =  8; // 0000 1000
// etc.

let day = 48; // 0011 0000

day & SUNDAY   // 0 indicating Sunday should not be checked
day & SATURDAY // 32 indicating Saturday should be checked
day & FRIDAY   // 16 indicated Friday should be checked
day & THURSDAY // 0 indicated Thursday should not be checked

If you want to turn this into an array of checked values, the simplest option would be to stop using a bitfield an instead store a JSON array of strings.

Assuming that's not possible, your case statement can be replaced with something as simple as...

const DAYS = [ 1, 2, 4, 8, 16, 32, 64 ];

const dayBitfield = 41;

DAYS.filter(day => dayBitfield & day) // [1, 8, 32]

Upvotes: 1

Related Questions