2

I'm doing the Angular Tour of heroes tutorial, but there is somethings I don't understand, I did some google reasearch but I don't find out an explanation. I don't know where I could ask question. So, sorry if I am in the wrong place...

So, there : https://angular.io/tutorial/toh-pt6#simulate-a-data-server

I don't understand this part :

  // Overrides the genId method to ensure that a hero always has an id.
  // If the heroes array is empty,
  // the method below returns the initial number (11).
  // if the heroes array is not empty, the method below returns the highest
  // hero id + 1.

  genId(heroes: Hero[]): number {
    return heroes.length > 0 ? Math.max(...heroes.map(hero => hero.id)) + 1 : 11;
  }

the genId() method, what does it do ? Someone can explain me step by step please ?

especially this part :

return heroes.length > 0 ? Math.max(...heroes.map(hero => hero.id)) + 1 : 11;

this is the part where i get lose :

Math.max(...heroes.map(hero => hero.id)) + 1 : 11;

Thanks.

1 Answer 1

2

Possibly the mix of a ternary (" condition ? expression-if-true : expression-if-false "), combined with less-familiar array-spread notation ("...") makes this a little too compact. Unpacking it to equivalent code may help make it more clear:

genId(heroes: Hero[]): number {

    // determine next-available id
    if (heroes.length > 0) {
        // we already have some heroes, so:

        // get array of just the ids:
        let existingIds = heroes.map(hero => hero.id); // [11,12,...,20] (assuming 20 is the highest id used so far)

        // and find the highest number in that array:
        // "..." spread notation turns this statement into Math.max(11,12,13,...,20)
        let max = Math.max(...existingIds); // 20

        return max + 1; // 21

    } else {
        // we have no heroes, so:
        return 11; // start at 11
    }

}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.