Skip to content

Commit

Permalink
feat(uniq): initial commit of function
Browse files Browse the repository at this point in the history
  • Loading branch information
jackw committed Jul 4, 2020
1 parent c9ff78c commit 6de7e31
Show file tree
Hide file tree
Showing 2 changed files with 65 additions and 0 deletions.
37 changes: 37 additions & 0 deletions src/_uniq.scss
Original file line number Diff line number Diff line change
@@ -0,0 +1,37 @@
@import 'reduce';

///
/// Returns a new list containing only one copy of each element in the original
/// list. [`equals`](#equals) is used to determine equality.
///
/// @group list
/// @param {Array} list The array to consider.
/// @return {Array} The list of unique items.
/// @example
///
/// uniq([1, 1, 2, 1]); //=> [1, 2]
/// uniq([1, '1']); //=> [1, '1']
/// uniq([[42], [42]]); //=> [[42]]
///

@function uniq($list...) {
$result: ();

@if type-of($list) == arglist and length(nth($list, 1)) == 0 {
@return $result;
}

$_list: if(
type-of($list) == arglist and length($list) == 1,
reduce(append, (), nth($list, 1)),
$list
);
@each $item in $_list {
// should probably test with `get-function` for functions.
@if not index($result, $item) {
$result: append($result, $item);
}
}

@return $result;
}
28 changes: 28 additions & 0 deletions test/_uniq.spec.scss
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
@import 'true';
@import '../src/uniq';
@import '../src/add';
@import '../src/identity';

@include describe('uniq [function]') {
@include it(
'returns a set from any array (i.e. purges duplicate elements)'
) {
$list: [1, 2, 3, 1, 2, 3, 1, 2, 3];
@include assert-equal(uniq($list), (1 2 3));
}

@include it('keeps elements from the left') {
@include assert-equal(uniq([1, 2, 3, 4, 1]), (1 2 3 4));
}

@include it('returns an empty array for an empty array') {
@include assert-equal(uniq([]), ());
}

@include it('uses reference equality for functions') {
@include assert-equal(
length(uniq([add, identity, add, identity, add, identity])),
2
);
}
}

0 comments on commit 6de7e31

Please sign in to comment.