【问题标题】:Calculate the Cartesian product (xprod method) of two Observables计算两个 Observable 的笛卡尔积(xprod 方法)
【发布时间】:2015-07-09 18:01:08
【问题描述】:

我有一个有趣的问题。也许有人知道我如何实现像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]));
});

【问题讨论】:

  • 那么,您的解决方案有效吗?如果是,您的问题是什么?
  • 我需要一个更好的解决方案。现在我应该将所有数据累积到一个序列中并在订阅中排序。但我认为存在另一种方法。
  • 等等,如果你想要转置的顺序,只需在那些 .for 循环中交换 asbs
  • 哦!也许我今天累了。不看小事。是的,可能你是对的 =) let as = [1, 2, 3]; let bs = ['a', 'b', 'c']; Rx.Observable.for(as, b => { return Rx.Observable.for(bs, a => Rx.Observable.just([b, a])); })./*toArray().*/subscribe(x => { console.log(x/*.sort((a, b) => a[0] - b[0])*/); });
  • FWIW:虽然你知道我是 Rx 的 巨大 支持者,但如果你已经拥有这些数组(你必须这样做),直接使用数组执行此操作可能更有效/性能更高,然后将结果转换为 Observable。

标签: reactive-programming rxjs bacon.js


【解决方案1】:

我同意 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]];

【讨论】:

  • 我知道如何在 vanilla js 中实现它 =)
猜你喜欢
  • 2011-03-24
  • 2017-03-07
  • 1970-01-01
  • 1970-01-01
  • 2013-04-20
  • 2021-11-19
  • 2015-10-21
  • 2012-01-03
  • 2017-03-05
相关资源
最近更新 更多