countDistinct.js.flow 681 B

12345678910111213141516171819202122232425262728293031
  1. /**
  2. * Copyright (c) 2013-present, Facebook, Inc.
  3. *
  4. * This source code is licensed under the MIT license found in the
  5. * LICENSE file in the root directory of this source tree.
  6. *
  7. * @providesModule countDistinct
  8. * @flow
  9. */
  10. 'use strict';
  11. var Set = require('./Set');
  12. var emptyFunction = require('./emptyFunction');
  13. /**
  14. * Returns the count of distinct elements selected from an array.
  15. */
  16. function countDistinct<T1, T2>(iter: Iterable<T1>, selector: (item: T1) => T2): number {
  17. selector = selector || emptyFunction.thatReturnsArgument;
  18. var set = new Set();
  19. for (var val of iter) {
  20. set.add(selector(val));
  21. }
  22. return set.size;
  23. }
  24. module.exports = countDistinct;