大前端:练习题-基于以下代码完成练习题

super.js

class Container {
	static of(value) {
		return new Container(value);
	}
	constructor(value) {
		this._value = value;
	}
	map(fn) {
		return Container.of(fn(this._value));
	}
}
class Maybe {
	static of(x) {
		return new Maybe(x);
	}
	isNothing() {
		return this._value === null || this._value === undefined;
	}
	constructor(x) {
		this._value = x;
	}
	map(fn) {
		return this.isNothing() ? this : Maybe.of(fn(this._value));
	}
}
module.exports = { Container, Maybe };

app.js
练习1:使用 fp.add(x, y) 和 fp.map(f, x) 创建一个能让 functor 里的值增加的函数 ex1

const fp = require('loadsh/fp');
const { Maybe, Container } = require('./support');
let maybe = Maybe.of([5, 6, 1]);
let ex1 = () => {
	maybe.map((x) => fp.map(fp.add(1), x));
};
console.log(ex1);

练习2:实现一个函数 ex2,能够使用 fp.first 获取列表的第一个元素

let xs = Container.of(['do', 'ray', 'me', 'fa', 'so', 'la', 'ti', 'do']);
let ex2 = xs.map((x) => fp.first(x));
console.log(ex2);

练习3:实现一个函数 ex3,使用 safeProp 和 fp.first 找到 user 的名字的首字母

let safeProp = fp.curry(function (x, o) {
	return Maybe.of(o[x]);
});
let user = { id: 2, name: 'Albert' };
let ex3 = fp.flowRight(fp.map(fp.first), safeProp('name'));
console.log(ex3(user));

练习4:使用 Maybe 重写 ex4,不要有 if 语句

let ex4 = function (n) {
	if (n) {
		return parseInt(n);
	}
};

let ex4_2 = fp.flowRight(fp.map(parseInt), Maybe.of);
console.log(ex4_2(2));
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值