Last active
December 24, 2015 15:39
-
-
Save gerardpaapu/6821484 to your computer and use it in GitHub Desktop.
This file contains hidden or 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
function arraySum(i) { | |
'use strict'; | |
function type(obj) { | |
// Object.prototype.toString provides a way to reliably identify | |
// builtin javascript types like Array, Number and String, but | |
// will fail (in older browsers) if called on null or undefined | |
// | |
// The relevant specs: | |
// | |
// http://es5.github.io/#x15.2.4.2 | |
// http://ecma262-5.com/ELS5_Section_15.htm#Section_15.2.4.2 | |
// | |
var _toString = Object.prototype.toString; | |
return obj === null ? 'Null' | |
: obj === undefined ? 'Undefined ' | |
: _toString.call(obj).slice(8, -1); | |
} | |
function sum(obj) { | |
switch (type(obj)) { | |
case 'Number': | |
// numbers sum to themselves | |
return obj; | |
case 'Array': | |
// Arrays sum to the total of the sum of each item | |
// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/Reduce | |
return obj.reduce(function (total, obj) { | |
// call sum on each element of obj | |
return total + sum(obj); | |
}, 0); | |
default: | |
// All other objects sum to 0 | |
return 0; | |
} | |
} | |
return sum(i); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment