偏函数的应用

偏函数的用法是指创建一个调用另外一个变量或参数已经预置的函数的函数。这段话读起来比较抽象,可以看如下一个示例。

通常写一个判断数据类型的函数可以使用如下方式。

const toString = Object.prototype.toString;
const isString = x => toString.call(x) === '[object String]'
const isArray = x => toString.call(x) === '[object Array]'

为了写类型校验的函数可能要写很多个形如这样的函数。这样就会导致出现很多冗余的代码。

为了解决这个问题,可以引入一个类似工厂作用的函数,其它的函数都通过这个工厂函数来创建。

const toString = Object.prototype.toString;
const isType = type => x => toString.call(x) === `[object ${type}]`;

const isString = isType('String');
const isArray = isType('Array');

这种通过指定部分参数来产生一个定制函数的形式就是偏函数。

如果您觉得本文对您有用,欢迎捐赠或留言~
微信支付
支付宝

发表评论

您的电子邮箱地址不会被公开。 必填项已用 * 标注