Home > database >  JavaScript : Altering a series every Nth time (start with 1 always)?
JavaScript : Altering a series every Nth time (start with 1 always)?

Time:01-23

I have a component <Card> which takes a parameter alter and renders the result based on the alter value.

If alter is 0 it renders in orange color and if alter is 1 it renders in blue color.

I am rendering results in grid as shown below:

Orange       Blue
Blue         Orange
Orange       Blue

My input function looks like this:

const getAlterParam = (index:number) => {
    return alter;
}

The function should behave like this:

input: 0 output: 1
input: 1 output: 0 [Negation of previous value] [Count = 1]
input: 2 output: 0 [Negation of first value] [Count = 2]
input: 3 output: 1 [Altering the value after N = 2] [Count = 1]
input: 4 output: 1 [Count = 2]
input: 5 output: 0 [Altering the value after N = 2] [Count = 1]
input: 6 output: 0 [Count = 2]
input: 7 output: 1 [Altering the value after N = 2] [Count = 1]
...

Here's what I tried:

let count = 0;
let alter = 1;
const getAlterParam = () => {
    count  ;
    if (count % 3 === 0) {
        alter = alter === 1 ? 0 : 1;
        count = 1;
    }
    return alter;
};

but the above code doesn't take index into consideration, it would generate the series when invoked in sequence. I need to link input and output somehow.

CodePudding user response:

Notice the pattern 1, 0, 0, 1 is repeating. We can use index modulus 4 to generate the pattern.

//assuming index is a non-negative integer
const getAlterParam = (index) => {
    return (index % 4 == 0 || index % 4 == 3) ? 1 : 0;
};
  • Related