UNPKG

@devix-tecnologia/value-objects

Version:

Coleção de objetos de valores para implementação em sistemas.

107 lines (106 loc) 3.08 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.PlacaVeiculo = void 0; /** * Value Object para Placa de Veículo brasileira. * Suporta dois formatos: * - Formato Antigo: ABC1234 (3 letras + 4 números) * - Formato Mercosul: ABC1D23 (3 letras + 1 número + 1 letra + 2 números) */ class PlacaVeiculo { constructor(plate) { this._isValid = false; const normalized = this.normalizePlate(plate); this._plate = normalized; this._format = this.detectFormat(normalized); this._isValid = this._format !== 'INVALID'; } normalizePlate(plate) { // Remove espaços, hífens e converte para maiúsculas return plate.replace(/[\s\-]+/g, '').toUpperCase(); } detectFormat(plate) { // Formato Antigo: ABC1234 const oldPattern = /^[A-Z]{3}\d{4}$/; // Formato Mercosul: ABC1D23 const mercosulPattern = /^[A-Z]{3}\d[A-Z]\d{2}$/; if (oldPattern.test(plate)) { return 'ANTIGA'; } if (mercosulPattern.test(plate)) { return 'MERCOSUL'; } return 'INVALID'; } get type() { return 'VEHICLE_PLATE'; } get version() { return PlacaVeiculo.VERSION; } get validation() { return 'Validação de formato de placa brasileira (Antiga e Mercosul)'; } get format() { return this._format; } get formatted() { this.isValid({ raiseException: true }); if (this._format === 'ANTIGA') { // ABC-1234 return `${this._plate.slice(0, 3)}-${this._plate.slice(3)}`; } // ABC1D23 -> ABC-1D23 return `${this._plate.slice(0, 3)}-${this._plate.slice(3)}`; } get unformatted() { this.isValid({ raiseException: true }); return this._plate; } toJSON() { return { type: this.type, value: this.unformatted, formatted: this.formatted, format: this.format, isValid: this._isValid, version: this.version, }; } toString() { return this.formatted; } isValid(config = { raiseException: false }) { if (config.raiseException && !this._isValid) { throw new Error('Invalid vehicle plate'); } return this._isValid; } equals(other) { if (!this._isValid) return false; try { const otherPlate = other instanceof PlacaVeiculo ? other : new PlacaVeiculo(other); return this.unformatted === otherPlate.unformatted; } catch (_a) { return false; } } /** * Verifica se a placa está no formato Mercosul */ isMercosul() { return this._format === 'MERCOSUL'; } /** * Verifica se a placa está no formato antigo */ isOldFormat() { return this._format === 'ANTIGA'; } } exports.PlacaVeiculo = PlacaVeiculo; PlacaVeiculo.VERSION = '1.0.0';