这可以重构为使用通用功能原则吗? [英] Can this be refactored to use generic functional principles?

查看:20
本文介绍了这可以重构为使用通用功能原则吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

比较器函数 ascending 接受两个参数 - ab.它必须返回一个比较两者的整数.

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.

我可以使用函数式惯用语来组合这两个函数,而不是让 byName 负责组合生成的函数吗?

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))); 

推荐答案

我不确定它是否满足您的要求,但这里是您的 useTogether(与一个有点不同的签名)确实有效.我不知道具有这种效果的标准函数.

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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆