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.

Eric
  • 43
  • 5

1 Answers1

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
    }

}
storsoc
  • 309
  • 1
  • 7