Skip to content

Instantly share code, notes, and snippets.

@itayganor
Last active December 18, 2019 17:47
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save itayganor/e30711ce742e2c21156acebe41bd5bbd to your computer and use it in GitHub Desktop.
Save itayganor/e30711ce742e2c21156acebe41bd5bbd to your computer and use it in GitHub Desktop.
Asynchronously manipulate URLS found in a text paragraph - PoC
const linkify = require('linkifyjs');
function sleep(delay = 500) {
return new Promise(resolve => {
setTimeout(resolve, delay);
});
}
class Placeholder {}
async function replaceLinksEfficiently(str, callback) {
const tokens = linkify.tokenize(str);
let result = [];
const promises = [];
for (let i = 0; i < tokens.length; i++) {
let token = tokens[i];
if (!token.isLink) {
result.push(token.toString());
continue;
}
let formattedHref = token.toHref('http');
result.push(new Placeholder());
promises.push(new Promise((resolve, reject) => {
callback(formattedHref).then(resolve);
}));
}
const newValues = await Promise.all(promises);
result = result.map(part => part instanceof Placeholder ? newValues.shift() : part);
return result.join('');
}
async function replaceLinks(str, callback) {
const tokens = linkify.tokenize(str);
let result = [];
for (let i = 0; i < tokens.length; i++) {
let token = tokens[i];
if (!token.isLink) {
result.push(token.toString());
continue;
}
let formattedHref = token.toHref('http');
// TODO consider something with Promise.all for simultaneously replace links
let link = await callback(formattedHref);
result.push(link);
}
return result.join('');
}
function main() {
const str = 'hello http://google.com/ world! (github.com). dev.to. go to bit.ly/p?1=2&3=4#5 now. "google.com" 3.99$ ';
async function convert(match) {
console.log(`converting... ${match}`);
await sleep();
return `<${match}>`;
}
replaceLinksEfficiently(str, convert).then(result => {
console.log('Converted content:', result);
});
}
if (require.main === module) {
main();
}
@itayganor
Copy link
Author

itayganor commented Dec 18, 2019

Output of the above:

converting... http://google.com/
converting... http://github.com
converting... http://dev.to
converting... http://bit.ly/p?1=2&3=4#5
converting... http://google.com
Converted content: hello <http://google.com/> world! (<http://github.com>). <http://dev.to>. go to <http://bit.ly/p?1=2&3=4#5> now. "<http://google.com>" 3.99$

replaceLinks iterates all found URLs one by one (uses await).

replaceLinksEfficiently uses Promise.all() to process all found URLs at once.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment