Skip to content

Commit a7275c1

Browse files
committed
Add uniq
1 parent 3a4a871 commit a7275c1

File tree

5 files changed

+57
-5
lines changed

5 files changed

+57
-5
lines changed

README.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -46,6 +46,7 @@ You can also check code coverage by running ```composer run test:coverage```.
4646
- some
4747
- first
4848
- last
49+
- uniq
4950
- Function composition
5051
- flow
5152
- compose

composer.json

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -43,6 +43,7 @@
4343
"src/reject.php",
4444
"src/reverse.php",
4545
"src/some.php",
46+
"src/uniq.php",
4647
"src/zip.php"
4748
]
4849
},

composer.lock

Lines changed: 5 additions & 5 deletions
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

src/uniq.php

Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,26 @@
1+
<?php
2+
3+
namespace fphp;
4+
5+
/**
6+
* Return an array without duplicates
7+
*
8+
* @param array $collection collection
9+
* @return array
10+
* @author Rémy Peru <peru.remy@gmail.com>
11+
*/
12+
function uniq(...$args) {
13+
$uniq = function (array $collection) {
14+
$uniqArray = [];
15+
16+
foreach($collection as $item) {
17+
if (!includes($item, $uniqArray)) {
18+
$uniqArray[] = $item;
19+
}
20+
}
21+
22+
return $uniqArray;
23+
};
24+
25+
return curryN($uniq, 1)(...$args);
26+
}

tests/uniq.php

Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,24 @@
1+
<?php
2+
3+
use function fphp\uniq;
4+
5+
describe('uniq', function () {
6+
it('should return input array without duplicates', function () {
7+
$res = uniq([1, 2, 3, 3 ,4 ,5 , 'orange', 'green', 'orange']);
8+
9+
expect($res)->toBe([1, 2, 3, 4 ,5 , 'orange', 'green']);
10+
});
11+
12+
it('should be curried', function () {
13+
$res = uniq();
14+
$res = $res([1, 2, 3, 3 ,4 ,5 , 'orange', 'green', 'orange']);
15+
16+
expect($res)->toBe([1, 2, 3, 4 ,5 , 'orange', 'green']);
17+
});
18+
19+
it('should work with non contiguous arrays', function () {
20+
$res = uniq([0 => 1, 4 => 2, 8 => 2]);
21+
22+
expect($res)->toBe([1, 2]);
23+
});
24+
});

0 commit comments

Comments
 (0)