Created
April 30, 2019 02:36
-
-
Save whiteinge/8ca731c3e66e857fd8ead87d1042ceed to your computer and use it in GitHub Desktop.
One interpretation of simple vs. easy in JavaScript
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// In my opinion the simple vs. easy division is often represented when coding | |
// to "layers of abstraction". Having to context-switch and switch to | |
// a different layer to solve a problem is noise that distracts you from the | |
// problem you were originally trying to solve. | |
// For example, if you're trying to draw a paginating, tabular, grid view of | |
// data to the screen it is distracting when you have to stop and wire up | |
// a for-loop to sum the total for the current page then again for all records. | |
// --- | |
// Initialize a starting value then manually add each thing in a list to that | |
// value. | |
const numberList = [1, 5, 9] | |
let sum1 = 0 | |
for (let i = 0; i < numberList.length; i += 1) { | |
sum1 += numberList[i] | |
} | |
// Easy because it requires only basic programming knowledge. | |
// Not simple because it requires a fair bit of thought and attention to write | |
// each time it is used. | |
// --- | |
// Initialize a starting value, describe how to add two things together, | |
// then run that against each item in the list. | |
const sum2 = [1, 5, 9].reduce((acc, cur) => acc + cur, 0) | |
// Somewhat easy because it's quick to write, harder to get wrong, and easy to | |
// read. Although it requires knowledge of higher-order functions. | |
// Somewhat simple because it abstracts iteration from combining things so you | |
// only have to think about one at a time. Although it requires a starting | |
// value that makes sense for the operation. | |
// --- | |
// Have a list of things that already know what starting value makes sense and | |
// already know how to add themselves together. | |
const fold = M => xs => xs.reduce((acc, x) => acc.concat(x), M.empty()) | |
const Sum = val => ({ val, concat: x => Sum(val + x.val) }) | |
Sum.empty = () => Sum(0) | |
const sum3 = fold(Sum)([Sum(1), Sum(5), Sum(9)]) | |
// Not easy because it requires knowledge of unusual, fairly abstract concepts | |
// with unusual names (like monoid). | |
// Simple because you do not have to concern yourself with the implementation | |
// details at all when you use it. You can just Sum things without thought. | |
// --- | |
// Results. | |
console.log({ sum1, sum2, sum3: sum3.val }) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment