Skip to content

Instantly share code, notes, and snippets.

@juanmaguitar
Created December 18, 2017 17:15
Show Gist options
  • Select an option

  • Save juanmaguitar/d18093dfad766eed2b8de9e65a3a8e07 to your computer and use it in GitHub Desktop.

Select an option

Save juanmaguitar/d18093dfad766eed2b8de9e65a3a8e07 to your computer and use it in GitHub Desktop.
Interface implementation
const ERROR_METHODS_AS_STRINGS = 'Interface constructor expects method names to be passed in as a string'
const ERROR_PROPERTIES_AS_STRINGS = 'Interface constructor expects property names to be passed in as a string'
const ERROR_NO_OBJECT = 'No Object to check'
const ERROR_METHOD_NOT_IMPLEMENTED = (interface, method) => `The object does not implement the interface ${interface}. Method ${method} not found.`
const ERROR_PROPERTY_NOT_IMPLEMENTED = (interface, property) => `The object does not implement the interface ${interface}. Property ${property} not found.`
const isString = text => typeof text === 'string'
const isFunction = fn => typeof fn === 'function'
class Interface {
constructor(name, methods=[], properties=[]) {
this.name = name
if ( methods.every(isString) ) this.methods = methods
else throw new Error(ERROR_METHODS_AS_STRINGS)
if ( methods.every(isString) ) this.properties = properties
else throw new Error(ERROR_PROPERTIES_AS_STRINGS)
}
isImplementedBy(obj) {
if (obj) {
this.methods.forEach( method => {
if ( !obj[method] || !(obj[method]) ) return
throw new Error(ERROR_METHOD_NOT_IMPLEMENTED(this.name, method))
})
this.properties.forEach( property => {
if ( !obj[property] || isFunction(obj[property]) ) return
throw new Error(ERROR_PROPERTY_NOT_IMPLEMENTED(this.name, property))
})
}
else throw new Error(ERROR_NO_OBJECT)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment