Skip to content

Commit

Permalink
Implement uniqBy in terms of filter
Browse files Browse the repository at this point in the history
  • Loading branch information
wojpawlik committed Aug 18, 2018
1 parent d91e8e7 commit 00ea0c4
Show file tree
Hide file tree
Showing 3 changed files with 20 additions and 13 deletions.
7 changes: 7 additions & 0 deletions source/uniq.js
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,13 @@ import uniqBy from './uniqBy';
* Returns a new list containing only one copy of each element in the original
* list. [`R.equals`](#equals) is used to determine equality.
*
* Dispatches to the `filter` method of the argument, if present.
*
* Performs the transformation lazily and returns a non-iterator iterable
* if a non-array iterable is given in list position.
*
* Acts as a transducer if a transformer is given in list position.
*
* @func
* @memberOf R
* @since v0.1.0
Expand Down
22 changes: 9 additions & 13 deletions source/uniqBy.js
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import _Set from './internal/_Set';
import _curry2 from './internal/_curry2';
import filter from './filter';


/**
Expand All @@ -8,6 +9,13 @@ import _curry2 from './internal/_curry2';
* each list element. Prefers the first item if the supplied function produces
* the same value on two items. [`R.equals`](#equals) is used for comparison.
*
* Dispatches to the `filter` method of the second argument, if present.
*
* Performs the transformation lazily and returns a non-iterator iterable
* if a non-array iterable is given in list position.
*
* Acts as a transducer if a transformer is given in list position.
*
* @func
* @memberOf R
* @since v0.16.0
Expand All @@ -22,18 +30,6 @@ import _curry2 from './internal/_curry2';
*/
var uniqBy = _curry2(function uniqBy(fn, list) {
var set = new _Set();
var result = [];
var idx = 0;
var appliedItem, item;

while (idx < list.length) {
item = list[idx];
appliedItem = fn(item);
if (set.add(appliedItem)) {
result.push(item);
}
idx += 1;
}
return result;
return filter(item => set.add(fn(item)), list);
});
export default uniqBy;
4 changes: 4 additions & 0 deletions test/uniqBy.js
Original file line number Diff line number Diff line change
Expand Up @@ -28,4 +28,8 @@ describe('uniqBy', function() {
eq(R.uniqBy(R.identity, [new Just([1, 2, 3]), new Just([1, 2, 3])]).length, 1);
});

it('can act as a transducer', function() {
eq(R.into([], R.uniqBy(Math.abs), [-2, -1, 0, 1, 2]), [-2, -1, 0]);
});

});

0 comments on commit 00ea0c4

Please sign in to comment.