-
Notifications
You must be signed in to change notification settings - Fork 1
/
index.js
74 lines (58 loc) · 1.76 KB
/
index.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
'use strict';
exports.searchNReplace = function (regex, replaceFn, inputString, outputStream) {
var tokens = splitChunk(inputString, regex);
var promiseArray = [];
var tokenPromise;
tokens.forEach(function (token, index) {
// for first element there is no previous promise
if (index === 0) {
tokenPromise = processToken(token, replaceFn, Promise.resolve(''));
} else {
tokenPromise = processToken(token, replaceFn, promiseArray[index - 1]);
}
// store promise to array
promiseArray.push(tokenPromise);
// once promise is fulfilled, write to response stream
tokenPromise.then(function (result) {
let outputString = result[0];
if (typeof outputString === 'string') {
outputStream.write(outputString, 'utf-8');
if (index === tokens.length - 1) {
outputStream.end();
}
}
}).catch(function (e) {
console.log(e);
});
});
return Promise.all(promiseArray);
}
function processToken(token, replaceFn, previousPromise) {
// previousPromise should always be the second promise is "all" sequence
if (token.static) {
return Promise.all([Promise.resolve(token.value), previousPromise]);
} else {
return Promise.all([replaceFn(token.value), previousPromise]);
}
}
function splitChunk(inputString, regex) {
var ind = 0;
var match;
var outputArray = [];
while ((match = regex.exec(inputString))) {
outputArray.push({
'static': true,
'value': inputString.slice(ind, match.index)
});
ind = match.index + match[0].length;
outputArray.push({
'static': false,
'value': match.slice(1)
});
}
outputArray.push({
'static': true,
'value': inputString.slice(ind, inputString.length)
});
return outputArray;
};