DEV Community

loading...

Discussion on: Is JavaScript's .shift() Method a Performance Boost?

Collapse
liaowow profile image
Annie Liao Author

Thanks Josh! Sure, here's the leftRotate challenge on HackerRank.

Collapse
joshcheek profile image
Josh Cheek

So I was a little bit wrong. Keeping track of two indexes doesn't work unless you also keep an array of the d items that will get overwritten. And then at that point, it's probably worse than arr.push(arr.shift()). However, because they verify the result by having you write it to a file, you can still optimize like I was thinking (basically, you don't have to rotate at all, you can just start printing the numbers from the offset, and then loop around to the beginning (I cleaned it up a bit, their template was really verbose which made it difficult to follow):

const fs  = require('fs')
const out = fs.createWriteStream(process.env.OUTPUT_PATH)

let input = '';
process.stdin.on('data', inputStdin => input += inputStdin)

process.stdin.on('end', function() {
    let [[n, d], a] = input.split('\n').map(str => str.split(' '))
    while(n--)
      out.write(`${a[d++%a.length]} `)
})

It's not immediately clear that this will be more performant, but looking at the docs, it seems like it will be. If it were actually doing multiple file writes, then that would be expensive, and it might be better to rotate the array and join it into a single string to be written. But the docs say it should buffer the writes, so this is probably similar to what I had in mind. That said, I'm not confident it will be faster without benchmarking, as joining the array may avoid the allocation of the string with the space on the end of it.

Thread Thread
liaowow profile image
Annie Liao Author

Interesting. I always skipped the file writes and jumped to the function instructed. Not sure if this is what the challenge intended, but it's cool to see we can change input like that, as I'm still a NodeJS newbie. Thanks for taking a deep dive into this, Josh.