功能工具

0.3.0 2021-11-29 10:54 UTC

This package is auto-updated.

Last update: 2024-09-29 05:50:04 UTC


README

功能工具

示例

所有

确定数组中所有元素是否满足谓词。

Futils\all(fn($x) => $x > 100)([101, 102, 103]) // => true

总是

创建一个总是返回给定值的函数。

Futils\always(true)() // => true

任何

确定数组中的任何元素是否满足谓词。

Futils\any(fn($x) => $x == 100)([1, 2, 100]) // => true

组合

函数组合(fn -> ... -> f2 -> f1)。

Futils\compose(fn($x) => $x + 1, fn($x) => $x * 100)(2) // => 201

包含

检查值是否包含在数组中。

Futils\contains(1337)([1, 1337, 2]) // => true

差集

计算数组的差集。

Futils\difference([1, 2, 3, 4])([1, 2]) // => [3, 4]

丢弃

从数组的前端丢弃前n个元素。

Futils\drop(2)([1, 2, 3, 4]) // => [3, 4]

过滤

使用回调函数过滤数组的元素。

Futils\filter(fn($x) => $x > 0)([-1, -2, 1, 2]) // => [1, 2]

查找

找到满足谓词的第一个数组元素。

Futils\find(fn($x) => $x > 10)([1, 2, 11]) // => 11

展开

展开嵌套数组。

Futils\flatten([1, [2, [3, [4]]]]) // => [1, 2, 3, 4]

检查数组中是否存在具有此键的元素。

Futils\has("test")(["test" => 1]) // => true

头部

获取数组的头部。

Futils\head([1, 2, 3]) // => 1

索引

获取数组中值的第一个索引。

Futils\indexOf("test")([1, "test", 3]) // => 1

连接

使用字符串连接数组元素。

Futils\join([1, 2, 3])("|") // => "1|2|3"

尾部

获取数组的最后一个元素。

Futils\last([1, 2, 3, 4]) // => 4

映射

将函数应用于数组的每个元素。

Futils\map(fn($x) => $x + 1)([1, 2, 3]) // => [2, 3, 4]

合并

合并两个数组。

Futils\merge([1, 2])([3, 4]) // => [1, 2, 3, 4]

部分

创建部分函数。

Futils\partial(fn($x, $y, $z) => $x + $y + $z)(1, 2)(3) // => 6

分区

等价于 [(filter f, arr), (reject f, arr)]

Futils\partition(fn($x) => $x > 0)([-1, -2, 1, 2]) // => [[1, 2], [-1, -2]]

管道

函数组合(f1 -> f2 -> ... -> fn)。

Futils\pipe(fn($x) => $x + 1, fn($x) => $x * 100)(1) // => 200

归约

使用回调函数将数组归约为一个单值。

Futils\reduce(fn($x, $y) => $x + $y)([1, 2, 3]) // => 6

拒绝

类似于过滤,但新数组由所有未通过函数的项组成。

Futils\reject(fn($x) => $x > 0)([-1, -2, 1, 2]) // => [-1, -2]

替换

将传递的数组中的元素替换到第一个数组中。

Futils\replace([1, 2, 3])([1 => 3, 2 => 2]) // => [1, 3, 2]

尾部

获取数组的尾部。

Futils\tail([1, 2, 3, 4, 5]) // => [2, 3, 4, 5]

从数组中获取前n个元素。

Futils\take(2)([1, 2, 3, 4]) // => [1, 2]

只有当谓词为真时才对参数应用函数,否则返回参数。

Futils\when(fn($x) => $x > 100)(fn($x) => $x + 5)(1000) // => 1005

压缩

将其两个参数压缩成一个数组数组的数组。

Futils\zip([1, 2, 3])([4, 5, 6]) // => [[1, 4], [2, 5], [3, 6]]

单子

IdentityMonad - 仅注释普通值和函数以满足单子定律。

(new Futils\IdentityMonad(100))
    ->bind(fn($x, $n) => $x * $n, 2)
    ->bind("strval")
    ->extract() // => "200"

MaybeMonad - 封装未定义值的类型。

(new Futils\MaybeMonad("test"))
    ->bind(fn() => null)
    ->bind(fn($x) => $x + 1)
    ->extract() // => null

ListMonad - 抽象化项目列表的概念。

(new Futils\ListMonad([1, new IdentityMonad(2), new MaybeMonad(3), new ListMonad([4])]))
    ->bind(fn($x) => $x + 100)
    ->extract() // => [101, 102, 103, [104]]