forked from sheepzh/time-tracker-4-browser
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbase64.ts
More file actions
23 lines (18 loc) · 800 Bytes
/
Copy pathbase64.ts
File metadata and controls
23 lines (18 loc) · 800 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
const BASE64_CHARS = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/'
export function encode(str: string): string {
const bytes = new TextEncoder().encode(str)
let result = ''
for (let i = 0; i < bytes.length; i += 3) {
const byte1 = bytes[i] ?? 0
const byte2 = bytes[i + 1] ?? 0
const byte3 = bytes[i + 2] ?? 0
const char1 = byte1 >> 2
const char2 = ((byte1 & 0x03) << 4) | (byte2 >> 4)
const char3 = ((byte2 & 0x0F) << 2) | (byte3 >> 6)
const char4 = byte3 & 0x3F
result += BASE64_CHARS.charAt(char1) + BASE64_CHARS.charAt(char2) +
(i + 1 < bytes.length ? BASE64_CHARS.charAt(char3) : '=') +
(i + 2 < bytes.length ? BASE64_CHARS.charAt(char4) : '=')
}
return result
}