Explicador de Por el precio correcto
Objetivo de este acertijo: Crear la función underAHundred
y usarla como filtro.
Tutorial de la solución: La función underAHundred
debe tomar un object de reseña de un hotel almacenado en hotel
y luego devolverá si el .price
de ese hotel
es menor que 100. Esa prueba se escribe como hotel.price < 100
, y ésta debe usarse como el valor return
.
Para usar la función underAHundred
como filtro para grasslandHotels
, usa el método .filter()
en ella. El argumento de .filter()
es una función de devolución de llamada, underAHundred
, que no tiene paréntesis después de ella. grasslandHotels.filter(underAHundred)
devolverá una copia de grasslandHotels
, pero solo los que tienen una propiedad .price
menor que 100.
Solución del código de ejemplo:
(Pulsa a continuación para revelar)
import { getData, findHotels } from 'grasshopper.reviews';
import { averageRating } from 'myFunctions';
let grasslandHotels = getData('Grassland', findHotels);
function underAHundred(hotel) {
return hotel.price < 100;
}
let affordableHotels = grasslandHotels.filter(underAHundred);
console.log('Average Rating in Grassland under $100:');
console.log(averageRating(affordableHotels));
Conceptos de JavaScript: funciones de devolución de llamada, funciones de llamada, bloque de código (función), .filter()
, import
Código adicional (código oculto que se ejecuta antes del código del acertijo):
let _hotelReviews = [
{
type: 'Hopaday Inn',
city: 'Hopalot',
price: 138,
rating: 4.0
},
{
type: 'Hopaday Inn',
city: 'Hopalot',
price: 78,
rating: 3.8
},
{
type: 'Hopaday Inn',
city: 'Hoptropolis',
price: 86,
rating: 2.4
},
{
type: 'Hopaday Inn',
city: 'Hoptropolis',
price: 126,
rating: 4.4
},
{
type: 'Hopaday Inn',
city: 'Grassland',
price: 98,
rating: 3.0
},
{
type: 'Hopaday Inn',
city: 'Grassland',
price: 245,
rating: 4.6
},
{
type: 'The Grassy Suites',
city: 'Hopalot',
price: 189,
rating: 4.4
},
{
type: 'The Grassy Suites',
city: 'Hopalot',
price: 111,
rating: 2.4
},
{
type: 'The Grassy Suites',
city: 'Hoptropolis',
price: 171,
rating: 2.8
},
{
type: 'The Grassy Suites',
city: 'Hoptropolis',
price: 191,
rating: 2.8
},
{
type: 'The Grassy Suites',
city: 'Grassland',
price: 185,
rating: 4.1
},
{
type: 'The Grassy Suites',
city: 'Grassland',
price: 86,
rating: 3.5
},
{
type: 'Hopton Inn',
city: 'Hopalot',
price: 160,
rating: 2.4
},
{
type: 'Hopton Inn',
city: 'Hoptropolis',
price: 226,
rating: 4.5
},
{
type: 'Hopton Inn',
city: 'Hoptropolis',
price: 192,
rating: 3.5
},
{
type: 'Hopton Inn',
city: 'Grassland',
price: 189,
rating: 4.9
}
];
const getData = (city, afunction) => {
afunction(city.trim().charAt(0).toUpperCase() + city.trim().toLowerCase().slice(1));
};
const findHotels = city => {
_hotelReviews.filter( review => review.city === city);
};
const averageRating = hotelList => {
hotelList.map(hotel => hotel.rating).reduce((a, b) => a + b) / hotelList.length
};