From 98723969eb6cf4152b1e13a949e97cad319b9de2 Mon Sep 17 00:00:00 2001 From: Geir Okkenhaug Jerstad Date: Mon, 23 Sep 2024 12:41:34 +0200 Subject: [PATCH] jobbet litt med arrow functions --- .../summarizing_with_reduce.js | 20 +++++++++++++++++++ .../transforming_with_map.js | 11 ++++++++++ 2 files changed, 31 insertions(+) create mode 100644 eloquentjavascript/05_higher_order_functions/summarizing_with_reduce.js create mode 100644 eloquentjavascript/05_higher_order_functions/transforming_with_map.js diff --git a/eloquentjavascript/05_higher_order_functions/summarizing_with_reduce.js b/eloquentjavascript/05_higher_order_functions/summarizing_with_reduce.js new file mode 100644 index 0000000..3712418 --- /dev/null +++ b/eloquentjavascript/05_higher_order_functions/summarizing_with_reduce.js @@ -0,0 +1,20 @@ +const SCRIPTS = require("./scripts.js"); + +function reduce(array, combine, start) { + let current = start; + for(let element of array){ + current = combine(current, element); + } + return current +} +console.log(reduce([1,2,3,4], (a,b) => a +b, 0)); +console.log([1,2,3,4].reduce((a,b) => a +b)); + +function characterCount(script) { + return script.ranges.reduce((count, [from, to]) => { + return count + (to - from); + }, 0); +} +console.log(SCRIPTS.reduce((a,b) => { + return characterCount(a) < characterCount(b) ? b : a; +})); \ No newline at end of file diff --git a/eloquentjavascript/05_higher_order_functions/transforming_with_map.js b/eloquentjavascript/05_higher_order_functions/transforming_with_map.js new file mode 100644 index 0000000..d7560e8 --- /dev/null +++ b/eloquentjavascript/05_higher_order_functions/transforming_with_map.js @@ -0,0 +1,11 @@ +const SCRIPTS = require("./scripts.js"); + +function map(array, transform) { + let mapped = []; + for (let element of array){ + mapped.push(transform(element)); + } + return mapped +} +let rtlScripts = SCRIPTS.filter(s => s.direction == 'rtl'); +console.log(map(rtlScripts, s => s.name)); \ No newline at end of file