[JS Compose] 1. Refactor imperative code to a single composed expression using Box
After understanding how Box is, then we are going to see how to use Box to refacotr code, to un-nested expression.
For example, we have code:
const moneyToFloat = str => {
const cost = str.replace(/\$/g, '');
return parseFloat(cost);
} const percentToFloat = str => {
const cost = parseFloat(str.replace(/\$/g, ''));return cost * 0.01;
} const applyDiscount = (price, prec) => {
const cost = moneyToFloat(price);
const p = percentToFloat(prec);
return cost - cost * p;
} const result = applyDiscount('$5.00', '20%')
console.log(result) //
So how it would be when we using Box version:
const moneyToFloat = str => {
const cost = str.replace(/\$/g, '');
return parseFloat(cost);
} const moneyToFloat = str =>
Box(str)
.map(s => s.replace(/\$/g, ''))
.map(s => parseFloat(cost))
Well, nothing really impress here, we put 'str' into Box, and using map to do all the logic.
const percentToFloat = str => {
const cost = parseFloat(str.replace(/\$/g, ''));
return cost * 0.01;
} const percentToFloat = str =>
Box(str.replace(/\$/g, ''))
.map(s => parseFloat(s))
.map(s => s * 0.01)
This part, notice we un-nest 'parseFloat(str.replace(...))', make logic more readable by using map.
const applyDiscount = (price, prec) => {
const cost = moneyToFloat(price);
const p = percentToFloat(prec);
return cost - cost * p;
} const applyDiscount = (price, prec) =>
moneyToFloat(price)
.fold(cost => percentToFloat(prec)
.fold(p => cost - cost * p))
Notice here, because 'moneyToFloat' return a Box, so we are able to chain map on that.
And 'cost', we can use clouse to remember 'cost', and chain 'fold' on precentToFloat. The reason we use 'fold' instead of 'map', is 'fold' we can get value out of Box.
const Box = x =>
({
map: f => Box(f(x)),
fold: f => f(x),
toString: () => `Box(${x})`
}) const moneyToFloat = str =>
Box(str)
.map(s => s.replace(/\$/g, ''))
.map(s => parseFloat(cost)); const percentToFloat = str =>
Box(str.replace(/\$/g, ''))
.map(s => parseFloat(s))
.map(s => s * 0.01); const applyDiscount = (price, prec) =>
moneyToFloat(price)
.fold(cost => percentToFloat(prec)
.fold(p => cost - cost * p)) const result = applyDiscount('$5.00', '20%')
console.log(result) //
[JS Compose] 1. Refactor imperative code to a single composed expression using Box的更多相关文章
- [JS Compose] 3. Use chain for composable error handling with nested Eithers (flatMap)
We refactor a function that uses try/catch to a single composed expression using Either. We then int ...
- [转]Node.js tutorial in Visual Studio Code
本文转自:https://code.visualstudio.com/docs/nodejs/nodejs-tutorial Node.js tutorial in Visual Studio Cod ...
- myeclipse中导入js报如下错误Syntax error on token "Invalid Regular Expression Options", no accurate correc
今天在使用bootstrap的时候引入的js文件出现错误Syntax error on token "Invalid Regular Expression Options", no ...
- [JS Compose] 2. Enforce a null check with composable code branching using Either
We define the Either type and see how it works. Then try it out to enforce a null check and branch o ...
- [JS Compse] 4. A collection of Either examples compared to imperative code
For if..else: const showPage() { if(current_user) { return renderPage(current_user); } else { return ...
- 【JS】Advanced1:Object-Oriented Code
Object-Oriented Code 1. var Person = function (name) { this.name = name; }; Person.prototype.say = f ...
- Node.js and Forever “exited with code: 0”
CentOs 6.5 using root acount, I have a working Node.js Express app: root@vps [/home/test/node]# npm ...
- [Functional Programming Monad] Refactor Stateful Code To Use A State Monad
When we start to accumulate functions that all work on a given datatype, we end up creating a bunch ...
- [JS Compose] 0. Understand 'Box' or 'Container', they are just like Array!
We'll examine how to unnest function calls, capture assignment, and create a linear data flow with a ...
随机推荐
- 安卓View的缓冲机制
View组件显示的内容能够通过cache机制保存为bitmap, 主要有下面方法: void setDrawingCacheEnabled(boolean flag), Bitmap getDr ...
- 19,tuple多元数组
#include <iostream> #include <tuple> using namespace std; void main() { char ch = 'a'; ; ...
- 洛谷P3273 [SCOI2011]棘手的操作
题目描述 有N个节点,标号从1到N,这N个节点一开始相互不连通.第i个节点的初始权值为a[i],接下来有如下一些操作:U x y: 加一条边,连接第x个节点和第y个节点A1 x v: 将第x个节点的权 ...
- Cisco安全防护读书笔记之一Cisco系统设备协议漏洞
650) this.width=650;" onclick='window.open("http://blog.51cto.com/viewpic.php?refimg=" ...
- BZOJ3926: [Zjoi2015]诸神眷顾的幻想乡(广义后缀自动机)
Description 幽香是全幻想乡里最受人欢迎的萌妹子,这天,是幽香的2600岁生日,无数幽香的粉丝到了幽香家门前的太阳花田上来为幽香庆祝生日. 粉丝们非常热情,自发组织表演了一系列节目给幽香看. ...
- BZOJ1195: [HNOI2006]最短母串(Trie图,搜索)
Description 给定n个字符串(S1,S2,„,Sn),要求找到一个最短的字符串T,使得这n个字符串(S1,S2,„,Sn)都是T的子串. Input 第一行是一个正整数n(n<=12) ...
- c3p0的经常使用配置方式
1:第一种方式很easy c3p0.driverClass=com.mysql.jdbc.Driver c3p0.jdbcUrl=jdbc:mysql://localhost:3308/databas ...
- ajax中的POST和GET传值
ajax中的POST和GET传值 转自:http://www.cnblogs.com/jtome/archive/2008/12/04/1347864.html Ajax中我们经常用到get和post ...
- sampleviewer add menu item error 'assert'
可以跟踪到 mfc提供的源代码内部,(注:如果打开了mfc源代码,设置了断点,但是跟不进去,那就需要更新PDB文件,具体网上搜)打开 wincore.cpp文件(D:\Program Files\Mi ...
- ubuntu下安装phpredis的模块扩展
1.前提是先安装好redis,然后再安装phpredis. .. 2.先下载phpredis-master.tar.gz安装包... 详细详情例如以下: <span style="co ...