Last active
June 26, 2019 22:55
-
-
Save nrkn/096b62a961dc3fca27ebf28b360eb8af 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
export const createRobot = ( name, job ) => ({ name, job }) | |
export const isRobot = value => | |
value && typeof value.name === 'string' && typeof value.job === 'string' | |
export const introduceRobot = ({ name, job }) => | |
console.log( `Hi, I'm ${ name }. My job is ${ job }.` ) |
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
import { createRobot, isRobot, introduceRobot } from './0-robot-fn.js' | |
export const Robot = ( name, job ) => { | |
const robot = createRobot( name, job ) | |
if( !isRobot( robot ) ) | |
throw Error( 'Expected "name" and "job" to be strings' ) | |
robot.introduce = () => introduceRobot( robot ) | |
return robot | |
} |
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
import { createRobot, isRobot, introduceRobot } from './0-robot-fn.js' | |
import { Robot } from './1-robot-factory.js' | |
const bender = createRobot( 'Bender', 'bending' ) | |
introduceRobot( bender ) // Hi! I'm Bender. My job is bending. | |
console.log( isRobot( bender ) ) // true | |
const wallE = createRobot( 'Wall-E', 'trash collection' ) | |
introduceRobot( wallE ) // Hi! I'm Wall-E. My job is trash collection. | |
console.log( isRobot( wallE ) ) // true | |
const marvin = Robot( 'Marvin', 'opening doors' ) | |
marvin.introduce() // Hi, I'm Marvin. My job is opening doors. | |
console.log( isRobot( marvin ) ) // true | |
// context captured by closure, no need for `apply`, `bind` etc: | |
const { introduce: introduceMarvin } = marvin | |
introduceMarvin() // Hi, I'm Marvin. My job is opening doors. |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment