-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.js
More file actions
141 lines (94 loc) · 2.41 KB
/
main.js
File metadata and controls
141 lines (94 loc) · 2.41 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
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
//-------------------------------------
// user code of the thunkified request
//-------------------------------------
var thunkRequest = thunkify(getRequest)
function mainCode() {
var beforeTime = Date.now()
var thunkGetUser1 = thunkRequest('users/user1', 'get')
var thunkGetUser2 = thunkRequest('users/user2', 'post')
thunkGetUser1(function user1Got(user1) {
thunkGetUser2(function user2Got(user2) {
console.trace(user1, user2)
var afterTime = Date.now()
console.log('time took', afterTime - beforeTime, user1.ms, user2.ms)
})
})
}
mainCode()
//---------------------------
// thunkified reqyest thingy
//---------------------------
/*
Intermediate function I wrote first, in order to write the thunkify function
function thunkRequest(url, method) {
var userFnPtr = null
var data = null
var returnFn = function thunkRequestInner(userFn) {
if(data != null) {
userFn(data)
} else {
userFnPtr = userFn
}
}
getRequest(url, method, function requestCallbackInsideThunkWrapper(requestData) {
if(userFnPtr != null) {
userFnPtr(requestData)
} else {
data = requestData
}
})
return returnFn
}
*/
function newArr(arr) {
return Array.prototype.slice.call(arr, 0)
}
// It assumes that the callback is the last argument.
function thunkify(callbackFn) {
var userFnPointer = null
var callbackResult = null
var callbackFnCallbackFn
var userCallable
callbackFnCallbackFn = function thunkifiedCallback(result) {
if(userFnPointer != null) {
userFnPointer(result)
} else {
callbackResult = result
}
}
userCallable = function userCallable(userFn) {
if(callbackResult != null) {
userFn(callbackResult)
} else {
userFnPointer = userFn
}
}
var thunkifiedFn = function thunkified() {
var argsArr = newArr(arguments)
var fixedArgs = argsArr.concat(callbackFnCallbackFn)
callbackFn.apply(this, fixedArgs)
return userCallable
}
return thunkifiedFn
}
//------------------------------------
// Classic callback style thingymajig
//------------------------------------
var staticDummyUsers = [
{
userName: 'mike',
id: 42,
points: 5000
},
{
userName: 'John',
id: 2,
points: 1250
},
]
function getRequest(url, method, callback) {
var ms = Math.floor( Math.random() * 1000 )
setTimeout(function requestDone() {
callback({data: staticDummyUsers[Math.random() * 2 | 0], url: url, method: method, ms: ms})
}, ms)
}