jueves, 11 de julio de 2013

Creating Javascript Fluent Api

First of all the tests, using Jasmine (making TDD):

describe("Test for Fluent Car", function(){

    it("Create simple Object Car", function () {
        var car = new Car();

        expect(car).not.toBeNull();
    })

    it("initialize Model", function () {
        var car = new Car();
        var model = 'Model';
        
        car.withModel(model);
        
        expect(car.Model()).toEqual(model);
    })

    it("initialize Model & Gas", function () {
        var car = new Car();
        var model = 'Model';
        var gas =  120;
        
        car.withModel(model)
           .withGas(gas);

        expect(car.Model()).toEqual(model);
        expect(car.Gas()).toEqual(gas);
    })

    it("initialize Make & Model & Gas", function () {
        var car = new Car();
        var make = 'make';
        var model = 'Mmdel';
        var gas =  120;

        car.withModel(model)
           .withMake(make)
           .withGas(gas);
        
        expect(car.Model()).toEqual(model);
        expect(car.Make()).toEqual(make);
        expect(car.Gas()).toEqual(gas);
    })

    it("initialize Height & Width", function () {
        var car = new Car();
        var height = 147;
        var width = 259;

        car.withHeight(height)
           .withWidth(width);
        
        expect(car.Height()).toEqual(height);
        expect(car.Width()).toEqual(width);
    })
});

The code:
function Car(){
 this._make = '';
 this._model = '';
 this_gas = 0;
 this._height = 0;
 this._width = 0;
 
 function Make(){
  return this._make;
 }

 function withMake(make){
  this._make = make;
  return this;
 }

 function Model(){
  return this._model;
 }

 function withModel(model){
  this._model =  model;
  return this;
 }

 function Gas(){
  return this._gas;
 }

 function withGas(gas){
  this._gas = gas;
  return this;
 }

 function Height(){
  return this._height;
 }

 function withHeight(height){
  this._height = height;
  return this;
 }

 function Width(){
  return this._width;
 }

 function withWidth(width){
  this._width = width;
  return this;
 }

 return{
  Make:Make,
  withMake:withMake,
  Model:Model,
  withModel:withModel,  
  Gas:Gas,
  withGas:withGas,
  Width:Width,
  withWidth:withWidth,
  Height:Height,
  withHeight:withHeight
 }
}




Source

No hay comentarios:

Publicar un comentario