-
Notifications
You must be signed in to change notification settings - Fork 7
/
typeCast.js
56 lines (48 loc) · 1.27 KB
/
typeCast.js
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
export {
stringFromArrayBuffer,
arrayBufferFromBlob,
stringFromBlob,
stringFromArray,
setFromArray,
mapFromObject,
};
const textDecoder = new TextDecoder();
/* works with
Uint8Array, Uint16Array, Uint32Array,
Int8Array, Int16Array, Int32Array, ArrayBuffer */
const stringFromArrayBuffer = function (arrayBufferOrView) {
return textDecoder.decode(arrayBufferOrView);
};
const xFromBlob = function (readAs) {
/**
* @param {Blob | File} blob
* @return {Promise}
*/
return function (blob) {
return new Promise(function (resolve, reject) {
const reader = new FileReader();
reader.onload = function () {
resolve(reader.result);
};
reader.onerror = function (error) {
reject(error);
};
reader[readAs](blob);
});
};
};
const arrayBufferFromBlob = xFromBlob(`readAsArrayBuffer`);
const stringFromBlob = xFromBlob(`readAsText`);
const stringFromArray = function (array, sep = ` `) {
return array.join(sep);
};
const setFromArray = (array) => {
return new Set(array);
};
const mapFromObject = function (obj) {
const m = new Map();
for (const key in obj) {
m.set(key, obj[key]);
}
return m;
};