esnext.array.unique-by.js 1.2 KB

1234567891011121314151617181920212223242526272829303132333435363738
  1. 'use strict';
  2. var $ = require('../internals/export');
  3. var toLength = require('../internals/to-length');
  4. var toObject = require('../internals/to-object');
  5. var getBuiltIn = require('../internals/get-built-in');
  6. var arraySpeciesCreate = require('../internals/array-species-create');
  7. var addToUnscopables = require('../internals/add-to-unscopables');
  8. var push = [].push;
  9. // `Array.prototype.uniqueBy` method
  10. // https://github.com/tc39/proposal-array-unique
  11. $({ target: 'Array', proto: true }, {
  12. uniqueBy: function uniqueBy(resolver) {
  13. var that = toObject(this);
  14. var length = toLength(that.length);
  15. var result = arraySpeciesCreate(that, 0);
  16. var Map = getBuiltIn('Map');
  17. var map = new Map();
  18. var resolverFunction, index, item, key;
  19. if (typeof resolver == 'function') resolverFunction = resolver;
  20. else if (resolver == null) resolverFunction = function (value) {
  21. return value;
  22. };
  23. else throw new TypeError('Incorrect resolver!');
  24. for (index = 0; index < length; index++) {
  25. item = that[index];
  26. key = resolverFunction(item);
  27. if (!map.has(key)) map.set(key, item);
  28. }
  29. map.forEach(function (value) {
  30. push.call(result, value);
  31. });
  32. return result;
  33. }
  34. });
  35. addToUnscopables('uniqueBy');