Created
August 20, 2018 13:48
-
-
Save quatrix/265c9f4b54362b6e7bd67a7974a5bff7 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const toChunks = (input: string, chunkSize) => { | |
const i = Math.ceil(Math.random() * Math.min(chunkSize, input.length)) | |
if (!input.length) { | |
return [] | |
} | |
const head = input.slice(0, i) | |
const tail = input.slice(i, input.length) | |
return [head, ...toChunks(tail, chunkSize)] | |
} | |
const chunks = toChunks('hello world foo bar baz 1234567!!!11', 5) | |
const bufferToSize = (chunkSize) => (source) => | |
Observable.create(subscriber => { | |
let buffer = '' | |
return source.subscribe({ | |
next: (value) => { | |
buffer += value | |
while (buffer.length > chunkSize) { | |
subscriber.next(buffer.slice(0, chunkSize)) | |
buffer = buffer.slice(chunkSize, buffer.length) | |
} | |
}, | |
complete: () => { | |
subscriber.next(buffer) | |
subscriber.complete() | |
} | |
}) | |
}); | |
from(chunks) | |
.pipe(bufferToSize(4)) | |
.subscribe((v: string) => console.log(`value: '${v}' :: len: ${v.length}`)) | |
from(chunks) | |
.pipe( | |
Rx.concatMap((v: string) => from(v)), | |
Rx.bufferCount(4), | |
Rx.map(v => v.join('')) | |
) | |
.subscribe((v: string) => console.log(`value: '${v}' :: len: ${v.length}`)) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment