0
const Arr = [0, 1, 2];

for (var i = Number.MIN_SAFE_INTEGER; i <= Number.MAX_SAFE_INTEGER; i += 1) { ... }

Need to correlate any given i to an appropriate index in Arr, so that

i=-3 => 0
i=-2 => 1
i=-1 => 2
i=0 => 0
i=1 => 1
i=2 => 2
i=3 => 0
i=4 => 1
i=5 => 2

... etc.

1
  • It would be more appropriate to use an object with 2 properties: the key and the value Commented Jan 14, 2018 at 21:16

3 Answers 3

2

This question does not need the array factor. It is about mapping any integer to a limited range.

This you can do with the following transformation:

j = i - Math.floor(i/3)*3

NB: for positive numbers you could use just i % 3, but it does not give the results you desire for negative numbers.

Sign up to request clarification or add additional context in comments.

Comments

1

I might recommend to make an index function that takes an array xs, and an index i. Conceptually, what we want to do is wrap i around if it goes out-of-bounds of xs in either direction. The remainder (%) operator is just what we need for the job

const index = (xs, i) =>
  i < 0
    ? xs [0 - (i % xs.length)]
    : xs [i % xs.length]

const data =
  [ 'a', 'b', 'c' ]

for (let i = -5; i < 6; i++)
  console.log (i, index (data, i))
// -5 'c'
// -4 'b'
// -3 'a'
// -2 'c'
// -1 'b'
// 0 'a'
// 1 'b'
// 2 'c'
// 3 'a'
// 4 'b'
// 5 'c'

Comments

0

I've found quite a nice solution to this:

function mod(n, m) {
  const q = n % m;
  return q < 0 ? q + m : q;
}

found here: https://github.com/oliviertassinari/react-swipeable-views/blob/master/packages/react-swipeable-views-core/src/mod.js

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.