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的更多相关文章

  1. [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 ...

  2. [转]Node.js tutorial in Visual Studio Code

    本文转自:https://code.visualstudio.com/docs/nodejs/nodejs-tutorial Node.js tutorial in Visual Studio Cod ...

  3. myeclipse中导入js报如下错误Syntax error on token "Invalid Regular Expression Options", no accurate correc

    今天在使用bootstrap的时候引入的js文件出现错误Syntax error on token "Invalid Regular Expression Options", no ...

  4. [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 ...

  5. [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 ...

  6. 【JS】Advanced1:Object-Oriented Code

    Object-Oriented Code 1. var Person = function (name) { this.name = name; }; Person.prototype.say = f ...

  7. 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 ...

  8. [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 ...

  9. [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 ...

随机推荐

  1. Emmet学习教程

    Emmet (前身为 Zen Coding) 是一个能大幅度提高前端开发效率的一个工具,Emmet是很成熟的并且非常适用于编写HTML/XML 和 CSS 代码的前端开发人员,但也可以用于编程语言.所 ...

  2. oracle数据库spfile

    http://blog.chinaunix.net/uid-8996530-id-3195808.html http://www.cnblogs.com/HondaHsu/p/4885318.html ...

  3. Lucy_Hedgehog techniques

    在project euler 的第\(10\)题的 \(forum\) 中 Lucy Hedgehog 提到的这种方法. 求 \(n\) 以内素数个数以及求 \(n\) 以内素数和的算法. 定义\(S ...

  4. Windows 7 下快速挂载和分离VHD文件的小脚本

    1.保存以下代码为VDM.vbs,放在Windows\system32下 Dim ArgsSet Args = WScript.ArgumentsTranArgs = " "For ...

  5. oled屏幕模块

    oled屏幕模块似乎是厂家提供的 也许可以根据屏幕驱动芯片去写 根据现在了解的芯片一般有两个:SH1106和SSD1306 不过这次我们用的是SSD1306芯片驱动的屏幕 下面是从裸屏到模块的pcb: ...

  6. python3 用递归方法列出所有目录与文件

    python3 用递归方法列出所有目录与文件 # !/usr/bin/env python # -*- coding:utf-8 -*- # Author:Hiuhung Wan import os ...

  7. C# 泛型特化

    C# 泛型不是 C++ 的模板类,并不支持特化和偏特化,但是使用一些技巧可以在一定程度上达到相同的目的. 原文是 po 在 stackoverflow 上的一个回答:A: Generic indexe ...

  8. ThreadPoolExecutor – Java Thread Pool Example(java线程池创建和使用)

    Java thread pool manages the pool of worker threads, it contains a queue that keeps tasks waiting to ...

  9. CNTK 搞深度学习-1

    CNTK 搞深度学习 Computational Network Toolkit (CNTK) 是微软出品的开源深度学习工具包.本文介绍CNTK的基本内容,如何写CNTK的网络定义语言,以及跑通一个简 ...

  10. vue指令概览

    原文 简书原文:https://www.jianshu.com/p/5fd47b7422fd 大纲 1.什么是vue指令 2.向指令中传入参数 3.指令中带入修饰符 4.指令的缩写 5.常见的vue指 ...