Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Heritable, stateful functional units (i.e., class-like things)
// A pattern for creating objects with public, private, and static methods
// without relying on bad parts of javascript.
const myType = id => {
// Creates a silly type that acts like a class.
// => Object
const token = Math.random()
const hmac = ghmac(token)
const privateMethod = n => {
// A simple example private function within myType.
// => number
return ((100 / n) - token)
}
const public = Object.create(null)
public.type = 'MyType'
public.id = id
public.publicVar = 50
public.somethingMore = 'John Doe'
public.publicMethod = n => {
return (privateMethod(n) + 100)
}
return public
}
myType.someStaticMethod = myTypeInstance => {
// A description of the static method.
// => string
return (myTypeInstance.id + 'whatever')
}
const otherType = (public = {}) => {
// Creates a type that we\'ll use to extend myType.
// => Object
const myVar = 1e8
const myMethod = n => {
// A desccription of the private method.
// => number
return ((1000 / n) + myVar)
}
public.something = Math.pow(5, 5)
public.baz = [1, 2, 3]
public.otherMethod = n => {
// A desccription of the public method.
// => number
return private.method(n) + 100
}
return public
}
// myType instance:
const myThing = myType(39785)
// otherType instance, now inheriting from myType:
const myOtherThing = otherType(myThing)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment