From dcb13b9586a147f89bfd20159a140141473c8488 Mon Sep 17 00:00:00 2001 From: pencil-dog <60233442+pencil-dog@users.noreply.github.com> Date: Thu, 25 Mar 2021 11:36:08 +0100 Subject: [PATCH] [Dict] add unique_scalar() function to avoid performance penalty hit when using Dict\unique() on large scalar arrays (#168) Co-authored-by: yivi --- docs/component/dict.md | 1 + src/Psl/Dict/unique_scalar.php | 38 ++++++++++++++++++++++++ src/Psl/Internal/Loader.php | 1 + tests/Psl/Dict/UniqueScalarTest.php | 46 +++++++++++++++++++++++++++++ 4 files changed, 86 insertions(+) create mode 100644 src/Psl/Dict/unique_scalar.php create mode 100644 tests/Psl/Dict/UniqueScalarTest.php diff --git a/docs/component/dict.md b/docs/component/dict.md index de92a8b..9d785ac 100644 --- a/docs/component/dict.md +++ b/docs/component/dict.md @@ -49,5 +49,6 @@ - [take_while](./../../src/Psl/Dict/take_while.php#L26) - [unique](./../../src/Psl/Dict/unique.php#L17) - [unique_by](./../../src/Psl/Dict/unique_by.php#L23) +- [unique_scalar](./../../src/Psl/Dict/unique_scalar.php#L21) diff --git a/src/Psl/Dict/unique_scalar.php b/src/Psl/Dict/unique_scalar.php new file mode 100644 index 0000000..12d286e --- /dev/null +++ b/src/Psl/Dict/unique_scalar.php @@ -0,0 +1,38 @@ + $iterable + * + * @return array + */ +function unique_scalar(iterable $iterable): array +{ + if (is_array($iterable)) { + return array_unique($iterable); + } + + return unique_by( + $iterable, + /** + * @param scalar $v + * + * @return scalar + * + * @pure + */ + static fn($v) => $v + ); +} diff --git a/src/Psl/Internal/Loader.php b/src/Psl/Internal/Loader.php index f1ac854..4195898 100644 --- a/src/Psl/Internal/Loader.php +++ b/src/Psl/Internal/Loader.php @@ -136,6 +136,7 @@ final class Loader 'Psl\Dict\take_while', 'Psl\Dict\unique', 'Psl\Dict\unique_by', + 'Psl\Dict\unique_scalar', 'Psl\Dict\diff', 'Psl\Dict\diff_by_key', 'Psl\Dict\intersect', diff --git a/tests/Psl/Dict/UniqueScalarTest.php b/tests/Psl/Dict/UniqueScalarTest.php new file mode 100644 index 0000000..d019619 --- /dev/null +++ b/tests/Psl/Dict/UniqueScalarTest.php @@ -0,0 +1,46 @@ +