Last active
July 21, 2018 20:52
-
-
Save agm1984/7e9112edc96d6cc2ba9671e4244e06ad to your computer and use it in GitHub Desktop.
Advanced JavaScript Object and Function composition using basic logic
This file contains 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
// First we are creating or getting some users and placing them in `users` | |
const users = [ | |
{ name: 'Bob' }, | |
{ name: 'Alice' }, | |
] | |
// Then we are creating a config object that we could pass around as needed | |
// Notice we are using shorthand `users` instead of `users: users` | |
const config = { | |
appOwner: 'INSERT_YOUR_NAME', | |
users, | |
} | |
// Then we are creating an object that holds functions to quickly access anywhere | |
const actions = { | |
showUser: user => console.log('User:', user.name), | |
addLineThenShowUsers: (users) => { | |
console.log('\n=================') | |
users.forEach(user => console.log('User:', user.name)) | |
}, | |
} | |
// Lets investigate what we have now, some Plain Old JavaScript Objects (POJOs) | |
console.log('We got users:', users) | |
console.log('We got config:', config) | |
console.log('We got actions:', actions) | |
console.log('\nWho is the 2nd user?', users[1].name) | |
// We can always check if something is there or not with a ternary operator | |
// It's like an if/else statement but can be thrown around as a Boolean | |
// We use names like `isUserLoaded` or `hasBorder` to tell the developer how to read it | |
const isAlice = (users[1].name === 'Alice') ? true : false | |
console.log('Is it Alice?', isAlice) | |
// What if we do something crazy now? | |
console.log('\n') | |
// Let's call the actions we made | |
actions.showUser(users[1]) | |
actions.addLineThenShowUsers(users) | |
// Lets make an app now | |
const app = { | |
users, | |
config, | |
actions | |
} | |
console.log('\nAPP:', app) | |
console.log('\nApp Owner:', app.config.appOwner) | |
console.log('\n=================') | |
app.users.forEach((user, i) => { | |
console.log('User:', user.name) | |
console.log('Owned by:', app.config.appOwner) | |
console.log('--------------') | |
}) | |
console.log('=================') |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment