Skip to content

Instantly share code, notes, and snippets.

@andre-f-paggi
Last active October 10, 2017 21:45
Show Gist options
  • Save andre-f-paggi/c610e95c98d5801e797ef77aa9312703 to your computer and use it in GitHub Desktop.
Save andre-f-paggi/c610e95c98d5801e797ef77aa9312703 to your computer and use it in GitHub Desktop.
function Cep(cep) {
// constructor
this._cep = cep;
this.cepEhValido = cepEhValido;
this.comPontos = comPontos;
this.semPontos = semPontos;
if (cep)
_lancarExcecaoSeCepForInvalido(cep);
// functions
function cepEhValido(cep) {
cep = cep || this._cep;
var regexCep = /^\d{5}\-?\d{3}$/;
return regexCep.test(cep);
}
function comPontos(cep) {
cep = cep || this._cep;
_lancarExcecaoSeCepForInvalido(cep);
var cepSemPontos = cep.replace(/\D/gi, "");
var cepComPontos = cepSemPontos.substring(0, 5) + "-" + cepSemPontos.substring(5, 8);
return cepComPontos;
}
function semPontos(cep) {
cep = cep || this._cep;
_lancarExcecaoSeCepForInvalido(cep);
return cep.replace(/\D/gi, "");
}
function _lancarExcecaoSeCepForInvalido(cep) {
cep = cep || this._cep;
if (!cepEhValido(cep))
throw new Error("Informe um CEP válido para formatação");
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment