Skip to content

Instantly share code, notes, and snippets.

@nrkn
Last active June 26, 2019 22:55
Show Gist options
  • Save nrkn/096b62a961dc3fca27ebf28b360eb8af to your computer and use it in GitHub Desktop.
Save nrkn/096b62a961dc3fca27ebf28b360eb8af to your computer and use it in GitHub Desktop.
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 }.` )
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
}
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