equalsIterable.js 1.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071
  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. } // We might be able to short circuit by using the size or length fields.
  19. var oneSize = maybeGetSize(one);
  20. var twoSize = maybeGetSize(two);
  21. if (oneSize != null && twoSize != null && oneSize !== twoSize) {
  22. return false;
  23. } // Otherwise use the iterators to check equality. Here we cannot use for-of
  24. // because we need to advance the iterators at the same time.
  25. var oneIterator = enumerate(one);
  26. var oneItem = oneIterator.next();
  27. var twoIterator = enumerate(two);
  28. var twoItem = twoIterator.next();
  29. var safeAreEqual = areEqual || referenceEquality;
  30. while (!(oneItem.done || twoItem.done)) {
  31. if (!safeAreEqual(oneItem.value, twoItem.value)) {
  32. return false;
  33. }
  34. oneItem = oneIterator.next();
  35. twoItem = twoIterator.next();
  36. }
  37. return oneItem.done === twoItem.done;
  38. }
  39. function maybeGetSize(o) {
  40. if (o == null) {
  41. return null;
  42. }
  43. if (typeof o.size === 'number') {
  44. return o.size;
  45. }
  46. if (typeof o.length === 'number') {
  47. return o.length;
  48. }
  49. return null;
  50. }
  51. function referenceEquality(one, two) {
  52. return one === two;
  53. }
  54. module.exports = equalsIterable;