Javascript RxJS中的bufferReduce

Javascript RxJS中的bufferReduce,javascript,stream,rxjs,reactive-programming,Javascript,Stream,Rxjs,Reactive Programming,您好,我想用RxJSbufferReduce,想知道这是否可能。 solution函数应将一个大文本拆分为字符总数不超过100个字符的单词。结果如下所示: [ ['lorem ipsum whatever less than 100 chars'], ['bla bla blub less than 100 chars'], ] Rx.Observable.from("abc defg hij ...").bufferReduce((acc, letter) => { ac

您好,我想用RxJS
bufferReduce
,想知道这是否可能。 solution函数应将一个大文本拆分为字符总数不超过100个字符的单词。结果如下所示:

[
  ['lorem ipsum whatever less than 100 chars'],
  ['bla bla blub less than 100 chars'],
]
Rx.Observable.from("abc defg hij ...").bufferReduce((acc, letter) => {
   acc = acc.push(letter)
   if(acc.length < 100){ 
     return true; // flush the buffer (I know it should return the acc ;) I just want you to get the idea.)
   }
   return false
})
我的纯js解决方案是:

const calcCharsInWordList = wordList => {
  return wordList.reduce((letterCount, lineWord) => letterCount + lineWord.length, 0) + wordList.length - 1 // add wordlist Length for the sparating spaces
};


const textToLines = (text, maxLineLength) => {
  return text
    .split(' ')
    .reduce((acc, word) => {
      acc.currentLine.push(word);
      if (calcCharsInWordList(acc.currentLine) > maxLineLength) {
        acc.allLines.push(acc.currentLine);
        acc.currentLine = [];
      }
      return acc;
    }, { currentLine: [], allLines: [] })
    .allLines
    .map(line => line.join(' '));
};


console.log(textToLines(`lorem ipsum ....... `, 100));
但如果可能的话,我想用RxJS解决这个问题:

[
  ['lorem ipsum whatever less than 100 chars'],
  ['bla bla blub less than 100 chars'],
]
Rx.Observable.from("abc defg hij ...").bufferReduce((acc, letter) => {
   acc = acc.push(letter)
   if(acc.length < 100){ 
     return true; // flush the buffer (I know it should return the acc ;) I just want you to get the idea.)
   }
   return false
})
Rx.Observable.from(“abc defg hij…”)。bufferReduce((acc,字母)=>{
acc=acc.push(字母)
如果(附件长度<100){
return true;//刷新缓冲区(我知道它应该返回acc;),我只是想让你知道。)
}
返回错误
})
那么,也许嵌套的可观测对象可以在这方面有所帮助?BufferWhen和bufferCount在这里真的没有帮助。
我真的很高兴能用RxJS解决这个问题。

我在这里多次看到类似的问题。基本问题是,诸如
bufferWhen
windowWhen
之类的运算符在每次打开新的缓冲区/窗口时调用用户函数,但这些运算符不允许您对通过的值做出反应。如果他们这样做,事情就会容易得多

此解决方案使用
扫描
,还包括可以短于
限制
常数的最后一行。它仍然非常简单,不涉及任何
异步
调度器,在使用例如
可连接的可观察
(共享可观察的源代码并有条件地将其馈送到
缓冲区()
)时可能需要这些调度器

见现场演示:

此代码打印以下输出:

"Lorem ipsum dolor sit amet,"
"consectetur adipiscing elit."
"Sed non lacinia dui. Pellentesque"
"ullamcorper sed enim et rhoncus."
"Vestibulum iaculis enim eget"
"consectetur sagittis. Orci"
"varius natoque penatibus et"
"magnis dis parturient montes,"
"nascetur mus."
我相信可能会有一个更短的解决方案,但我希望总是从
扫描中发出一个简单的字符串。如果我传递了一些对象,我可以更容易地检测何时我想要分割线


这里有一个类似的问题:

扫描再次累加整个输入文本并添加\n。那其实不是我想要的。我认为可以将字符串像流一样完全管道化。结果中没有
\n