Skip to content

Instantly share code, notes, and snippets.

@koyanloshe
Last active June 15, 2019 08:18
Show Gist options
  • Save koyanloshe/ef19c199ebe29067861726aa4344ad82 to your computer and use it in GitHub Desktop.
Save koyanloshe/ef19c199ebe29067861726aa4344ad82 to your computer and use it in GitHub Desktop.
Javascript Design Patterns #Javascript
// bad
const foo = y && z;
// good
const isPostEnabled = isPost && postDateValid;
/*The art of naming variables by Richard Tan[https://hackernoon.com/the-art-of-naming-variables-52f44de00aad]*/
let result = null;
if (conditionA) {
if (conditionB) {
result = "A & B";
} else {
result = "A";
}
} else {
result = "Not A";
}
const result = !conditionA
? "Not A"
: conditionB
? "A & B"
: "A";
/* Nested Ternaries by Eric Elliot [https://medium.com/javascript-scene/nested-ternaries-are-great-361bddd0f340]*/
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;
}, [[], []]);
/*[https://30secondsofcode.org/]*/
// Switch
let createType = null;
switch (contentType) {
case "post":
createType = () => console.log("creating a post...");
break;
case "video":
createType = () => console.log("creating a video...");
break;
default:
createType = () => console.log('unrecognized content type');
}
createType();
// Object literal
const contentTypes = {
post: () => console.log("creating a post..."),
video: () => console.log("creatinga video..."),
default: () => console.log('unrecognized content type')
};
const createType = contentTypes[contentType] || contentTypes['default'];
createType();
/*by May Shavin [https://medium.com/front-end-weekly/switch-case-if-else-or-a-lookup-map-a-study-case-de1c801d944]*/
function transformData(rawData) {
// check if no data
if (!rawData) {
return [];
}
// check for specific case
if (rawData.length == 1) {
return [];
}
// actual function code goes here
return rawData.map((item) => item);
}
/*The bouncer pattern by Rik Schennink [http://rikschennink.nl/thoughts/the-bouncer-pattern/]*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment