Created
October 1, 2019 04:07
-
-
Save Ntropish/0da8049d2aea6aa44df3ef9405331fed to your computer and use it in GitHub Desktop.
This file contains hidden or 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
//============================================================================= | |
// Original | |
//============================================================================= | |
var scrKeys = Object.keys(source) | |
return collection.filter(obj => srcKeys.map(key => obj[key] === souce[key]) | |
.map(key => obj[key] === souce[key]). | |
reduce((a, b) => a && b | |
) | |
) | |
//============================================================================= | |
// Formatted via https://prettier.io/playground/ | |
//============================================================================= | |
var scrKeys = Object.keys(source); | |
return collection.filter(obj => | |
srcKeys.map(key => obj[key] === souce[key]).reduce((a, b) => a && b) | |
); | |
//============================================================================= | |
// Extract functions | |
//============================================================================= | |
var scrKeys = Object.keys(source); | |
var srcKeyEqualOnBoth = key => obj[key] === souce[key]; | |
var andAll = (a, b) => a && b; | |
var keysMatchSource = obj => srcKeys.map(srcKeyEqualOnBoth).reduce(andAll); | |
return collection.filter(keysMatchSource); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Also, with the transformations, it might seem hard to justify extracting all of those functions. But think of it as "relaxing" the code. The prettier version is compact and nice looking, but it's sort of "constricted" in that everything is stuck together on one line and it can't be modified easily. This is really important when working on real projects that change constantly. But it's also the technique I use when I feel like something is too difficult. Just start relaxing the code, breaking things up, and naming them so you can start thinking about them in English.
These extracted functions/data eventually merge into reusable utilites.