From 26aabf954cddb56552564b2c99bdf9e105d01970 Mon Sep 17 00:00:00 2001 From: Grzegorz Kucmierz Date: Fri, 24 Jan 2020 09:26:18 +0100 Subject: [PATCH] Closest friends --- closest-friends/index.js | 21 +++++++++++++++++++++ 1 file changed, 21 insertions(+) create mode 100644 closest-friends/index.js diff --git a/closest-friends/index.js b/closest-friends/index.js new file mode 100644 index 0000000..a963d8f --- /dev/null +++ b/closest-friends/index.js @@ -0,0 +1,21 @@ +// https://www.codewars.com/kata/58791aa554a6783827000221/javascript + +const phoneMap = new Map(); +for (let name in phonebook) { + phoneMap.set(phonebook[name], name); +} + +function closestFriends(history) { + const sum = new Map(); + history.map(entry => { + const m = entry.match(/^(.*) (\d{2}):(\d{2}):(\d{2})$/); + const [PHONE, H, M, S] = [1, 2, 3, 4]; + let duration = (+m[H]) * 3600 + (+m[M]) * 60 + (+m[S]); + if (sum.has(m[PHONE])) { + duration += +sum.get(m[PHONE]); + } + sum.set(m[PHONE], duration); + }); + const top3 = [...sum].sort((a, b) => +b[1] - +a[1]).slice(0, 3); + return top3.map(e => phoneMap.get(e[0])); +}