It makes no sense the existence of the function algorithm messenger()
.
messenger()
is dependent on the external variable txt
.
- The first use of the function
detector()
is harmless in no way affecting the data flow.
- The function
msg()
makes a more rational use of function detector()
and only this should be maintained.
It’s better to work existing algorithms than create something new based on a collection of problems.
Analyzing the detector function:
function detector(){
var detector = txt.indexOf("!")
if(detector>-1)
return true
}
The first change will be the creation of a parameter texto
making the function independent of external variable:
function detector(texto){
var detector = texto.indexOf("!")
if(detector>-1)
return true
}
Looking carefully at the sentence:
if(detector>-1)
return true
It is a redundancy allied to an indefinition. This sentence says to return true if the variable detector
be true, but if it is not true the return is undefined. So to remove the redundancy together with the undefined just do:
function detector(){
var detector = txt.indexOf("!")
return detector > -1; //Sempre sera retornado o valor da comparação independente de teste prévio.
}
Speaking of redundancy you have declared a variable with the same name as the function and this is a serious mistake because it prevents you from performing recursions and corrections. So it fits the simplification:
function detector(texto) {
return texto.indexOf("!") > -1;
}
The same goes for the function msg()
it is possible to break with the dependence on external variables:
function msg(texto){
if(detector(texto)==true){
return "true"
}else{
return "false"
}
}
At the same time you remove the redundancies, and for that I used the native method Boolean.prototype.toString()
that returns a string representing the specific Boolean object:
function msg(texto) {
return detector(texto).toString();
}
Putting it all together:
//Detector de !
function detector(texto) {
return texto.indexOf("!") > -1;
}
//reponder a mensagem
function msg(texto) {
return detector(texto).toString();
}
console.log(msg("teste 1 !"));
console.log(msg("teste 2 "));
Without the need for a third function.
javascript uses lexical context, the txt variable has to exist at the moment that vc declares the detector function... I think the best approach there is to send txt as argument of the detector function
– guijob
@guijob but the txt of
messenger(txt)
is not considered a variable?– didi
Yes, but where you define the function is what counts, not where you call.. in messenser vc calls the detector function... javascript will look for txt in the context of where you defined the function and not in the context you called it
– guijob
@guijob ah entendi vlw
– didi