What’s wrong with this code?

Asked

Viewed 203 times

-3

A virtual store allows its visitors to filter products by price. There is an array of product prices. A programmer has already created a function maisBaratosQue(valor, precos) that returns an array with prices of products cheaper than the value passed as parameter. Another programmer has already created a function maisCarosQue(valor, precos) that returns an array with prices more expensive than the value passed as parameter. It’s your turn!

Create a function precosEntre(valorMenor, valorMaior, precos) that must use the functions maisBaratosQue and maisCarosQue to return the prices that are between the valorMenor and the valorMaior. Your function should then receive two parameters:

  • valorMenor to represent the minimum value of the prices to be listed

  • valorMaior to represent the maximum value of the prices to be listed

  • precos to represent an array of product prices

It should return an array with all prices between valorMenor and valorMaior

function maisBaratosQue(valor, precos) {
   return precos.filter(p => p <= valor);
}
 
function maisCarosQue(valor, precos){
   return precos.filter(p => p >= valor);
}
function precosEntre(valorMaior, valorMenor, precos) {
  precos.filter( maisBaratosQue() && maisCarosQue(), valor);
     return precosEntre;
}

1 answer

2

maisBaratosQue and maisCarosQue return arrays, not being possible to do precos.filter( maisBaratosQue() && maisCarosQue(), valor).

Given the retractions presented, to implement this method it is necessary to filter the list once with each of the previous methods. Something like:

function precosEntre(valorMaior, valorMenor, precos) {
    var precosEntre = maisBaratosQue(valorMaior, precos);
    precosEntre = maisCarosQue(valorMenor, precosEntre);
  
    return precosEntre;
}

Note that the precosEntre returned by maisBaratosQue is sent to maisCarosQue. It is also noteworthy that the order of the parameters of precosEntre looks swapped. Usually make the smallest and then the highest value.

function maisBaratosQue(valor, precos) {
    return precos.filter(p => p <= valor);
}
 
function maisCarosQue(valor, precos){
    return precos.filter(p => p >= valor);
}

function precosEntre(valorMaior, valorMenor, precos) {
    var precosEntre = maisBaratosQue(valorMaior, precos);
    precosEntre = maisCarosQue(valorMenor, precosEntre);
  
    return precosEntre;
}

var precos = [1, 11, 15, 22];
var precosEntre = precosEntre(20, 10, precos);

console.log(precosEntre);

Browser other questions tagged

You are not signed in. Login or sign up in order to post.