Parametry metody reduce

0
const songs = [
 { name: "Film 1", duration: 300, released: 1990 },
{ name: "Film 2", duration: 400, released: 1995 }
]


const shortestReducer = (prev, next) => prev.duration < next.duration ? prev : next
const shortest = songs.reduce(shortestReducer, songs)

Miałbym pytanie jakim argumentem jest tutaj songs w metodzie reduce:

const shortest = songs.reduce(shortestReducer, songs)

Według dokumentacji metoda reduce przyjmuje takie argumenty:

array.reduce(function(total, currentValue, currentIndex, arr), initialValue)

Czy w takim razie argument songs jest tutaj jako initialValue przekazany?

2

Tak. Chociaż w przypadku takiego reducera będzie to trochę bez sensu, bo za pierwszym razem songs trafi do reducera jako prev. A ten kod:

const shortestReducer = (prev, next) => prev.duration < next.duration ? prev : next

zakłada, że prev będzie miał zmienną duration (której tablica songs nie posiada)

0
(prev, next) => prev.duration < next.duration ? prev : next

W tym wypadku prev i next są mylące, raczej powinno być shortest i elem. Najlepiej będzie opakować całą operację w nazwaną funkcje, shortestMovie(movies) i po kłopocie.

1 użytkowników online, w tym zalogowanych: 0, gości: 1