array-unique-by.js 1.2 KB

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