Last active
December 23, 2015 10:09
-
-
Save ungoldman/6619506 to your computer and use it in GitHub Desktop.
sums in node
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 usage = 'Usage: node sum.js val1 val2 [other_vals]'; | |
var nums = process.argv.slice(2); | |
var sum = 0; | |
// as a simple program | |
console.log(nums); | |
if (nums.length < 2) { | |
console.log(usage); | |
} else { | |
for (var i=0;i<nums.length;i++) { | |
// putting a unary operator (+) in front of a variable coerces it into a number | |
// see http://xkr.us/articles/javascript/unary-add/ for more info | |
sum += +nums[i]; | |
} | |
console.log(sum); | |
} | |
// as a function | |
function getSum(arr) { | |
// this `sum`'s scope is the function so it doesn't overwrite the global `sum` | |
var sum = 0; | |
if (arr.length < 2) { | |
// you can also catch errors with try/catch (look it up) | |
throw new Error(usage); | |
} else { | |
for (var i=0;i<arr.length;i++) { | |
sum += +arr[i]; | |
} | |
return sum; | |
} | |
} | |
var result = getSum(nums); | |
console.log(result); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment