-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmathFunctions.html
More file actions
49 lines (47 loc) · 1.26 KB
/
Copy pathmathFunctions.html
File metadata and controls
49 lines (47 loc) · 1.26 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
<script>
/* Add recursive sum function to native Math class
* Arguments:
* • x1, ..., xn : finite list of numbers or list of containers of numbers
* returns :
* • sum of all numbers
*/
Math.sum = function() {
var sum = 0;
for (var j in arguments)
{
if ((typeof arguments[j] === 'object') || (typeof arguments[j] === 'Array'))
{
for (var k in arguments[j]) sum += Math.sum(arguments[j][k]);
}
else sum += arguments[j];
}
return sum;
}
/* Add avg function to native Math class
* Arguments:
* • x1, ..., xn : finite list of numbers
* Returns:
* • average of all numbers, or 0 if no numbers specified
*/
Math.avg = function() {
return arguments.length ? Math.sum(arguments) / countNumbers(arguments) : 0;
}
/* returns amount of numbers in object(s)
* Arguments:
* • x1, ..., xn : finite list of numbers (or objects containing numbers)
* Returns:
* • amount of numbers in arguments
*/
function countNumbers() {
var count = 0;
for (var j in arguments)
{
if ((typeof arguments[j] === 'object') || (typeof arguments[j] === 'Array'))
{
for (var k in arguments[j]) count += countNumbers(arguments[j][k]);
}
else count += 1;
}
return count;
}
</script>