Typescript builder example

Date: 2020-08-10
export class TransportOrderBuilder {
    private _TransportOrder: TransportOrder;

    constructor() {
        this._TransportOrder = new TransportOrder();
    }

    public setOrderStatus(status: enumOrderStatus) {
        this._TransportOrder.OrderStatus = status;
        return this;
    }

    public setCargoType(status: EnumCargoType) {
        this._TransportOrder.CargoType = status;
        return this;
    }

    public setTransportDirection(status: enumTransportDirection) {
        this._TransportOrder.TransportDirection = status;
        return this;
    }

    public setPlanningStatus(status: enumPlanningStatus) {
        this._TransportOrder.PlanningStatus = status;
        return this;
    }

    public setSignUpStatus(status: enumSignedUpStatus) {
        this._TransportOrder.OrderStatus = enumOrderStatus.SignedUp;
        this._TransportOrder.SignedUpStatus = status;
        return this;
    }

    public setLoadingStatus(status: EnumLoadingStatus) {
        this._TransportOrder.OrderStatus = enumOrderStatus.InLoading;
        this._TransportOrder.LoadingStatus = status;
        return this;
    }

    public build(): TransportOrder {
        return this._TransportOrder;
    }

    public setTransporterId(id: string) {
        this._TransportOrder.Transporter = new Transporter({ Id: id });
        return this;
    }

    public buildToList(amountInList: number): TransportOrder[] {
        const result = new Array<TransportOrder>();

        for (let index = 0; index < amountInList; index++) {
            const element = <TransportOrder>deepCopy(this.build());
            result.push(element);
        }

        return result;
    }
}

function deepCopy(obj) {
    let copy;

    // Handle the 3 simple types, and null or undefined
    // tslint:disable-next-line:curly
    if (null == obj || "object" !== typeof obj) return obj;

    // Handle Date
    if (obj instanceof Date) {
        copy = new Date();
        copy.setTime(obj.getTime());
        return copy;
    }

    // Handle Array
    if (obj instanceof Array) {
        copy = [];
        for (let i = 0, len = obj.length; i < len; i++) {
            copy[i] = deepCopy(obj[i]);
        }
        return copy;
    }

    // Handle Object
    if (obj instanceof Object) {
        copy = {};
        for (const attr in obj) {
            // tslint:disable-next-line:curly
            if (obj.hasOwnProperty(attr)) copy[attr] = deepCopy(obj[attr]);
        }
        return copy;
    }

    throw new Error("Unable to copy obj! Its type isn't supported.");
}

const order = new TransportOrderBuilder()
      .setTransportDirection(enumTransportDirection.Unknown)
      .setCargoType(EnumCargoType.bulk).build();
38720cookie-checkTypescript builder example