stampit-org / stamp

Stamps - better OOP model
https://stampit.js.org
MIT License
25 stars 3 forks source link

fp-constructor/of broken #35

Closed ericelliott closed 7 years ago

ericelliott commented 7 years ago

fp-constructor is implemented wrong. Probably my fault.

  1. .constructor should be an instance method (on the instance's delegate prototype), not a static property. It should refer to the specific stamp which created the instance. (See type representatives)
  2. .of() should be a static prop (on the stamp). It should also refer to the stamp. (See .of() method)

In other words, it should create the stamp equivalent to the following factory:

const createUser = ({
  userName = 'Anonymous',
  avatar = 'anon.png'
} = {}) => Object.assign(
  Object.create({
    constructor: createUser
  }), {
    userName,
    avatar
  }
);

createUser.of = createUser;

// testing .of and .constructor:
const empty = ({ constructor } = {}) => constructor.of ?
  constructor.of() :
  undefined
;

const foo = createUser({ userName: 'Empty', avatar: 'me.png' });

console.log(
  empty(foo), // { avatar: "anon.png", userName: "Anonymous" }
  foo.constructor === createUser.of, // true
  createUser.of === createUser      // true
);

.constructor and .of() can be used as a tool to create Functors and Monads, to derive operations for algebraic datatypes, etc...

Incidentally, .constructor and .of() go hand-in-hand. If you want one, you almost certainly want both.