计算两个Observables的笛卡尔积(xprod方法)

时间:2015-07-09 18:01:09

标签: reactive-programming rxjs bacon.js

我有一个有趣的问题。也许有人知道如何实现像http://ramdajs.com/docs/#xprod这样的方法。我找到了一个解决方案:

let as = [1, 2, 3];
let bs = ['a', 'b', 'c'];

Rx.Observable.for(bs, b => {  
  return Rx.Observable.for(as, a => Rx.Observable.just([a, b]));  
}).toArray().subscribe(x => {
  console.log(x.sort((a, b) => a[0] - b[0]));
});

1 个答案:

答案 0 :(得分:0)

我同意Ben Lesh上面的评论,除非有异步,否则你可能不需要使用Observable

基于阵列的简单ES5解决方案(相当于Matt Podwysocki的内部地图solution)可能如下所示:

var as     = [1, 2, 3],
    bs     = ['a', 'b', 'c'];
as.flatMap = flatMap;

var product = as.flatMap(pairWithAllBs);

// pairWithAllBs :: Number -> [[Number, String]]
function pairWithAllBs(a) {
    return bs.map(function (b) {
        return [a, b];
    });
}

// flatMap :: @[a], (a -> [b]) -> [b]
// JS does not have a built-in flatMap function.
function flatMap(fn) {
    return Array.prototype.concat.apply([], this.map(fn));
}

在ES7中,使用array comprehensions,我们应该能够:

[for (a of as) for (b of bs) [a, b]];