fp纯函数训练小记

第一题

const fp = require('lodash/fp');
const 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
  }
]
// 练习一
const f = fp.flowRight(fp.prop('in_stock'),fp.last);//从右到左,依次取最后一个对象,对象的属性in_stock
console.log(f(cars));

//练习二
const f1 = fp.flowRight(fp.prop('name'),fp.first);//从右到左,依次取第一个对象,对象的属性name
console.log(f1(cars));

//练习三
let _average = function (xs) {
  return fp.reduce(fp.add, 0 ,xs) / xs.length
}//无须改动
let averageDollarValue = function (cars){
  let dollar_values = fp.map(function(car){
    return car.dollar_value
  },cars)
  return _average(dollar_values)
}
//优化如下
const f3 = fp.flowRight(_average,fp.map(fp.prop('dollar_value')))
console.log(f3(cars));

//联系四
let _underscore = fp.replace(/\W+/g,'_')//无须改动
//优化如下 依次遍历数组,取出name、大写变小写,调用正则函数
const sanitizeNames = fp.flowRight(fp.map(_underscore),fp.map(fp.toLower),fp.map(fp.prop('name')))
console.log(sanitizeNames(cars));

第二题

const fp = require('lodash/fp')
const {Maybe , Container} = require('./main')
let maybe = Maybe.of([5,6,1])
//联系一
let ex1 = (x) =>{
  //使用fp.add(x,y) fp.map(f,x)创建一个能让functor里的值增加的函数exl
  let f1 = fp.flowRight(fp.map(fp.add(x)))
  return maybe.map(f1);
}
console.log(ex1(1));

//练习二
let xs = Container.of(['do','ray','me','fa','so','la','ti','do']);
//使用fp.first获取列表的第一个元素
let ex2 = () =>{
  return xs.map(fp.first)._value
}
console.log(ex2());

//练习三
//使用safeProp和fp.first找到user的名字的首字母
let safeProp = fp.curry(function (x,o){
  return Maybe.of(o[x])
})
let user = {id:2,name:'Albert'}
let ex3 = (user) =>{
  //使用萨芬Prop得到name的值,然后遍历字符串输出第一个字母
  let f = safeProp('name')(user).map(fp.first)._value;
  return f
}
console.log(ex3(user));

//练习四
//使用Maybe重写ex4 不要有if语句
let ex4 = function (n) {
  // if(n){
  //   return parseInt(n)
  // }
  return Maybe.of(n).map(parseInt)._value
}
console.log(ex4(1));
console.log(ex4(null));
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容