gpt4 book ai didi

javascript - 我如何像 Elm 那样在 JS 中传递函数?

转载 作者:行者123 更新时间:2023-11-30 07:02:07 24 4
gpt4 key购买 nike

我刚开始学习函数式编程,但我很难弄清楚如何做到这一点(如果这值得麻烦的话)。我研究了柯里化(Currying),但不确定这是否是我需要走的方向??还是管道?

我想从一个值开始,然后通过不同的函数将其通过管道传递。 Underscore 有类似的 'chain' 方法。但是我不想使用原型(prototype)来做到这一点。我意识到解决方案可能与我的目标语法不匹配。

Elm 有 |> 语法(如下),看起来非常漂亮

// what i'd like to do (or similar) in JS *without using prototype*
num = ("(123) 456-7890")
.removeDashes()
.removeParens()
.removeSpaces()

// what elm does
"(123) 456-7890"
|> removeDashes
|> removeParens
|> rem


// functions I wrote so far

removeDashes = function(str) {
return str.replace(/-/g, '');
};

removeParens = function(str) {
return str.replace(/\(|\)/g, '');
};

removeSpaces = function(str) {
return str.replace(/\s/g, '');
};


// what i'm currently doing

num =
removeDashes(
removeParens(
removeSpaces(
"(123) 456-7890"")));

最佳答案

如果您想尝试使用 JavaScript 进行函数式编程,我建议您使用像 Underscore、Lodash 或 Ramda 这样的库。它们都具有组合/管道功能。大多数时候,您希望将它与这些库也提供的某种形式的部分应用程序结合起来。

无论如何,尝试自己实现它是一个很好的练习。我会这样解决...

/* Asumes es5 or higher */

function pipe (firstFn /* ...restFns */) {
var _ = null;
var _slice = Array.prototype.slice;
var restFns = _slice.call(arguments, 1) || [];


return function exec_fns() {
var args = _slice.call(arguments, 0, 1);

return restFns.reduce(function(acc, fn) {
return fn.call(_, acc);
}, firstFn.apply(_, args));
}
}

removeDashes = function(str) {
return str.replace(/-/g, '');
};

removeParens = function(str) {
return str.replace(/\(|\)/g, '');
};

removeSpaces = function(str) {
return str.replace(/\s/g, '');
};


console.log(pipe(
removeDashes,
removeParens,
removeSpaces
)("(123) 456-7890") == "1234567890")

Fogus 的 Functional JavaScript 也是深入研究这种编程风格的好资源

关于javascript - 我如何像 Elm 那样在 JS 中传递函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32485401/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com