intersect.js 780 B

1234567891011121314151617181920212223242526272829303132333435363738394041
  1. 'use strict';
  2. const internals = {};
  3. module.exports = function (array1, array2, options = {}) {
  4. if (!array1 ||
  5. !array2) {
  6. return (options.first ? null : []);
  7. }
  8. const common = [];
  9. const hash = (Array.isArray(array1) ? new Set(array1) : array1);
  10. const found = new Set();
  11. for (const value of array2) {
  12. if (internals.has(hash, value) &&
  13. !found.has(value)) {
  14. if (options.first) {
  15. return value;
  16. }
  17. common.push(value);
  18. found.add(value);
  19. }
  20. }
  21. return (options.first ? null : common);
  22. };
  23. internals.has = function (ref, key) {
  24. if (typeof ref.has === 'function') {
  25. return ref.has(key);
  26. }
  27. return ref[key] !== undefined;
  28. };