Last active
November 18, 2019 15:05
-
-
Save jeffmcmahan/b682d60c2696c829c50176c3fa2c20f9 to your computer and use it in GitHub Desktop.
Heritable, stateful functional units (i.e., class-like things)
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
// 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