forked from VladislavPixel/home-work-cs-frontend
-
Notifications
You must be signed in to change notification settings - Fork 0
/
iter-symbols.ts
76 lines (53 loc) · 1.39 KB
/
iter-symbols.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
interface IResultForNextMethod {
value: undefined | string;
done: boolean;
}
export interface IIterator {
next(): IResultForNextMethod;
[Symbol.iterator](): IIterator;
}
function iter(strValue: string): IIterator {
const isSurrogate = (str: string, index: number): boolean => {
const codePoint = str.codePointAt(index);
const codePointPrev = str.codePointAt(index - 1);
if (codePoint && codePoint >= 65536) {
return true;
}
if (codePointPrev && codePointPrev >= 65536) {
return true;
}
return false;
};
let stack: number[] = [];
let currentIndex: number = 0;
return {
next(): IResultForNextMethod {
while (currentIndex < strValue.length) {
const code = strValue.charCodeAt(currentIndex);
if (stack.length === 2) {
const strSymbol = String.fromCharCode(...stack);
stack = [];
return { value: strSymbol, done: false };
}
if (isSurrogate(strValue, currentIndex)) {
stack.push(code);
currentIndex++;
continue;
}
const char = strValue.charAt(currentIndex);
currentIndex++;
return { value: char, done: false };
}
if (stack.length !== 0) {
const strSymbol = String.fromCharCode(...stack);
stack = [];
return { value: strSymbol, done: false };
}
return { value: undefined, done: true };
},
[Symbol.iterator]: function (): IIterator {
return this;
}
};
}
export default iter;