array-unique-by.js 1.0 KB

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