Skip to content

Instantly share code, notes, and snippets.

@Conduitry
Created September 5, 2016 22:22
Show Gist options
  • Save Conduitry/76469a776350f7e7ba4da9829340bde1 to your computer and use it in GitHub Desktop.
Save Conduitry/76469a776350f7e7ba4da9829340bde1 to your computer and use it in GitHub Desktop.
Asynchronous version of String.prototype.replace, using promises
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