Home > Back-end >  Repeat same numbers after particular number
Repeat same numbers after particular number

Time:12-20

I have a logic like user gives a date. I compare with current date and calculate the difference. According the difference, I send back them a message. I have set of 4 messages. If the difference is 1 then I send 1st message from set of 4. My confusion is, If the difference is 5 then it should send 1st message, if difference is 6 then it should send 2nd message. Because I have only 4 messages. Basically I'm trying to create a method where I give 5 as parameter and I give back 1 as result. Give 6 and get 2 and it goes on.

Code

var userDate;
var todayDate = new Date();
var diff = moment.duration(moment(userDate).diff(moment(todayDate)));
if(diff > 4){
   diff = 1;
}

This logic didn't worked out for me. Please help me out.

CodePudding user response:

Simplest option is the remainder operator:

function getDiff(num) {
  return num % 5
}

Or the same but more verbose:

function getDiff(num) {
  return num - (Math.floor(num/5) * 5)
}
  • Related