From e8be01693cc041f2a9e223b51c657da194851359 Mon Sep 17 00:00:00 2001 From: Conduitry Date: Sun, 28 Oct 2018 21:22:00 -0400 Subject: [PATCH] add replaceAsync util function --- src/utils/replaceAsync.ts | 38 ++++++++++++++++++++++++++++++++++++++ 1 file changed, 38 insertions(+) create mode 100644 src/utils/replaceAsync.ts diff --git a/src/utils/replaceAsync.ts b/src/utils/replaceAsync.ts new file mode 100644 index 0000000000..362b76b41d --- /dev/null +++ b/src/utils/replaceAsync.ts @@ -0,0 +1,38 @@ +// asynchronous String#replace + +export default async function replaceAsync( + str: string, + re: RegExp, + func: (...any) => Promise +) { + const replacements: Promise[] = []; + str.replace(re, (...args) => { + replacements.push( + func(...args).then( + res => + { + offset: args[args.length - 2], + length: args[0].length, + replacement: res, + } + ) + ); + return ''; + }); + let out = ''; + let lastEnd = 0; + for (const { offset, length, replacement } of await Promise.all( + replacements + )) { + out += str.slice(lastEnd, offset) + replacement; + lastEnd = offset + length; + } + out += str.slice(lastEnd); + return out; +} + +interface Replacement { + offset: number; + length: number; + replacement: string; +}