Skip to content

Register type #11

@jrf0110

Description

@jrf0110

This might predicate #10 Something like this:

// Easily go from orderId->Order->OrderWithItems
utils.overload.registerType({
  name: 'OrderWithItems'
, inherits: 'Order'
, def: function( order ){
    return Array.isArray( order.items );
  }
});

utils.overload.registerType({
  name: 'User'
, inherits: 'Object'
, def: function( user ){
    return [
      'first_name'
    , 'last_name'
    , 'user_id'
    ].every( function( k ){
      return k in user;
    });
  }
});

var doSomethingWithOrder = utils.overload({
  default: function(){
    throw new Error('Invalid argument combination');
  }

, 'Number,Function':
  function( orderId, callback ){
    db.orders.findOne( orderId, function( error, order ){
      if ( error ) return callback( error );

      return doSomethingWithOrder( order, callback );
    });
  }

, 'Order,Function':
  function( order, callback ){
    order.fetchItems( function( error ){
      if ( error ) return callback( error );

      return doSomethingWithOrder( order, callback );
    });
  }

, 'OrderWithItems':
  function( order, callback ){
    // Do something with order knowing for sure it's in the correct state
  }
});

doSomethingWithOrder( 1, function(){ /* ... */ });
doSomethingWithOrder( someOrder, function(){ /* ... */ });
doSomethingWithOrder( someOrderWithItemsFetched, function(){ /* ... */ });

Your functions can handle arguments that are in many different states, but the logic for finagling those states is clearly defined and well-separated.

Metadata

Metadata

Assignees

No one assigned

    Labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions