-2

I would like the most modern way to make an array like this

const nextchunk = [];
nextchunk[0] = [0, 6];
nextchunk[1] = [7, 13];

Each nextchunk must have 7 places in it as shown. These represent a limit query later in in the code. So nextchunk[1] gets out item 7 - 13, nextchunk[2] gets out 14 - 20

I would like the flexibility of being able to call nextchunk[20] at runtime and have it return the correct values.

32423hjh32423
  • 3,048
  • 7
  • 44
  • 59
  • 1
    Start by using a loop to generate them, then go for [`Array.from({length: 21}, (_, i) => …)` or something similar](https://stackoverflow.com/q/3746725/1048572) – Bergi Apr 08 '18 at 11:42
  • Amazing. -3 yet 3 answers from very experienced stackers - that would suggest the opposite. – 32423hjh32423 Apr 08 '18 at 11:57
  • 2
    You know that question downvotes mean "*This post does not show any effort*"? You can still [edit] to improve. – Bergi Apr 08 '18 at 12:07

3 Answers3

5
   function chunks(size) {
     return function getChunk(index) {
       return [size * index, size * (index + 1) - 1];
     }
   }

   const nextchunk = chunks(7);
   console.log(
      nextchunk(0), 
      nextchunk(1), 
      nextchunk(20)
   );

You can easily calculate the value. There is no need to generate it before it is actually needed. If you really need the array, its easy to build it up with the upper helper:

  const nextchunk = Array.from({length: 21}, (_, i) => chunks(7)(i));
  console.log(nextchunk[20]);
Jonas Wilms
  • 132,000
  • 20
  • 149
  • 151
4

I would like the flexibility of being able to call nextchunk[20] at runtime and have it return the correct values.

Though I don't recommend to use this approach in production (mainly because you won't be able to transpile it to work in elder js engines) but you could achive nextchuck[20] syntax using Proxies.

// just for fun
const nextChunk = new Proxy([], {
  get(target, prop) {
    const maybeIndex = parseInt(prop, 10)
    const has = Reflect.has(target, prop)
    const value = Reflect.get(target, prop)
    
    if (has) { 
      return value
    }
    
    if(!Number.isNaN(maybeIndex)) {
      const newValue = [maybeIndex * 7, 6 + maybeIndex * 7]
      Reflect.set(target, prop, newValue );
      
      return newValue;
    }
    
    return value;
  }
});

console.log(nextChunk[0], nextChunk[1], nextChunk[20])
console.log(nextChunk[0] === nextChunk[0])
Yury Tarabanko
  • 44,270
  • 9
  • 84
  • 98
2

You could create custom function that takes array and number and adds new element to array based on your calculation.

const arr = [];
const nextchunk = (array, chunk) => {
  const start = chunk * 6 + chunk;
  array.push([start, start + 6])
}

nextchunk(arr, 0);
nextchunk(arr, 1);
nextchunk(arr, 2);
nextchunk(arr, 20);

console.log(arr)
Nenad Vracar
  • 118,580
  • 15
  • 151
  • 176