|
| 1 | +/** |
| 2 | + * JavaScript30 by Wes Bos, https://javascript30.com/ |
| 3 | + * TypeScript implementation by Will Wager |
| 4 | + * Project: Adding up times with reduce |
| 5 | + * Concepts: Map, reduce, calculating times |
| 6 | + * Key takeaways: Mapping step by step can be more readable, but combining |
| 7 | + * into a single map or reduce is less expensive. |
| 8 | + * Sidenotes: Targeted es6 to get Array.from |
| 9 | + * Compilation command: |
| 10 | + * tsc --removeComments --strictNullChecks --noImplicitAny --target es6 typescripts.ts |
| 11 | + */ |
| 12 | + |
| 13 | +const timeNodes = Array.from(document.querySelectorAll('[data-time]')); |
| 14 | +console.time('map and reduce'); |
| 15 | +const seconds = timeNodes |
| 16 | + .map((node: HTMLElement) => node.dataset.time) |
| 17 | + .map(timeCode => { |
| 18 | + if (!timeCode) return 0; |
| 19 | + const [mins, secs] = timeCode.split(':').map(Number); |
| 20 | + return (mins * 60) + secs; |
| 21 | + }) |
| 22 | + .reduce((total, vidSeconds) => total + vidSeconds); |
| 23 | +console.timeEnd('map and reduce'); |
| 24 | + |
| 25 | +let secondsLeft = seconds; |
| 26 | +const hours = Math.floor(secondsLeft / 3600); |
| 27 | +secondsLeft = secondsLeft % 3600; |
| 28 | +const minutes = Math.floor(secondsLeft / 60); |
| 29 | +secondsLeft = secondsLeft % 60; |
| 30 | +console.log(`Map and reduce: ${hours}:${minutes}:${secondsLeft}`); |
| 31 | + |
| 32 | + |
| 33 | +console.time('just reduce'); |
| 34 | +const redSeconds = timeNodes.reduce((totalSeconds: number, node: HTMLElement) => { |
| 35 | + const [mins, secs] = node.dataset.time!.split(':').map(Number); |
| 36 | + return totalSeconds + mins * 60 + secs; |
| 37 | +}, 0); |
| 38 | +console.timeEnd('just reduce'); |
| 39 | +console.log(`Just reduce: ${Math.floor(redSeconds / 3600)}:${Math.floor((redSeconds % 3600) / 60)}:${redSeconds % 60}`); |
0 commit comments