array-unique-by.js 1.3 KB

12345678910111213141516171819202122232425262728293031323334353637
  1. 'use strict';
  2. var getBuiltIn = require('../internals/get-built-in');
  3. var uncurryThis = require('../internals/function-uncurry-this');
  4. var aCallable = require('../internals/a-callable');
  5. var isNullOrUndefined = require('../internals/is-null-or-undefined');
  6. var lengthOfArrayLike = require('../internals/length-of-array-like');
  7. var toObject = require('../internals/to-object');
  8. var arraySpeciesCreate = require('../internals/array-species-create');
  9. var Map = getBuiltIn('Map');
  10. var MapPrototype = Map.prototype;
  11. var mapForEach = uncurryThis(MapPrototype.forEach);
  12. var mapHas = uncurryThis(MapPrototype.has);
  13. var mapSet = uncurryThis(MapPrototype.set);
  14. var push = uncurryThis([].push);
  15. // `Array.prototype.uniqueBy` method
  16. // https://github.com/tc39/proposal-array-unique
  17. module.exports = function uniqueBy(resolver) {
  18. var that = toObject(this);
  19. var length = lengthOfArrayLike(that);
  20. var result = arraySpeciesCreate(that, 0);
  21. var map = new Map();
  22. var resolverFunction = !isNullOrUndefined(resolver) ? aCallable(resolver) : function (value) {
  23. return value;
  24. };
  25. var index, item, key;
  26. for (index = 0; index < length; index++) {
  27. item = that[index];
  28. key = resolverFunction(item);
  29. if (!mapHas(map, key)) mapSet(map, key, item);
  30. }
  31. mapForEach(map, function (value) {
  32. push(result, value);
  33. });
  34. return result;
  35. };