Created
August 28, 2014 09:18
-
-
Save geraintluff/7fdd7f320ca12c10e4f6 to your computer and use it in GitHub Desktop.
Asynchronous replace() for JavaScript
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
String.prototype.asyncReplace = function (subStr, replacer, callback) { | |
var str = this; | |
var replacements = {}; | |
var pending = 0; | |
var checkDone = function () { | |
if (!--pending) { | |
var result = str.replace(subStr, function (match) { | |
var args = Array.prototype.slice.call(arguments, 0); | |
var pos = args[args.length - 2]; | |
var key = pos + '-' + match.length; | |
return replacements[key]; | |
}); | |
callback(null, result); | |
} | |
}; | |
str.replace(subStr, function (match) { | |
pending++; | |
var args = Array.prototype.slice.call(arguments, 0); | |
var pos = args[args.length - 2]; | |
var key = pos + '-' + match.length; | |
args.push(function (error, result) { | |
if (error) { | |
pending = Infinity; | |
replacer = function () {}; | |
return callback(error); | |
} | |
replacements[key] = result; | |
checkDone(); | |
}); | |
replacer.apply(null, args); | |
}); | |
if (!pending) { | |
setTimeout(function () { | |
callback(null, str); | |
}, 10); | |
} | |
return this; | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment