-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathindex.js
65 lines (63 loc) · 2.29 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
module.exports = {
replace : replace,
Replacer : Replacer
};
/**
* Replaces instances of the regex in str using the asynchronous callback function, replacer
*
* @param {regex} regex The regex object to execute.
* @param {string} str The string to be matched
* @param {function} replacer The asynchronous callback function called to translate matches into replacements
* @param {function} done The callback function invoked on completion or error
*
* The replacer callback should take two parameters (match, callback). match is the result from regex.exec(), including capturing groups.
* callback should be invoked with (err, replacement_value) when done.
*
* The done callback will be invoked with (err, result) once all replacements have been processed.
*
*/
function replace(regex, str, replacer, done) {
regex.lastIndex = 0;
var match = regex.exec(str);
if(match==null) { // No matches, we are done.
done(null, str);
}
else {
// Found a match, call the async replacer
var params = Array.of(function(err, result) {
if(err) { // If the replacer failed, callback and pass the error
return done(err, result);
}
var matchIndex = match.index;
var matchLength = match[0].length;
// Splice the replacement back into the string
var accum = str.substring(0,matchIndex) + result;
var rest = str.substring(matchIndex + matchLength);
if(regex.global) { // Keep replacing
replace(regex, rest, replacer, function(err, remaining) {
done(err, accum + remaining);
});
}
else {
done(null, accum + rest);
}
});
replacer.apply(null, params.concat(match));
}
}
/**
* Constructor function that returns a closuer locking in the regex and the replacer.
*
* @param {regex} regex The regex object to execute
* @param {function} replacer The asynchronous callback function called to translate matches into replacements
*
* @returns {function} a function that can be called with (str, done) to execute the replacements.
*/
function Replacer(regex, replacer) {
var flags = (regex.global ? "g" : "") + (regex.ignoreCase ? "i" : "") + (regex.multiline ? "m" : "");
return function(str, done) {
// Cloning the regex so it has it's own lastIndex state to avoid concurrency issues
var re_clone = new RegExp(regex.source, flags);
replace(re_clone, str, replacer, done);
}
}