Created
May 18, 2022 04:29
-
-
Save scarletquasar/cb132f3f9e9b4871e9f41ebeb3911b4b 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
/* | |
* Dynamic assignments to Objects in JavaScript: | |
* In JavaScript, object field names and other factors can be dynamic because | |
* all the objects in the language are 'dynamic' and the types/values | |
* are defined in runtime. | |
*/ | |
/* | |
* Getting started: this function returns a dynamic object that depends | |
* on the passed boolean argument. | |
*/ | |
const dynamicConditionalObject = (firstOption = false) => { | |
return { | |
[firstOption ? "option1" : "option2"]: "Hello! I am a potato." | |
} | |
} | |
/* | |
* You can also dynamically pass arguments to the function and generate | |
* a dynamic field + dynamic value. | |
*/ | |
const dynamicStringObject = (myFieldName) => { | |
return { | |
[myFieldName]: `This is the content for ${myFieldName}` | |
} | |
} | |
/* | |
* Pattern matching can be used to attend specific cases where you will need | |
* default cases in your functions | |
*/ | |
const patternMatchingBoolObject = (option = false) => { | |
return { | |
[true]: "default option", | |
[option === true]: "alternative option" | |
}.true | |
} | |
/* | |
* This method can be used in some real world cases, like fetching data | |
* from a specific API. | |
*/ | |
const fakeFetchAndDisplaySomeData = (fakeError = false) => { | |
const fetchData = () => { | |
try { | |
//...fetch(...) some data | |
if(fakeError) { | |
throw new Error("Oh no! You could not fetch the data.") | |
} | |
return { | |
response: "Wow, you just fetched some data! Nice job." | |
} | |
} | |
catch(e) { | |
return e.message; | |
} | |
} | |
const displayData = () => { | |
const result = fetchData(); | |
const isError = typeof(result) == "string"; | |
const fieldName = isError ? "error" : "response"; | |
const fieldContent = isError ? result : result.response; | |
console.log({ | |
[fieldName]: fieldContent | |
}) | |
} | |
displayData(); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment