Last active
December 18, 2019 17:47
-
-
Save itayganor/e30711ce742e2c21156acebe41bd5bbd to your computer and use it in GitHub Desktop.
Asynchronously manipulate URLS found in a text paragraph - PoC
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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(); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Output of the above:
replaceLinks
iterates all found URLs one by one (usesawait
).replaceLinksEfficiently
usesPromise.all()
to process all found URLs at once.