Skip to content

Commit

Catch up with main

# Conflicts: # math.js

g1tbotcommitted Parents0c1f0d19812c46Browse files
2 files+33−10/2 viewed
+26−1
2929 return result;
3030 }
3131
32−module.exports = { add, multiply, mod, power };
32+/** Returns the average of numbers; throws a TypeError if the array is empty. */
33+function mean(numbers) {
34+ if (numbers.length === 0) {
35+ throw new TypeError("numbers must not be empty");
36+ }
37+ return numbers.reduce((sum, n) => sum + n, 0) / numbers.length;
38+}
39+
40+/** 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. */
41+function median(numbers) {
42+ if (numbers.length === 0) {
43+ throw new TypeError("numbers must not be empty");
44+ }
45+ const sorted = [...numbers].sort((a, b) => a - b);
46+ const mid = Math.floor(sorted.length / 2);
47+ return sorted.length % 2 === 0 ? (sorted[mid - 1] + sorted[mid]) / 2 : sorted[mid];
48+}
49+
50+/** Returns the population standard deviation of numbers; throws a TypeError if the array is empty. */
51+function standard_deviation(numbers) {
52+ const avg = mean(numbers);
53+ const variance = numbers.reduce((sum, n) => sum + (n - avg) ** 2, 0) / numbers.length;
54+ return Math.sqrt(variance);
55+}
56+
57+module.exports = { add, multiply, mod, power, mean, median, standard_deviation };
+7−0
1111 assert.strictEqual(math.power(2, 10), 1024);
1212 assert.strictEqual(math.power(5, 0), 1);
1313 assert.throws(() => math.power(2, -1), RangeError);
14+assert.strictEqual(math.mean([1, 2, 3, 4]), 2.5);
15+assert.strictEqual(math.median([3, 1, 2]), 2);
16+assert.strictEqual(math.median([4, 1, 3, 2]), 2.5);
17+assert.strictEqual(math.standard_deviation([2, 4, 4, 4, 5, 5, 7, 9]), 2);
18+for (const fn of [math.mean, math.median, math.standard_deviation]) {
19+ assert.throws(() => fn([]), TypeError);
20+}
1421 console.log("all tests passed");