Skip to content

Instantly share code, notes, and snippets.

@quatrix
Created August 20, 2018 13:48
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save quatrix/265c9f4b54362b6e7bd67a7974a5bff7 to your computer and use it in GitHub Desktop.
Save quatrix/265c9f4b54362b6e7bd67a7974a5bff7 to your computer and use it in GitHub Desktop.
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