Skip to content

Instantly share code, notes, and snippets.

@Ntropish
Created October 1, 2019 04:07
Show Gist options
  • Save Ntropish/0da8049d2aea6aa44df3ef9405331fed to your computer and use it in GitHub Desktop.
Save Ntropish/0da8049d2aea6aa44df3ef9405331fed to your computer and use it in GitHub Desktop.
//=============================================================================
// 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);
@Ntropish
Copy link
Author

Ntropish commented Oct 1, 2019

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.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment