这可以重构使用泛型功能原理? [英] Can this be refactored to use generic functional principles?
问题描述
比较函数升序
接受两个参数 - a
和 b
。它必须返回一个比较两个整数的整数。
我有一个我想按名称排序的列表,所以我写了下面的函数。
是否有一个可用于组合这两个函数的函数式习惯用法,而不是让 byName
负责撰写得到的函数?
const ascending =(a,b)=> a.localeCompare(b)中;
const byName =(i)=> i.get(姓名);
const useTogether =(... fns)=> ...; //是否有像这样的惯用功能?
// usage
items.sort(useTogether(byName(ascending)));
我不确定它是否满足您的要求,重新寻找,但这里有一个可能的表达方式,你的 useTogether
(有一些不同的签名)可以用于WORK。我不知道一个标准函数的效果。
const上升=(a,b)=> a.localeCompare(b); const byName =(i)=> i ['name']; const useTogether =(selector,consumer)=> (... fnArgs)=> consumer(... fnArgs.map(selector)); var items = [{name:C},{name:A},{name:B}]; console.log(items.sort( useTogether(byName,ascending)))
A comparator function ascending
accepts two arguments - a
and b
. It must return an integer comparing the two.
I have a list that I want to sort by name, so I wrote the following functions.
Is there a functional idiom I can use to combine these two functions, rather than having byName
take responsibility for composing the resulting function?
const ascending = (a, b) => a.localeCompare(b);
const byName = (i) => i.get('name');
const useTogether = (...fns) => ...; // is there an idiomatic function like this?
// usage
items.sort(useTogether(byName(ascending)));
I'm not sure if it satisfies what you're looking for, but here is one possible formulation of your useTogether
(with a somewhat different signature) that does WORK. I'm not aware of a standard function with precisely that effect.
const ascending = (a, b) => a.localeCompare(b);
const byName = (i) => i['name'];
const useTogether = (selector, consumer) => (...fnArgs) => consumer(...fnArgs.map(selector));
var items = [{ name: "C" }, { name: "A" }, { name: "B" }];
console.log(
items.sort(useTogether(byName, ascending))
)
这篇关于这可以重构使用泛型功能原理?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!