Skip to content

Instantly share code, notes, and snippets.

@Bulletninja
Created November 6, 2019 06:18
Show Gist options
  • Save Bulletninja/dca847a224a5407d8d15f4e7570e3f93 to your computer and use it in GitHub Desktop.
Save Bulletninja/dca847a224a5407d8d15f4e7570e3f93 to your computer and use it in GitHub Desktop.
Slick patterns to use in js
// one loop multiple checks (can be turned into a builder of other datastructure
const exampleValues = [2, 15, 8, 23, 1, 32];
const [truthyValues, falseyValues] = exampleValues.reduce((arrays, exampleValue) => {
if (exampleValue > 10) {
arrays[0].push(exampleValue);
return arrays;
}
arrays[1].push(exampleValue);
return arrays;
}, [[], []]);
// Replace switch with object literal
// Object literal
const createContent = function(contentType){
const contentTypes = createContent.contentTypes;
const createType = contentTypes[contentType] || contentTypes.default;
return createType(); // or new createType() if its a class constructor
}
createContent.contentTypes = {
post: Post,
video: Video,
default: Unknown
};
// similar to x && y
const criteria = [
user === 'logged-in',
hasCardDetails
]
if ( criteria.every(isTrue => isTrue) ) {
// do a thing if all are true
}
// similar to x || y
const criteria = [
user === 'logged-in',
hasCardDetails
]
if ( criteria.some(isTrue => isTrue) ) {
// do a thing if some are true
}
// more patterns @ https://dev.to/thejohnstew/5-programming-patterns-i-like-53dp
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment