How do I determine what value javascript should use for logical operations on objects?
I'm creating a competency object that needs the following features:
- Encapsulates the logic of creating a competency: month / year in MM / YYYY format
- When concatenated with string it returns the format MM / YYYY
- Two Competency objects can be compared
The functions str_pad () and checkdate () were used from the php.js library
My problem lies in comparing two objects. Since I have two variables data1 and data2 , I would like to compare them to know which one is larger or if both are of equal competence using the javascript logical operators directly between the variables.
ex: data1 > data2; data1 == data2;
I've tried to override prototype.value but it did not work.
Competencia = function(competencia){
var date = this.dateFromCompetencia(competencia);
Object.defineProperty(this, 'date', {
value: date
});
};
Competencia.prototype.toString = function () {
return this.formatado;
};
Object.defineProperties(Competencia.prototype, {
formatado: {
get: function(){
return this.competencia.replace(/^(\d{2})(\d{4})$/,"$1/$2");
}
},
competencia: {
get: function(){
return this.mes + this.ano;
}
},
mes: {
get: function(){
return mes = str_pad(String(this.date.getMonth()+1), 2, '0', 'STR_PAD_LEFT');
}
},
ano: {
get: function(){
return ano = String(this.date.getFullYear());
}
},
proxima:{
value: function(){
var mes = str_pad(String(Number(this.mes)+1), 2, '0', 'STR_PAD_LEFT');
var comp= mes + this.ano;
console.log(comp);
return new Competencia(comp);
}
},
dateFromCompetencia: {
value: function (competencia) {
competencia = String(competencia).replace(/\D/g, '');;
var mes = competencia.substr(-6,2);
var ano = competencia.substr(-4);
if(!checkdate(mes, 01, ano))
throw new Error('Competencia incorreta');
return new Date(ano, Number(mes)-1);
}
}
});
// função str_pad e checkdate do site phpjs.org
function str_pad(e,t,n,r){var i="",s;var o=function(e,t){var n="",r;while(n.length<t){n+=e}n=n.substr(0,t);return n};e+="";n=n!==undefined?n:" ";if(r!=="STR_PAD_LEFT"&&r!=="STR_PAD_RIGHT"&&r!=="STR_PAD_BOTH"){r="STR_PAD_RIGHT"}if((s=t-e.length)>0){if(r==="STR_PAD_LEFT"){e=o(n,s)+e}else if(r==="STR_PAD_RIGHT"){e=e+o(n,s)}else if(r==="STR_PAD_BOTH"){i=o(n,Math.ceil(s/2));e=i+e+i;e=e.substr(0,t)}}return e}
function checkdate(e,t,n){return e>0&&e<13&&n>0&&n<32768&&t>0&&t<=(new Date(n,e,0)).getDate()}
try{
fev14 = new Competencia('02/2014');
jan15 = new Competencia('01/2015');
fev2014 = new Competencia('02/2014');
document.getElementById('comparacao1').innerHTML = fev14 > jan15;
document.getElementById('comparacao2').innerHTML = fev14 > fev2014;
}catch(e){
alert(e.message);
}
Comparação <b>fev14 > jan15</b> -
<b>Resultado</b>: <span id="comparacao1"></span>
<b>Esperado</b>: false;
<br>
<br>
Comparação <b>fev14 == fev2014</b> -
<b>Resultado</b>: <span id="comparacao2"></span>
<b>Esperado</b>: true;