user1641831
user1641831

Reputation:

If statements with arithmetic progressions in Jquery

I have an if statement whose outcome depends on the length of an array.

At this time I have created a very rough formula that takes care of that in an extremely limited range of numbers (in other words, if the length of the array does not exceed a specific value). However, I would like to rephrase the function and make it scalable.

This is the current code:

var footerLength;
var footerLengthData = employees.length;

if([1,5,9,13,17].indexOf(footerLengthData) > -1) {footerLength = "footer_one"}
else if([4,8,12,16,20,24].indexOf(footerLengthData) > -1) {footerLength = "footer_two"}
else if([3,7,11,15,19,23].indexOf(footerLengthData) > -1) {footerLength = "footer_three"}
else if([2,6,10,14,18,22].indexOf(footerLengthData) > -1) {footerLength = "footer_four"}

Is there a way to tell Jquery that I don't just want the if statement to be triggered when the length is equal to 1,5,9,13 or 17, but rather every time its equal to N + X (e.g. in this case, starting from 1 and adding 4 every time)?

Upvotes: 2

Views: 107

Answers (1)

Nina Scholz
Nina Scholz

Reputation: 386680

You could use the remainder operator % and an array with the strings in the custom order.

footer = ['one', 'four', 'three', 'two'][(footerLengthData - 1) % 4];

Upvotes: 2

Related Questions