epic-p2p-shipping
Version:
A Point to Point Shipping calculation library.
62 lines (61 loc) • 2.78 kB
JavaScript
;
Object.defineProperty(exports, "__esModule", { value: true });
exports.ShippingZone = void 0;
const ShippingException_1 = require("./ShippingException");
class ShippingZone {
constructor(name, branches) {
this.name = name;
this.branches = branches;
this.has = (branchName) => Object.keys(this.Branches).includes(branchName);
this.getName = () => this.name;
this.getBranch = (name) => this.Branches[name];
this.getBranches = () => this.branches;
this.setAmount = (from, to, amount, recursive = false) => {
this.Amounts[from][to] = amount;
if (recursive)
this.Amounts[to][from] = amount;
return this;
};
this.branchOf = (node) => {
const Branches = this.branches.filter(branch => branch.has(node));
if (Branches.length)
return Branches[0];
else
throw new ShippingException_1.ShippingException(`Branch not found! Invalid node provided!`);
};
this.setResolver = (callback) => {
if (typeof callback === "function")
this.ResolverCallback = callback;
else
throw new ShippingException_1.ShippingException(`Invalid callback type has been provided!`);
return this;
};
this.getPayments = (from, to) => {
var _a, _b;
// Results
const tb = ((_a = this.branchOf(from).getAmount(from)) === null || _a === void 0 ? void 0 : _a.from) || 0;
const b2b = this.Amounts[this.branchOf(from).getName()][this.branchOf(to).getName()] || 0;
const fb = ((_b = this.branchOf(to).getAmount(to)) === null || _b === void 0 ? void 0 : _b.to) || 0;
let Amounts = [tb, b2b, fb];
// Apply Discount
if (typeof this.ResolverCallback === "function")
Amounts = this.ResolverCallback(tb, b2b, fb);
return {
toBranch: typeof Amounts[0] === "number" ? Amounts[0] : tb,
branchToBranch: typeof Amounts[1] === "number" ? Amounts[1] : b2b,
fromBranch: typeof Amounts[2] === "number" ? Amounts[2] : fb,
};
};
const Branches = {};
const Amounts = {};
branches.forEach(branch => {
Branches[branch.getName()] = branch;
Amounts[branch.getName()] = branches
.map(branch => ({ [branch.getName()]: 0 }))
.reduce((p, c) => (Object.assign(Object.assign({}, p), c)));
});
this.Branches = Branches;
this.Amounts = Amounts;
}
}
exports.ShippingZone = ShippingZone;