[Javascript Crocks] Compose Functions for Reusability with the Maybe Type
JavaScript for The with type Compose Functions
2023-09-14 09:00:49 时间
We can dot-chain our way to great success with an instance of Maybe, but there are probably cases where you need to apply the same series of transformations against different Maybe
s. In this lesson, we’ll look at some point-free versions of some common Maybe methods and see how we can compose them together to get a reusable function that can be applied to any Maybe instance.
We are going to rewrite the following code by using function composion:
const crocks = require('crocks'); const {and, isString, Maybe, prop, safe, option, map, alt, chain} = crocks; const {not, isEmpty, compose, converge, join, split, toLower} = require('ramda'); ///////////////UTILS///////////////// const joinKey = compose(join('_'), split(' '), toLower); const isNotEmpty = compose( not, isEmpty ) const isNonEmptyString = and(isNotEmpty, isString); /*const isNonEmptyString = R.converge( R.and, [ isNotEmpty, isString ] );*/ const createUrl = key =>`https://egghead.io/articles/${joinKey(key)}`; ////////////////MAIN//////////////// const article = { id: 1, name: 'Learn FP with this one weird trick' }; /* const getUrl = obj => prop('name', obj) // Maybe(string) .chain(safe(isNonEmptyString)) // Maybe(string) --safe(isNonEmptyString)--> Maybe(Maybe(String)) --chain--> Maybe(String) .alt(Maybe.of('Nope')) // Nothing -> Just('Nope') .map(createUrl) .option('default'); */ const getSafeName = compose( chain(safe(isNonEmptyString)), prop('name') ); const getUrlOrDefault = compose( option('Not valid URL'), map(createUrl) ); const getUrl = compose( getUrlOrDefault, getSafeName ); const getUrlOrNope = compose( getUrlOrDefault, alt(Maybe.of('Nope')), getSafeName ) const res = getUrl(article); console.log(res);
相关文章
- JavaScript笔记(20)
- JavaScript基础之for
- 【说站】javascript中for...of循环的原理
- JavaScript刷LeetCode拿offer-js版字典_2023-02-28
- JavaScript刷LeetCode贪心算法篇
- 解决The HTTP request is not acceptable for the requested resource
- WebStorm 2023 for Mac 永久激活版: 最强大的JavaScript集成开发环境
- ORA-53253: The metadata for the new DICOM object is invalid. ORACLE 报错 故障修复 远程处理
- ORA-13605: The specified task or object string does not exist for the current user. ORACLE 报错 故障修复 远程处理
- JavaScript学习总结(十六)——Javascript闭包(Closure)详解编程语言
- JavaScript学习总结(十三)——极简主义法编写JavaScript类详解编程语言
- loopOracle中的循环编程:For Loop游标(oracle游标for)
- 技巧使用Oracle的FOR循环加快编程效率(oracle的for循环)
- 学习Oracle中的For语句搭建数据库应用的基础(oracle for语法)
- 在IE中调用javascript打开Excel表
- 用JavaScript限制textarea输入长度(For:IE、Firefox...)[
- javascript写的一个表单动态输入提示的代码
- javascript函数参数原来是可以有缺省值的
- javascript循环语句while、do-while、for-in、for用法区别
- 深入理解JavaScript是如何实现继承的
- JavaScript中for-in遍历方式示例介绍
- javascript跨域的4种方法和原理详解
- javascript数组遍历for与forin区别详解