【发布时间】:2018-05-18 04:24:13
【问题描述】:
比较器函数 ascending 接受两个参数 - a 和 b。它必须返回一个整数来比较两者。
我有一个想要按名称排序的列表,所以我编写了以下函数。
我是否可以使用函数式惯用语来组合这两个函数,而不是让byName 负责组合生成的函数?
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)));
【问题讨论】:
-
顺便说一句,按字符串对 JavaScript 数组进行排序最好使用 String#localeCompare 完成,因此您的排序函数将是
const ascendingString = (a, b) => a.localeCompare(b);,这是不可组合的。 -
const ascending = g => (a, b) =>((a,b) => a < b ? ... )(g(a), g(b));然后item.sort(ascending(by => by.name)) -
看看thenBy.js。
标签: javascript functional-programming