Skip to content

Instantly share code, notes, and snippets.

@LeanSeverino1022
Last active September 2, 2019 07:15
Show Gist options
  • Save LeanSeverino1022/4ababeeceaf169b8fa30f8fc2b234f74 to your computer and use it in GitHub Desktop.
Save LeanSeverino1022/4ababeeceaf169b8fa30f8fc2b234f74 to your computer and use it in GitHub Desktop.
Compute Sum #vanillajs
//if you want the old way:
function sum(){
var sum =0;
for(var i=0;i<arguments.length;i++){
sum += arguments[i];
}
return sum;
}
sum(1,2); // returns 3
sum(1,2,3); // returns 6
/*The rest parameter syntax allows us to represent an indefinite number of arguments as an array */
function sum(...theArgs) {
return theArgs.reduce((previous, current) => {
return previous + current;
});
console.log(sum(1, 2, 3));
// expected output: 6
console.log(sum(1, 2, 3, 4));
// expected output: 10
//As a helper function - Returns the sum of all values in a given array.
const arrSum = arr => arr.reduce((a,b) => a + b, 0)
// arrSum([20, 10, 5, 10]) -> 45
//function above is identical to
arrSum = function(arr){
return arr.reduce(function(a,b){
return a + b
}, 0);
}
//src: https://codeburst.io/javascript-arrays-finding-the-minimum-maximum-sum-average-values-f02f1b0ce332
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment