有什么办法让一个函数的返回可以通过一个属性访问吗? [英] Is there any way to make a function's return accessible via a property?
问题描述
我是一名JS开发人员,正在尝试函数式编程思想,并且我想知道是否还有在编写诺言链的方式中使用同步函数链。
例如:
function square(num){
返回num * num;
}
let foo = 2
let a = square(foo)// => 4
let b = square(square(foo))// =>> 16
足够公平,但我想做的事情(通常使代码解析更容易)是通过将这些方法作为链的第一个参数传递来链接在一起。所以,这样的事情可以工作:
let c = square(foo)
.square()
.square()// => 256
有没有办法用vanilla javascript做到这一点,或者这是我必须修改Function.prototype做什么?
您可能对身份仿函数感兴趣 - 它允许您提升任何函数以操作身份的值 - square
和 mult
下方。您可以获得一个可链接的界面,而无需触及原生原型。^ _ ^
const Identity = x => ({runIdentity:x,map:f => Identity(f(x))})const square = x => x * xconst mult = x => y => x * ylet result = Identity(2).map(square).map(square).map(square).map(mult(1000)).runIdentity console.log(result)// 256000
I'm a JS dev, experimenting with functional programming ideas, and I'm wondering if there's anyway to use chains for synchronous functions in the way the promise chains are written.
For example:
function square (num) {
return num * num;
}
let foo = 2
let a = square(foo) //=> 4
let b = square(square(foo)) //=> 16
Fair enough, but what I'd like to do (often to make code parsing easier) is to chain together those methods by passing that in as the first parameter of a chain. So that something like this would work:
let c = square(foo)
.square()
.square() //=> 256
Is there any way to do this with vanilla javascript, or is this something I'd have to modify the Function.prototype to do?
You might be interested in the Identity functor – it allows you to lift any function to operate on the Identity's value – eg, square
and mult
below. You get a chainable interface without having to touch native prototypes ^_^
const Identity = x => ({
runIdentity: x,
map: f => Identity(f(x))
})
const square = x => x * x
const mult = x => y => x * y
let result = Identity(2)
.map(square)
.map(square)
.map(square)
.map(mult(1000))
.runIdentity
console.log(result)
// 256000
这篇关于有什么办法让一个函数的返回可以通过一个属性访问吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!