equalsIterable.js 1.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364
  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. *
  8. */
  9. 'use strict';
  10. var enumerate = require('./enumerate');
  11. /**
  12. * Checks if two iterables are equal. A custom areEqual function may be provided
  13. * as an optional third argument.
  14. */
  15. function equalsIterable(one, two, areEqual) {
  16. if (one === two) {
  17. return true;
  18. }
  19. // We might be able to short circuit by using the size or length fields.
  20. var oneSize = maybeGetSize(one);
  21. var twoSize = maybeGetSize(two);
  22. if (oneSize != null && twoSize != null && oneSize !== twoSize) {
  23. return false;
  24. }
  25. // Otherwise use the iterators to check equality. Here we cannot use for-of
  26. // because we need to advance the iterators at the same time.
  27. var oneIterator = enumerate(one);
  28. var oneItem = oneIterator.next();
  29. var twoIterator = enumerate(two);
  30. var twoItem = twoIterator.next();
  31. var safeAreEqual = areEqual || referenceEquality;
  32. while (!(oneItem.done || twoItem.done)) {
  33. if (!safeAreEqual(oneItem.value, twoItem.value)) {
  34. return false;
  35. }
  36. oneItem = oneIterator.next();
  37. twoItem = twoIterator.next();
  38. }
  39. return oneItem.done === twoItem.done;
  40. }
  41. function maybeGetSize(o) {
  42. if (o == null) {
  43. return null;
  44. }
  45. if (typeof o.size === 'number') {
  46. return o.size;
  47. }
  48. if (typeof o.length === 'number') {
  49. return o.length;
  50. }
  51. return null;
  52. }
  53. function referenceEquality(one, two) {
  54. return one === two;
  55. }
  56. module.exports = equalsIterable;