-
Notifications
You must be signed in to change notification settings - Fork 5
/
utils.ts
76 lines (65 loc) · 1.6 KB
/
utils.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
import { getLogger } from "@std/log";
const enc = new TextEncoder();
export function getUint8Array(str: string | Uint8Array): Uint8Array {
return str instanceof Uint8Array ? str : enc.encode(str);
}
export function hasPrefixFrom(
a: Uint8Array,
prefix: Uint8Array,
offset: number,
) {
for (let i = 0, max = prefix.length; i < max; i++) {
if (a[i + offset] !== prefix[i]) return false;
}
return true;
}
export async function* dummyAsyncIterable(
str: Uint8Array,
): AsyncIterable<Uint8Array> {
yield str;
}
// deno-lint-ignore no-explicit-any
export function isAsyncIterable(iter: any): iter is AsyncIterable<any> {
return !!iter[Symbol.asyncIterator];
}
export type SyncAsyncIterable<T> = AsyncIterable<T> | Iterable<T>;
export async function* makeAsyncIterable<T>(
iter: SyncAsyncIterable<T>,
): AsyncIterable<T> {
const i = isAsyncIterable(iter)
? iter[Symbol.asyncIterator]()
: iter[Symbol.iterator]();
while (true) {
const { done, value } = await i.next();
if (done) {
return;
} else {
yield value;
}
}
}
export function debug(msg: string) {
getLogger("csv").debug(msg);
}
export async function asyncArrayFrom<T>(
iter: AsyncIterable<T>,
): Promise<Array<T>> {
const arr: T[] = [];
for await (const row of iter) {
arr.push(row);
}
return arr;
}
export async function asyncArrayFrom2<T>(
iter: AsyncIterable<AsyncIterable<T>>,
): Promise<T[][]> {
const arr: T[][] = [];
for await (const rowIter of iter) {
const row: T[] = [];
for await (const cell of rowIter) {
row.push(cell);
}
arr.push(row);
}
return arr;
}