-2

Take the following function

function test(callbackFn) {
  for (var i = 1; i < 10; i++) {
    for (var k = 1; k < 100; k++) {
        callbackFn(i, k);
    }  
  }
}

The intention of function test is that it should call the callbackFn as follows

callbackFn(1, 1); callbackFn(1, 2)...callbackFn(1, 100);
callbackFn(2, 1); callbackFn(2, 2)...callbackFn(2, 100);
...

I would like to refactor out the for loops. Is there a suitable RxJs operator which would allow me to do this?

I have looked at the zip, concat and merge operators but they don't seem to suit the use case.

Any suggestions or tips would be greatly appreciated.

Sebastian Lenartowicz
  • 4,695
  • 4
  • 28
  • 39
Joseph King
  • 5,089
  • 1
  • 30
  • 37
  • why don't you like two foreach calls? – iberbeu Sep 20 '16 at 07:43
  • 1
    My real world problem is much more complicated than this. I wanted to keep the question as simple as possible. – Joseph King Sep 20 '16 at 07:49
  • 2
    `Also, I don't want to embed two array.forEach calls` there is no array there, so you can't even forEach it. Unless that code represents iterating over an array. Or two arrays? It's not exactly clear. – VLAZ Sep 20 '16 at 07:49
  • `My real world problem is much more complicated than this.` yet this is _too_ simplified. What is the exact intention here? We need a bit more details. Are you iterating over two arrays? Nested arrays? Is it one array with 10 elements? One array of 100 elements? unknown amount of arrays? What is the problem you want to solve exactly? Are you sure you need to start from 1 instead of 0? Do you simply want to call (pseudo-code) `callback([1-10], [1-1000])` where those represent ranges and you want all permutations? Is it always going to be those numbers? – VLAZ Sep 20 '16 at 07:54

2 Answers2

1

Actually concatMap() should work for you depending on what the callbackFn(i, k) is supposed to do.

These two question are about calling series of requests in order, which might be very similar to what you need to do:

Community
  • 1
  • 1
martin
  • 93,354
  • 25
  • 191
  • 226
0

What I was looking for was the cartesian product. This can be achieved easily enough by using the concatMap operator.

Here is the refactored function

function test(callbackFn) {
    Rx.Observable.range(1, 10)
      .concatMap(i => Rx.Observable.range(1, 100), (i, k) => [i, k])
      .subscribe(([i, k]) => callbackFn(i, k));
}

Hopefully this example can be of use to someone.

Joseph King
  • 5,089
  • 1
  • 30
  • 37