ean-generator
Version:
A randomly generated EAN-13 code For Amazon
99 lines • 3.7 kB
JavaScript
;
Object.defineProperty(exports, "__esModule", { value: true });
var EanGenerator = /** @class */ (function () {
function EanGenerator(countryCodeArr) {
this.countryCodeArr = [];
this.setCountryCode(countryCodeArr);
}
EanGenerator.prototype.create = function (prop) {
if (prop === void 0) { prop = { size: 1 }; }
return this._create(prop);
};
EanGenerator.prototype.createMultiple = function (prop) {
if (prop === void 0) { prop = { size: 1 }; }
var size = prop.size;
if (!size || Number(size) <= 0 || isNaN(Number(size))) {
size = 1;
}
var arr = new Array(size);
for (var i = 0; i < size; i++) {
arr[i] = this._create(prop);
}
return arr;
};
EanGenerator.prototype._create = function (prop) {
var countryCode = prop.countryCode, vendorEan = prop.vendorEan;
if (this.countryCodeArr.length === 0) {
throw new RangeError('please set countryCode before call create!');
}
if (countryCode && countryCode.toString().length !== 3) {
throw new RangeError('the length of countryCode must be 6');
}
if (vendorEan && vendorEan.toString().length !== 6) {
throw new RangeError('the length of vendorEan must be 6');
}
if (!countryCode) {
countryCode = this.pickCountryCode();
}
if (!vendorEan) {
vendorEan = this.fillNumber(6);
}
var eanCode = countryCode.toString() +
vendorEan.toString() +
this.fillNumber(3);
var lastestNum = this.computedEanLastNum(eanCode);
return eanCode + lastestNum;
};
EanGenerator.prototype.isValid = function (num) {
if (num.length !== 13) {
return false;
}
var computedLastNum = this.computedEanLastNum(num);
var lastNum = num.toString().charAt(12);
return lastNum === computedLastNum;
};
EanGenerator.prototype.setCountryCode = function (countryCodeArr) {
if (countryCodeArr.length === 0) {
throw new RangeError('the length of countryCodeArr must be >=1');
}
for (var i = 0; i < countryCodeArr.length; i++) {
if (countryCodeArr[i].length !== 3) {
throw new Error("the length of " + countryCodeArr[i] + " must be 3");
}
}
this.countryCodeArr = countryCodeArr;
};
EanGenerator.prototype.computedEanLastNum = function (num) {
var subNum = num.substr(0, 12);
var odd = 0;
var even = 0;
var bOdd = true;
for (var i = 0; i < subNum.length; i++) {
if (bOdd) {
odd += Number(subNum[i]);
}
else {
even += Number(subNum[i]);
}
bOdd = !bOdd;
}
var sum = odd + even * 3;
sum = sum.toString();
var lastestNum = (10 - Number(sum[sum.length - 1])) % 10;
return lastestNum.toString();
};
EanGenerator.prototype.pickCountryCode = function () {
var randomNum = Math.floor(Math.random() * this.countryCodeArr.length);
return this.countryCodeArr[randomNum];
};
EanGenerator.prototype.fillNumber = function (len) {
var str = '';
for (var i = 0; i < len; i++) {
str += Math.floor(Math.random() * 10).toString();
}
return str;
};
return EanGenerator;
}());
exports.default = EanGenerator;
//# sourceMappingURL=ean-generator.js.map