-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathsPromise.js
119 lines (103 loc) · 2.75 KB
/
sPromise.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
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
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
class sPromise extends Promise {
constructor(executor) {
super((resolve, reject) => {
return executor(resolve, reject);
})
this._caseTag = [];
this._caseFunc = [];
this.onRejected = () => {};
this._switch = () => {};
}
case (_case, _cb) {
if (!!_case || _case === 0) {
this._caseTag.push({ c: "==", case: _case });
this._caseFunc.push(_cb);
}
return this;
}
strictCase(_case, _cb) {
if (!!_case || _case === 0) {
this._caseTag.push({ c: "===", case: _case });
this._caseFunc.push(_cb);
}
return this;
}
//This function executes the case conditions
switch (onFulfilled, onRejected) {
let scope = this;
this.then(comparator => {
try {
let _switch = () => {};
if (scope._caseTag.length !== 0) {
_switch = (scope._caseFunc.filter((tag, index) => {
switch (scope._caseTag[index].c) {
case "==":
return scope._caseTag[index].case == comparator;
case "===":
return scope._caseTag[index].case === comparator;
}
}))[0] || (() => {}); //Get the first function that fulfills the condition
}
onFulfilled(_switch());
} catch (err) {
if (onRejected) onRejected(err);
else {
scope.onRejected(err);
};
}
});
return this;
} catch (onRejected) {
this.onRejected = onRejected
return this;
}
};
(new sPromise((resolve, reject) => {
let time = setTimeout(() => {
resolve(3);
}, 1000);
})).
case(1, () => {
console.log("WRONG result is ==1");
}).
case(2, () => {
console.log("WRONG result is ==2");
}).
strictCase('3', () => {
console.log("WRONG result is ==='3'");
}).
case('3', () => {
console.log("CORRECT result is =='3'");
}).
switch(res => {
console.log(res); //Should be null
console.log("Finished");
}).
catch(err => {
console.log(err);
});
(new sPromise((resolve, reject) => {
let time = setTimeout(() => {
resolve(3);
}, 1000);
})).
case(1, () => {
console.log("WRONG result is ==1");
}).
case(2, () => {
console.log("WRONG result is ==2");
}).
strictCase('3', () => {
console.log("WRONG result is ==='3'");
}).
case('3', () => {
console.log("CORRECT result is =='3'");
return 324;
}).
switch(res => {
console.log(res); //Should be 324
console.log("Finished");
}).
catch(err => {
console.log(err);
});