From c4013f72a3be8cd2f7e5853777ed5f5b6869a099 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?kleines=20Filmr=C3=B6llchen?= Date: Fri, 14 Jan 2022 15:02:44 +0100 Subject: [PATCH] Spreadsheet: Implement the mode function My statistics course has gotten to me :^) --- Base/res/js/Spreadsheet/runtime.js | 47 ++++++++++++++++++++++++++++-- 1 file changed, 45 insertions(+), 2 deletions(-) diff --git a/Base/res/js/Spreadsheet/runtime.js b/Base/res/js/Spreadsheet/runtime.js index 7fc99def83..bb1f5b48ae 100644 --- a/Base/res/js/Spreadsheet/runtime.js +++ b/Base/res/js/Spreadsheet/runtime.js @@ -351,6 +351,29 @@ function variance(cells) { return (count * squares - sums * sums) / count; } +function mode(cells) { + const counts = numericReduce( + (map, x) => { + if (!map.has(x)) map.set(x, 0); + map.set(x, map.get(x) + 1); + return map; + }, + new Map(), + cells + ); + + let mostCommonValue = undefined; + let mostCommonCount = -1; + counts.forEach((count, value) => { + if (count > mostCommonCount) { + mostCommonCount = count; + mostCommonValue = value; + } + }); + + return mostCommonValue; +} + function stddev(cells) { return Math.sqrt(variance(cells)); } @@ -727,15 +750,24 @@ variance.__documentation = JSON.stringify({ }, }, E4: { + kind: "Formula", + source: "mode(R`A0:C4`)", + value: "1", + type: "Numeric", + type_metadata: { + format: "mode: %d", + }, + }, + E5: { kind: "Formula", source: "count(R`A0:C4`)", - value: "15", + value: "12", type: "Numeric", type_metadata: { format: "count: %d", }, }, - E5: { + E6: { kind: "Formula", source: "sum(R`A0:C4`)", value: "18", @@ -771,6 +803,17 @@ variance.__documentation = JSON.stringify({ }, }); +mode.__documentation = JSON.stringify({ + name: "mode", + argc: 1, + argnames: ["cell names"], + doc: "Calculates the mode of the numeric values in the given range of cells, i.e. the value that appears most often", + examples: { + 'mode(range("A2", "A14"))': + "Calculate the mode of the values in A2:A14, [Click to view](spreadsheet://example/variance#simple)", + }, +}); + stddev.__documentation = JSON.stringify({ name: "stddev", argc: 1,