-
Notifications
You must be signed in to change notification settings - Fork 6
Expand file tree
/
Copy pathutil.js
More file actions
96 lines (87 loc) · 2.63 KB
/
util.js
File metadata and controls
96 lines (87 loc) · 2.63 KB
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
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
'user strict'
/*
@author Akash Singh
@email contact@akashsingh.io
@web akashsingh.io
*/
function arrayBufferToBase64(buffer) {
var binary = '';
var bytes = new Uint8Array(buffer);
var len = bytes.byteLength;
for (var i = 0; i < len; i++) {
binary += String.fromCharCode( bytes[ i ] );
}
return window.btoa(binary);
}
function base64ToArrayBuffer(base64) {
var binary_string = window.atob(base64);
var len = binary_string.length;
var bytes = new Uint8Array(len);
for (var i = 0; i < len; i++) {
bytes[i] = binary_string.charCodeAt(i);
}
return bytes.buffer;
}
function sendRequest(url, reqObj) {
return fetch(url, {
method: 'POST',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json'
},
body: JSON.stringify(reqObj)
})
.then(res => {
return res.json();
})
.catch(err => {
console.log(err);
})
}
// Util import from src/helpers.js
var util = (function() {
'use strict';
var StaticArrayBufferProto = new ArrayBuffer().__proto__;
return {
toString: function(thing) {
if (typeof thing == 'string') {
return thing;
}
return new dcodeIO.ByteBuffer.wrap(thing).toString('binary');
},
toArrayBuffer: function(thing) {
if (thing === undefined) {
return undefined;
}
if (thing === Object(thing)) {
if (thing.__proto__ == StaticArrayBufferProto) {
return thing;
}
}
var str;
if (typeof thing == "string") {
str = thing;
} else {
throw new Error("Tried to convert a non-string of type " + typeof thing + " to an array buffer");
}
return new dcodeIO.ByteBuffer.wrap(thing, 'binary').toArrayBuffer();
},
isEqual: function(a, b) {
// TODO: Special-case arraybuffers, etc
if (a === undefined || b === undefined) {
return false;
}
a = util.toString(a);
b = util.toString(b);
var maxLength = Math.max(a.length, b.length);
if (maxLength < 5) {
throw new Error("a/b compare too short");
}
return a.substring(0, Math.min(maxLength, a.length)) == b.substring(0, Math.min(maxLength, b.length));
}
};
})();
window.util = util;
window.arrBuffToBase64 = arrayBufferToBase64;
window.base64ToArrBuff = base64ToArrayBuffer;
window.sendRequest = sendRequest;