DEV Community

Discussion on: Reverse a string: awful answers only

Collapse
 
gzuidhof profile image
Guido Zuidhof • Edited

Why not use Python's [::-1], but entirely in the browser? We can load the Pyodide runtime so we can run Python in the browser through WebAssembly. We'll have to eval as no ES module is shipped, but surely that's not a problem. Also the runtime is 20MB, but it's worth it!

var stringToReverse = "hello";

const reversed = new Promise((resolve) => {
    (async() => {
        const pyodideLoaderJS = await (await fetch("https://cdn.jsdelivr.net/pyodide/v0.15.0/full/pyodide.js")).text()
        await eval(pyodideLoaderJS)

        resolve(pyodide.runPython(`
            from js import stringToReverse;
            stringToReverse[::-1]
        `))
    })();
});

reversed.then(s => console.log(s));
Enter fullscreen mode Exit fullscreen mode

Copy it into your browser console and be amazed..