当前位置: 首页 > news >正文

JavaScript 函数式编程之函子相关代码分享

一个简单的函子

// 一个简单的函子
class Container {constructor(value) {this._value = value}map(fn) {return new Container(fn(this._value))}
}// 简单使用
let r = new Container(3).map(v => v + 1).map(v => v * v)
console.log(r)

Maybe 函子

class MayBe {static of(value) {return new MayBe(value)}constructor(value) {this._value = value}map(fn) {return this.isNull() ? MayBe.of(null) : MayBe.of(fn(this._value))}isNull() {return this._value === null || this._value === undefined}
}// 对字符串做大写
let s1 = "hello world"
let s2 = nulllet r1 = MayBe.of(s1).map(v => v.toUpperCase())
console.log(r1)let r2 = MayBe.of(s2).map(v => v.toUpperCase())
console.log(r2)

Either 函子

class Left {static of(value) {return new Left(value)}constructor(value) {this._value = value}map(fn) {return this}
}class Right {static of(value) {return new Right(value)}constructor(value) {this._value = value}map(fn) {return Right.of(fn(this._value))}
}let r1 = Right.of(12).map(v => v + 1)
let r2 = Left.of(12).map(v => v + 1)console.log(r1)
console.log(r2)

IO 函子

const fp = require("lodash/fp")
class IO {static of(value){return new IO(()=>value)}constructor(fn) {this._value = fn}map(fn){return new IO(fp.flowRight(fn, this._value))}
}// 使用
let r = IO.of(process).map(p=>p.execPath)
console.log(r)console.log(r._value())

http://www.mrgr.cn/news/27971.html

相关文章:

  • pip install、yum install和conda install三者技术区分
  • jwt报错,位置:找不到符号 parseClaimsJws(java.lang.String)
  • 并发容器(Map、List、Set)实战及其原理分析
  • 在javascript中对象的键为什么只能是字符串或Symbol?
  • C++速通LeetCode简单第17题-爬楼梯
  • 【JS逆向分析】某药品网站价格(Price)解密
  • NFS在docker环境下无法写入文件的问题解决、NFS文件共享查看挂载客户端列表、mount监控及使用script命令保存屏幕终端输出内容
  • TS.38-2
  • 基于yolov8的无人机检测系统python源码+onnx模型+评估指标曲线+精美GUI界面
  • THREE.js:网页上的3D世界构建者
  • AIGC文本生成
  • Luogu P1874 快速求和 (线性DP)
  • 【MySQL学习】基础指令全解:构建你的数据库技能
  • MySQL之约束
  • ArrayList 源码解析
  • 1.2 交换技术
  • Java contains()方法
  • 电基础理解
  • 轮转数组 给定一个整数数组 nums,将数组中的元素向右轮转 k 个位置,其中 k 是非负数
  • Linux设备驱动开发:从基础理论到实战经验的全面解析