Created
September 5, 2016 22:22
-
-
Save Conduitry/76469a776350f7e7ba4da9829340bde1 to your computer and use it in GitHub Desktop.
Asynchronous version of String.prototype.replace, using promises
This file contains hidden or 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
export default function replaceAsync(str, re, func) { | |
let replacements = [] | |
str.replace(re, (...args) => { | |
replacements.push(func(...args).then(res => [ args[args.length - 2], args[0].length, res ])) | |
}) | |
return Promise.all(replacements).then(replacements => { | |
let out = '' | |
let lastEnd = 0 | |
for (let [ offset, length, replacement ] of replacements) { | |
out += str.slice(lastEnd, offset) + replacement | |
lastEnd = offset + length | |
} | |
out += str.slice(lastEnd) | |
return out | |
}) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment