u/ms-maria-main r/Frontend • Recommends
I ❤ #javascript: The shortest alternative to reverse function in JS?
1.7K subscribers • 7 videos on Hallway
Beginner. No background in the topic needed.
821 views8 years ago2 recommendations
Programming languagesJavaScript
A short exploration of different ways to reverse an array in JavaScript without using the built-in reverse method.
Hi, let's talk today about an alternative to Array reverse function in JavaScript. I'm Anatol and you're watching the Good Parts of the FrontEnd development. For the first part of the initial task the conditions are: 1. Your code should be as short as possible 2. You mustn't use Array.reverse() method Input array: [1, 2, 3, 'a', 'b', 'c', []] Output: [[], 'c', 'b', 'a', 3, 2, 1] Input: ['2',[],[],false,true,true,false,[],95] Output: [95, [], false, true, true, false, [], [], '2'] Input: [1,false,false,[],false,true,'yqG',false,false] Output: [false, false, 'yqG', true, false, [], false, false, 1] We can reverse an array in different ways. For example, you can use “for” loop and get the following lines. Or you can take a “while” loop. Or even you can twist with “destructuring” operator: At the very least you can suggest your own solution. Who knows maybe it can be even better? Recalling XOR operation, take your chance to be a superhero! Let’s appeal to basics, to ECMAScript specification ecma-international.org/ecma-262/6.0/#sec-array.prototype.sor… If compareFunction is not undefined, it should be a function that accepts two arguments x and y and returns a negative value if x lower than y, zero if x = y, or a positive value if x greater than y. In that case if a return value is positive (or a positive number, but not equal zero) the array will be reversed. That's exactly what we're looking for. Therefore, the shortest code will look like the following. It's only fifteen symbols not counting spaces. You can play around and try to make it even shorter. The second part is really tricky. It depends on your hardware, environment, the moon phase, etc. :) Nonetheless, I believe your "shortest" code won’t be the "fastest" one ;) To get the most efficient code you can check JSPerf website tests and detect what's the most efficient approach for your environment. jsperf.com/js-array-reverse-vs-while-loop/53 In my case the native reverse() and sort() functions perform almost two times slower than "while" and "for" loops. What’s about the fastest code in your environment? Leave your comments down below. That's it. So easy. If you like this video give it "thumbs up". Thanks for watching and stay curious. Used: looperman.com: Rosita Lofi Beat by Fanto8BC, Progress by nightingale, Chiptune Melody by L0neW0lf, Film Noir by LankFrampard, Russian Boogie by nightingaleu/ms-maria-main r/Frontend • Recommends
u/harlampiin r/node • Recommends