Created
June 4, 2014 12:40
-
-
Save Williammer/401f92608956b37a8a51 to your computer and use it in GitHub Desktop.
javaScript.argumentsDeepCalc.js
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
function flexisum(a) { | |
var total = 0; | |
for (var i = 0; i < arguments.length; i++) { | |
var el = arguments[i], | |
num; | |
if (el == null) { | |
continue; | |
} else { | |
if (isArray(el)) { | |
num = flexisum.apply(this, el); //recursion -- deep calculate | |
} else if (typeof (el) === 'function') { | |
num = Number(el()); | |
} else { | |
num = Number(el); | |
} | |
if (isNaN(num)) { | |
throw Error('cannot convert ' + el + 'to number.'); | |
} | |
total += num; | |
} | |
} | |
return total; | |
} | |
var isArray = Function.isArray || function (arr) { | |
return typeof arr === 'object' && Object.prototype.toString.call(arr) === '[object Array]'; | |
}; | |
var tot = flexisum([1, 2, 3], 4, 4, '4', function () { | |
return 5; | |
}); | |
console.log(tot); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment