-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathindex.js
More file actions
25 lines (25 loc) · 866 Bytes
/
index.js
File metadata and controls
25 lines (25 loc) · 866 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
export default function replaceAsync(string, searchValue, replacer) {
try {
if (typeof replacer === "function") {
// 1. Run fake pass of `replace`, collect values from `replacer` calls
// 2. Resolve them with `Promise.all`
// 3. Run `replace` with resolved values
var values = [];
String.prototype.replace.call(string, searchValue, function () {
values.push(replacer.apply(undefined, arguments));
return "";
});
return Promise.all(values).then(function (resolvedValues) {
return String.prototype.replace.call(string, searchValue, function () {
return resolvedValues.shift();
});
});
} else {
return Promise.resolve(
String.prototype.replace.call(string, searchValue, replacer)
);
}
} catch (error) {
return Promise.reject(error);
}
}