Skip to content
This repository has been archived by the owner on Feb 16, 2021. It is now read-only.

Handling union of unions by default #126

Closed
jgoux opened this issue Aug 27, 2015 · 2 comments
Closed

Handling union of unions by default #126

jgoux opened this issue Aug 27, 2015 · 2 comments

Comments

@jgoux
Copy link
Contributor

jgoux commented Aug 27, 2015

Hello,
at the moment, the default implementation of Union.dispatch doesn't delegate the dispatching if one of its type is of kind "union".
I propose to include this case in the implementation, so we can use union of unions :

Union.dispatch = function (x) {
    for (var i = 0, len = this.meta.types.length; i < len; i++ ) {
      if (types[i].meta.kind === "union") {
        var type = types[i].dispatch(x);
        if (type) {
          return type;
        }
      } else if (is(x, types[i])) {
        return types[i];
      }
    }
  };

With this implementation, something like this would work by default :

const TodoListAggregate.Command = union([AddTodo, EditTodo])
TodoListAggregate.Command.dispatch(customDispatch) // dispatch to AddTodo or EditTodo based on custom logic
const Command = union([TodoListAggregate.Command, AnotherAggregate.Command]) // union of unions :D
Command(fooBar) // assuming fooBar is of type AddTodo, it will delegate the dispatching to TodoListAggregate.Command.dispatch method
@gcanti
Copy link
Owner

gcanti commented Aug 27, 2015

Hi @jgoux, good idea! I'd just add a check to be sure it's really a union (theorically it could also be a class constructor):

function isStruct(x) {
  ...
}

function isMaybe(x) {
  ...
}

function isUnion(x) {
  return isType(x) && (x.meta.kind === 'union');
}

...

Union.dispatch = function (x) { // default dispatch implementation
  for (var i = 0, len = types.length; i < len; i++ ) {
    var type = types[i];
    if (isUnion(type)) { // dispatch recursively
      return type.dispatch(x);
    }
    if (is(x, type)) {
      return type;
    }
  }
};

Do you want to submit a PR with this change and some tests? I'd love to see you listed as a contributor

@jgoux
Copy link
Contributor Author

jgoux commented Aug 27, 2015

I'll try to push something tomorrow. 👍

Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants