Created
January 3, 2017 09:07
-
-
Save bepitulaz/bfb8df794843fc0fd250793d390927aa to your computer and use it in GitHub Desktop.
Higher-Order Functions Sample
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
var sampleData = [1, 2, 3, 4, 5]; | |
/* | |
Buat fungsi yang mengakumulasi keseluruhan elemen dalam Array. | |
Hasil yang diharapkan 15 | |
*/ | |
// Menggunakan perulangan for | |
function denganPerulangan(data) { | |
var result = 0; | |
for(var i = 0; i < data.length; i++) { | |
result = result + data[i]; | |
} | |
return result; | |
} | |
// Menggunakan reduce yang menerima fungsi lain sebagai parameternya | |
function denganReduce(data) { | |
return data.reduce(function(elemenSebelumnya, elemenSekarang) { | |
return elemenSebelumnya + elemenSekarang; | |
}); | |
} | |
denganPerulangan(sampleData); | |
denganReduce(sampleData); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment