npm i -S @bicycle-codes/util
Import sleep from here to reduce duplication.
import { sleep } from '@bicycle-codes/util/sleep'
await sleep(500) // 1/2 second
Take the number of bytes, return a string abbreviated to common sizes (megabyte, kilobyte, etc).
import { humanFilesize } from '@bicycle-codes/util/filesize'
const size = humanFilesize(10_000)
console.log(size)
// => 9.8 KiB
function humanFilesize (
bytes:number,
si:boolean = false,
dp:number = 1
):string
bytes
the byte countsi
-- use SI, instead of EIC units (defaultfalse
)dp
is the number of decimal places to show.
import { Queue } from '@bicycle-codes/util/queue'
Create a queue of promises. Promises will execute 1 at a time, in sequential order.
class Queue<T> {
add (createP:()=>Promise<T>):Promise<T|void>
}
Take a function that returns a promise. Return a promise that will resolve when the created promise resolves.
add (createP:()=>Promise<T>):Promise<T|void>
Note
This will resolve promises in the order they were added to the queue.
import { test } from '@bicycle-codes/tapzero'
import { Queue } from '@bicycle-codes/util'
test('queue of 3 items', t => {
const q = new Queue<string>()
// [p1, p2, p3]
const returned = [false, false, false]
const p1 = q.add(() => {
return new Promise<string>(resolve => {
setTimeout(() => resolve('p1'), 300)
})
})
const p2 = q.add(() => {
return new Promise<string>(resolve => {
setTimeout(() => resolve('p2'), 200)
})
})
const p3 = q.add(() => {
return new Promise<string>(resolve => {
setTimeout(() => resolve('p3'), 100)
})
})
// p1 takes the longest
p1.then((value) => {
t.equal(value, 'p1', '"p1" string is ok')
returned[0] = true
t.ok(!returned[2], 'p2 should not have returned yet')
t.ok(!returned[1], 'p1 should not have returned yet')
})
p2.then(value => {
t.equal(value, 'p2', 'should get string "p2"')
returned[1] = true
t.ok(returned[0], 'should have p1 b/c it was added first')
t.ok(!returned[2], 'should not have 3 yet b/c it was addded last')
})
// p3 is the fastest
p3.then(value => {
t.equal(value, 'p3', 'should get string "p3"')
returned[2] = true
t.ok(returned[0], 'should have p1 because it was added first')
t.ok(returned[1], 'should have p2 because it was added next')
})
// return 3 so the test knows when to end,
// because they resolve in order,
// even though the ms are backwards
return p3
})