forEach in JavaScript. Codingame: Stock Exchange Losses - Solved

Thanks! Share it with your friends!

You disliked this video. Thanks for the feedback!

Added by admin
29 Views
Hi! Let's have some fun and solve a puzzle titled "Stock Exchange Losses" by Codingame. I'm Anatol and you are watching the Good Parts of the FrontEnd development.

If this is your first time here, you wanna learn Frontend and JavaScript, start now by subscribing and don’t forget to turn on the subtitles.

The story tells:
You sometimes have to take risks buying market shares, and sometimes you have to know when it's time to sell before you lose everything. This is why we propose a little puzzle, to write a program that will do the maths for us, a program in which we can invest all our trust (and money?!).

In this puzzle you need to compare values and derivatives then memorize this information while traversing a list.

To win this game you need to find not the minimal value but the maximal drop.

I'll traverse this list once and then save a max value and delta, so the complexity of algorithm in Big O notation is N. Sounds good.
According to the graphics the prices cannot be below zero, therefore initial max is 0. Delta value is also set to 0.

For a cycle I use forEach function. It has the following syntax:
arr.forEach(cb(cur, i, arr) {
// code
}[, thisArg]);

forEach executes the provided callback function with:
- current element value
- the element index
- the array being traversed
"This" argument provides the context.

Let's dive into the code.

1. Read the input values
2. Set the initial parameters
3. For each stock price verify its delta and save it in case it's less than the previous value
4. Check a new max value and save it
5. Print results
6. Run all tests
7. OK

That's pretty easy, isn't it? Next time let's have a look at "Shadows of the Knight" and binary search in JavaScript.

My code is available on GitHub https://github.com/e1r0nd/codingame
Documentation is available in the Internet https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference
Follow the links if you’re eager to get more.

If you like this video give it "thumbs up". Thanks for watching and dive deeper.
Subscribe to the channel: https://www.youtube.com/c/AnatolMerezhanyi?sub_confirmation=1
Watch other episodes: https://www.youtube.com/playlist?list=PLEZfD_aygfgKcpJDU57Ipyf-nv1m51bIg
Follow on Twitter: https://twitter.com/e1r0nd_crg

Used:
http://www.looperman.com Mendum by Jakebur4, Belles Bells by Loupin, Feeling Better by haidarjasem
http://www.orangefreesounds.com Arcade Town, Police Radio Sound, Button Sound by Alexander
https://soundcloud.com/eric-skiff/come-and-find-me Come and Find Me by Eric Skiff
Category
Start web programming

Post your comment

Comments

Be the first to comment