0
0
mirror of https://github.com/sveltejs/svelte.git synced 2024-12-01 17:30:59 +01:00

add replaceAsync util function

This commit is contained in:
Conduitry 2018-10-28 21:22:00 -04:00
parent 03c7612c6b
commit e8be01693c

38
src/utils/replaceAsync.ts Normal file
View File

@ -0,0 +1,38 @@
// asynchronous String#replace
export default async function replaceAsync(
str: string,
re: RegExp,
func: (...any) => Promise<string>
) {
const replacements: Promise<Replacement>[] = [];
str.replace(re, (...args) => {
replacements.push(
func(...args).then(
res =>
<Replacement>{
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;
}