[Functional Programming] Functional JS - Pointfree Logic Functions

Learning notes. Video.

 

Less than:

If you use 'ramda', you maybe know 'lt, gt'..

R.lt(2, 1); //=> false

Is '2' less than '1' , the result is false. We can see that the data is actually come first which is 2.

Normally in FP, we want data come last. What we can do is using 'flip' from 'crocks.js'.

const {flip} = require('crocks')
const {lt} = require('ramda')

// isLessTen :: Number -> Boolean
const isLessTen = flip(lt, 10)
isLessThen(9) // true

 

If/Else:

const diff10 = v => {
    let result = null;
    if (v < 10) {
        result = v - 10
    } else {
        result = v + 10
    }
}

We can use 'ifElse' from 'crocks.js':

const {not, ifElse} = require('crocks');
const {add, lt} = require('ramda');

const declarative = ifElse(
    not(flip(lt, 10)), // if the given number is greater than 10
    add(10), // then plus 10
    add(-10) // go negitive
)

 

or/and:

复制代码
/**
 * Or && And
 */
// Just check one object has length prop is not enough
// Because Array has length, function has length
// Array is also object
const _hasLengthProp = x =>
    (isObject(x) && x.length !== undefined) || isArray(x);

// hasLengthProp :: a -> Boolean
const hasLengthProp = or(isArray, and(isObject, hasProp('length')));
log(hasLengthProp([])) // true
复制代码

 

[100] === [100]?

The Answer is : false

JS consider each [] is a new Object. 

In this case, we can use 'propEq' from 'crocks.js' to save us some safe checking:

const _aIs100A = x => isObject(x) && x.a === [100];
log(
    _aIs100A({a: [100]})
) // false, because it consider [100] is a new object
const aIs100A = and(isObject, propEq('a', [100]))
log(
    aIs100A({a: [100]}) // true
)

 

ES5 way to check Array is typeof Array, and Date is typeof Date:

const _isArray = x => Object.prototype.toString.call(x) === '[object Array]';
const _isDate = x => Object.prototype.toString.call(x) === '[object Date]';

 

posted @   Zhentiw  阅读(252)  评论(0编辑  收藏  举报
编辑推荐:
· SQL Server 2025 AI相关能力初探
· Linux系列:如何用 C#调用 C方法造成内存泄露
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
阅读排行:
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南
· 开源Multi-agent AI智能体框架aevatar.ai,欢迎大家贡献代码
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· AI技术革命,工作效率10个最佳AI工具
历史上的今天:
2018-04-27 [Angular] Introduce to NGXS
2017-04-27 [Angular] Auxiliary named router outlets
2016-04-27 [Angular 2] Using Two Reducers Together
2016-04-27 [Angular 2] Passing Observables into Components with Async Pipe
2016-04-27 [Angular 2] Passing Template Input Values to Reducers
2016-04-27 [Angular 2] Dispatching Action with Payloads and type to Reducers
点击右上角即可分享
微信分享提示