Skip to content

Commit

Catch up with main

# Conflicts: # math.js

g1tbotcommitted Parentsfd4e0bc9812c46Browse files
2 files+33−10/2 viewed
+26−1
2626 return result;
2727 }
2828
29−module.exports = { add, multiply, subtract, power };
29+/** Returns the average of numbers; throws a TypeError if the array is empty. */
30+function mean(numbers) {
31+ if (numbers.length === 0) {
32+ throw new TypeError("numbers must not be empty");
33+ }
34+ return numbers.reduce((sum, n) => sum + n, 0) / numbers.length;
35+}
36+
37+/** Returns the middle value of numbers (the average of the two middle values when the length is even); throws a TypeError if the array is empty. */
38+function median(numbers) {
39+ if (numbers.length === 0) {
40+ throw new TypeError("numbers must not be empty");
41+ }
42+ const sorted = [...numbers].sort((a, b) => a - b);
43+ const mid = Math.floor(sorted.length / 2);
44+ return sorted.length % 2 === 0 ? (sorted[mid - 1] + sorted[mid]) / 2 : sorted[mid];
45+}
46+
47+/** Returns the population standard deviation of numbers; throws a TypeError if the array is empty. */
48+function standard_deviation(numbers) {
49+ const avg = mean(numbers);
50+ const variance = numbers.reduce((sum, n) => sum + (n - avg) ** 2, 0) / numbers.length;
51+ return Math.sqrt(variance);
52+}
53+
54+module.exports = { add, multiply, subtract, power, mean, median, standard_deviation };
+7−0
77 assert.strictEqual(math.power(2, 10), 1024);
88 assert.strictEqual(math.power(5, 0), 1);
99 assert.throws(() => math.power(2, -1), RangeError);
10+assert.strictEqual(math.mean([1, 2, 3, 4]), 2.5);
11+assert.strictEqual(math.median([3, 1, 2]), 2);
12+assert.strictEqual(math.median([4, 1, 3, 2]), 2.5);
13+assert.strictEqual(math.standard_deviation([2, 4, 4, 4, 5, 5, 7, 9]), 2);
14+for (const fn of [math.mean, math.median, math.standard_deviation]) {
15+ assert.throws(() => fn([]), TypeError);
16+}
1017 console.log("all tests passed");