习题
最后更新于:2022-04-02 04:17:37
[TOC]
## 习题1
```
// 示例数据
var CARS = [
{name: "Ferrari FF", horsepower: 660, dollar_value: 700000, in_stock: true},
{name: "Spyker C12 Zagato", horsepower: 650, dollar_value: 648000, in_stock: false},
{name: "Jaguar XKR-S", horsepower: 550, dollar_value: 132000, in_stock: false},
{name: "Audi R8", horsepower: 525, dollar_value: 114200, in_stock: false},
{name: "Aston Martin One-77", horsepower: 750, dollar_value: 1850000, in_stock: true},
{name: "Pagani Huayra", horsepower: 700, dollar_value: 1300000, in_stock: false}
];
// 练习 1:
// ============
// 使用 _.compose() 重写下面这个函数。提示:_.prop() 是 curry 函数
var isLastInStock = function(cars) {
var last_car = _.last(cars);
return _.prop('in_stock', last_car);
};
// 使用 compose
var isLastInStock = _.compose(_.prop('in_stock'), _.last);
练习 2:
// 使用 _.compose()、_.prop() 和 _.head() 获取第一个 car 的 name
var nameOfFirstCar = _.compose(_.prop('name'), _.head);
/ 彩蛋 1:
// ============
// 使用 compose 重构 availablePrices
var availablePrices = function(cars) {
var available_cars = _.filter(_.prop('in_stock'), cars);
return available_cars.map(function(x){
return accounting.formatMoney(x.dollar_value);
}).join(', ');
};
// 解答
var formatPrice = _.compose(accounting.formatMoney,_.prop("dollar_value"))
var availablePrices = compose(_.join, _.map(formatPrice),_.filter,_.prop('in_stock'))
```
';