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
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
Documentation is available in the Internet
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:
Watch other episodes:
Follow on Twitter:

Used: Mendum by Jakebur4, Belles Bells by Loupin, Feeling Better by haidarjasem Arcade Town, Police Radio Sound, Button Sound by Alexander Come and Find Me by Eric Skiff
Start web programming

Post your comment


Be the first to comment