简体   繁体   English

基于Lazy.js的斐波那契映射到Bacon.js间隔?

[英]Lazy.js based fibonacci to map Bacon.js interval?

I have a code to generate fib sequences with lazy.js 我有一个代码用lazy.js生成fib序列

var fibF = function()
{
  var seq = []; //build sequence array in this closure
  var f = function(n)
  {
    var val;
    if (n <= 1)
    {
      val = 1; // as the Fib definition in Math
    }
    else
    {
      val = seq[n - 2] + seq[n - 1]; // as the Fib definition in Math
    }
    seq[n] = val;
    return val;
  };
  return f;
}();

var fibSequence = _.generate(fibF);  


/*  just for test
var fib_1000 =
  fibSequence
  .take(1000)  
  .toArray();  

console.log(fib_1000); 
//[ 1, 1, 2, 3, 5, 8, 13, 21, 34, 55,...........,4.346655768693743e+208 ]

*/

At the same time, I have a code of timer with Bacon.js 同时,我用Bacon.js编写了一个计时器代码

var B = require('baconjs');

var timeSequence = B
      .interval(1000); //every second

timeSequence 
    .onValue(function() 
      {
        console.log(require('moment')().format('MMMM Do YYYY, h:mm:ss')); 
        // print timestamps every second
      }); 

Then, 然后,

I want to map the the fibSequence onto timeSequence such as 我想将fibSequence maptimeSequence例如

var mySequence = fibSequence.map(timeSequence);

or 要么

var mySequence = timeSequence.map(fibSequence);

Is it possible? 可能吗?

If so, please show me the way. 如果是这样,请给我指路。

Any workaround solution is welcome. 任何解决方法的欢迎。

Thanks. 谢谢。

EDIT working code: 编辑工作代码:

//to simplify use Natrual, instead of Fib

var _ = require('lazy.js');
var __ = require('baconjs');

var natural = function(n)
{
  return n;
};

var _natural = _.generate(natural); //natural numbers
var __timer = __.interval(1000); //every second

var map_to__ = function(_seq, __seq)
{
  var it = _seq.getIterator();

  var sequence =
    __seq
    .map(function()
    {
      it.moveNext();
      return it.current();
    });

  return sequence;
};

var __mappedTimer = map_to__(_natural, __timer);

__mappedTimer
  .onValue(function(x)
  {
    console.log(x); // print every second
  });

I'm not sure whether this is the intended use of iterators , but it should work: 我不确定这是否是迭代器的预期用途,但它应该可以工作:

var it = fibSequence.getIterator()
var mySequence = timeSequence.map(function() {
    return it.moveNext() && it.current();
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM