collections.js 34.2 KB
Newer Older
1
// Copyright 2012 the V8 project authors. All rights reserved.
2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
//     * Redistributions of source code must retain the above copyright
//       notice, this list of conditions and the following disclaimer.
//     * Redistributions in binary form must reproduce the above
//       copyright notice, this list of conditions and the following
//       disclaimer in the documentation and/or other materials provided
//       with the distribution.
//     * Neither the name of Google Inc. nor the names of its
//       contributors may be used to endorse or promote products derived
//       from this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

28
// Flags: --expose-gc --allow-natives-syntax
29 30


31 32 33 34 35 36 37
function assertSize(expected, collection) {
  if (collection instanceof Map || collection instanceof Set) {
    assertEquals(expected, collection.size);
  }
}


38
// Test valid getter and setter calls on Sets and WeakSets
39 40 41 42 43 44
function TestValidSetCalls(m) {
  assertDoesNotThrow(function () { m.add(new Object) });
  assertDoesNotThrow(function () { m.has(new Object) });
  assertDoesNotThrow(function () { m.delete(new Object) });
}
TestValidSetCalls(new Set);
45
TestValidSetCalls(new WeakSet);
46 47 48 49 50 51 52 53


// Test valid getter and setter calls on Maps and WeakMaps
function TestValidMapCalls(m) {
  assertDoesNotThrow(function () { m.get(new Object) });
  assertDoesNotThrow(function () { m.set(new Object) });
  assertDoesNotThrow(function () { m.has(new Object) });
  assertDoesNotThrow(function () { m.delete(new Object) });
54 55 56 57 58 59 60 61 62 63 64 65 66 67 68
  assertDoesNotThrow(function () { m.get(undefined) });
  assertDoesNotThrow(function () { m.get(null) });
  assertDoesNotThrow(function () { m.get(0) });
  assertDoesNotThrow(function () { m.get('a-key') });
  assertDoesNotThrow(function () { m.get(Symbol()) });
  assertDoesNotThrow(function () { m.has(undefined) });
  assertDoesNotThrow(function () { m.has(null) });
  assertDoesNotThrow(function () { m.has(0) });
  assertDoesNotThrow(function () { m.has('a-key') });
  assertDoesNotThrow(function () { m.has(Symbol()) });
  assertDoesNotThrow(function () { m.delete(undefined) });
  assertDoesNotThrow(function () { m.delete(null) });
  assertDoesNotThrow(function () { m.delete(0) });
  assertDoesNotThrow(function () { m.delete('a-key') });
  assertDoesNotThrow(function () { m.delete(Symbol()) });
69 70 71 72 73 74 75 76
}
TestValidMapCalls(new Map);
TestValidMapCalls(new WeakMap);


// Test invalid getter and setter calls for WeakMap only
function TestInvalidCalls(m) {
  assertThrows(function () { m.set(undefined, 0) }, TypeError);
77
  assertThrows(function () { m.set(null, 0) }, TypeError);
78 79
  assertThrows(function () { m.set(0, 0) }, TypeError);
  assertThrows(function () { m.set('a-key', 0) }, TypeError);
80
  assertThrows(function () { m.set(Symbol(), 0) }, TypeError);
81 82 83 84
}
TestInvalidCalls(new WeakMap);


85
// Test expected behavior for Sets and WeakSets
86 87
function TestSet(set, key) {
  assertFalse(set.has(key));
88 89 90 91 92 93
  assertFalse(set.delete(key));
  if (typeof key === 'object' && !(set instanceof WeakSet)) {
    assertSame(set, set.add(key));
    assertTrue(set.has(key));
    assertTrue(set.delete(key));
  }
94 95
  assertFalse(set.has(key));
  assertFalse(set.delete(key));
96 97 98
  assertFalse(set.has(key));
}
function TestSetBehavior(set) {
99
  // Fill
100
  for (var i = 0; i < 20; i++) {
101
    TestSet(set, new Object);
102 103 104
    TestSet(set, i);
    TestSet(set, i / 100);
    TestSet(set, 'key-' + i);
105
    TestSet(set, Symbol(i));
106
  }
107 108 109 110 111

  var keys = [
    -0, +0, 1, 1/3, 10, +Infinity, -Infinity, NaN, true, false, null, undefined,
    'x', Symbol(), {}, function(){}
  ];
112 113
  for (var i = 0; i < keys.length; i++) {
    TestSet(set, keys[i]);
114 115 116
  }
}
TestSetBehavior(new Set);
117
TestSetBehavior(new WeakSet);
118 119 120 121


// Test expected mapping behavior for Maps and WeakMaps
function TestMapping(map, key, value) {
122 123 124 125 126 127 128 129 130 131 132 133 134 135
  assertFalse(map.has(key));
  assertSame(undefined, map.get(key));
  assertFalse(map.delete(key));
  if (typeof key === 'object' && !(map instanceof WeakMap)) {
    assertSame(map, map.set(key, value));
    assertSame(value, map.get(key));
    assertTrue(map.has(key));
    assertTrue(map.delete(key));
  }
  assertFalse(map.has(key));
  assertSame(undefined, map.get(key));
  assertFalse(map.delete(key));
  assertFalse(map.has(key));
  assertSame(undefined, map.get(key));
136
}
137 138
function TestMapBehavior(m) {
  // Fill
139 140 141 142 143 144 145
  TestMapping(m, new Object, 23);
  TestMapping(m, new Object, 'the-value');
  TestMapping(m, new Object, new Object);
  for (var i = 0; i < 20; i++) {
    TestMapping(m, i, new Object);
    TestMapping(m, i / 10, new Object);
    TestMapping(m, 'key-' + i, new Object);
146
    TestMapping(m, Symbol(i), new Object);
147
  }
148 149 150 151 152

  var keys = [
    -0, +0, 1, 1/3, 10, +Infinity, -Infinity, NaN, true, false, null, undefined,
    'x', Symbol(), {}, function(){}
  ];
153
  for (var i = 0; i < keys.length; i++) {
154 155
    TestMapping(m, keys[i], 23);
    TestMapping(m, keys[i], 'the-value');
156 157 158
    TestMapping(m, keys[i], new Object);
  }
}
159 160
TestMapBehavior(new Map);
TestMapBehavior(new WeakMap);
161 162 163 164 165


// Test expected querying behavior of Maps and WeakMaps
function TestQuery(m) {
  var key = new Object;
166 167 168 169
  var values = [ 'x', 0, +Infinity, -Infinity, true, false, null, undefined ];
  for (var i = 0; i < values.length; i++) {
    TestMapping(m, key, values[i]);
  }
170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228
}
TestQuery(new Map);
TestQuery(new WeakMap);


// Test expected deletion behavior of Maps and WeakMaps
function TestDelete(m) {
  var key = new Object;
  TestMapping(m, key, 'to-be-deleted');
  assertFalse(m.delete(key));
  assertFalse(m.delete(new Object));
  assertSame(m.get(key), undefined);
}
TestDelete(new Map);
TestDelete(new WeakMap);


// Test GC of Maps and WeakMaps with entry
function TestGC1(m) {
  var key = new Object;
  m.set(key, 'not-collected');
  gc();
  assertSame('not-collected', m.get(key));
}
TestGC1(new Map);
TestGC1(new WeakMap);


// Test GC of Maps and WeakMaps with chained entries
function TestGC2(m) {
  var head = new Object;
  for (key = head, i = 0; i < 10; i++, key = m.get(key)) {
    m.set(key, new Object);
  }
  gc();
  var count = 0;
  for (key = head; key != undefined; key = m.get(key)) {
    count++;
  }
  assertEquals(11, count);
}
TestGC2(new Map);
TestGC2(new WeakMap);


// Test property attribute [[Enumerable]]
function TestEnumerable(func) {
  function props(x) {
    var array = [];
    for (var p in x) array.push(p);
    return array.sort();
  }
  assertArrayEquals([], props(func));
  assertArrayEquals([], props(func.prototype));
  assertArrayEquals([], props(new func()));
}
TestEnumerable(Set);
TestEnumerable(Map);
TestEnumerable(WeakMap);
229
TestEnumerable(WeakSet);
230 231 232 233 234 235 236 237


// Test arbitrary properties on Maps and WeakMaps
function TestArbitrary(m) {
  function TestProperty(map, property, value) {
    map[property] = value;
    assertEquals(value, map[property]);
  }
238
  for (var i = 0; i < 20; i++) {
239 240 241 242 243 244 245 246 247 248
    TestProperty(m, i, 'val' + i);
    TestProperty(m, 'foo' + i, 'bar' + i);
  }
  TestMapping(m, new Object, 'foobar');
}
TestArbitrary(new Map);
TestArbitrary(new WeakMap);


// Test direct constructor call
249 250 251 252
assertThrows(function() { Set(); }, TypeError);
assertThrows(function() { Map(); }, TypeError);
assertThrows(function() { WeakMap(); }, TypeError);
assertThrows(function() { WeakSet(); }, TypeError);
253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279


// Test whether NaN values as keys are treated correctly.
var s = new Set;
assertFalse(s.has(NaN));
assertFalse(s.has(NaN + 1));
assertFalse(s.has(23));
s.add(NaN);
assertTrue(s.has(NaN));
assertTrue(s.has(NaN + 1));
assertFalse(s.has(23));
var m = new Map;
assertFalse(m.has(NaN));
assertFalse(m.has(NaN + 1));
assertFalse(m.has(23));
m.set(NaN, 'a-value');
assertTrue(m.has(NaN));
assertTrue(m.has(NaN + 1));
assertFalse(m.has(23));


// Test some common JavaScript idioms for Sets
var s = new Set;
assertTrue(s instanceof Set);
assertTrue(Set.prototype.add instanceof Function)
assertTrue(Set.prototype.has instanceof Function)
assertTrue(Set.prototype.delete instanceof Function)
280
assertTrue(Set.prototype.clear instanceof Function)
281 282 283 284 285 286 287 288 289


// Test some common JavaScript idioms for Maps
var m = new Map;
assertTrue(m instanceof Map);
assertTrue(Map.prototype.set instanceof Function)
assertTrue(Map.prototype.get instanceof Function)
assertTrue(Map.prototype.has instanceof Function)
assertTrue(Map.prototype.delete instanceof Function)
290
assertTrue(Map.prototype.clear instanceof Function)
291 292 293 294 295 296 297 298 299 300 301


// Test some common JavaScript idioms for WeakMaps
var m = new WeakMap;
assertTrue(m instanceof WeakMap);
assertTrue(WeakMap.prototype.set instanceof Function)
assertTrue(WeakMap.prototype.get instanceof Function)
assertTrue(WeakMap.prototype.has instanceof Function)
assertTrue(WeakMap.prototype.delete instanceof Function)


302 303 304 305 306 307 308 309 310 311 312 313 314
// Test some common JavaScript idioms for WeakSets
var s = new WeakSet;
assertTrue(s instanceof WeakSet);
assertTrue(WeakSet.prototype.add instanceof Function)
assertTrue(WeakSet.prototype.has instanceof Function)
assertTrue(WeakSet.prototype.delete instanceof Function)


// Test name of constructor.
assertEquals("Set", Set.name);
assertEquals("Map", Map.name);
assertEquals("WeakMap", WeakMap.name);
assertEquals("WeakSet", WeakSet.name);
315 316


317
// Test prototype property of Set, Map, WeakMap and WeakSet.
318
function TestPrototype(C) {
319 320
  assertTrue(C.prototype instanceof Object);
  assertEquals({
321
    value: C.prototype,
322
    writable: false,
323 324 325 326
    enumerable: false,
    configurable: false
  }, Object.getOwnPropertyDescriptor(C, "prototype"));
}
327 328 329 330
TestPrototype(Set);
TestPrototype(Map);
TestPrototype(WeakMap);
TestPrototype(WeakSet);
331 332


333
// Test constructor property of the Set, Map, WeakMap and WeakSet prototype.
334 335 336 337
function TestConstructor(C) {
  assertFalse(C === Object.prototype.constructor);
  assertSame(C, C.prototype.constructor);
  assertSame(C, (new C).__proto__.constructor);
338
  assertEquals(0, C.length);
339 340 341 342
}
TestConstructor(Set);
TestConstructor(Map);
TestConstructor(WeakMap);
343 344 345
TestConstructor(WeakSet);


346
// Test the Set, Map, WeakMap and WeakSet global properties themselves.
347 348 349 350 351 352 353 354 355 356 357 358
function TestDescriptor(global, C) {
  assertEquals({
    value: C,
    writable: true,
    enumerable: false,
    configurable: true
  }, Object.getOwnPropertyDescriptor(global, C.name));
}
TestDescriptor(this, Set);
TestDescriptor(this, Map);
TestDescriptor(this, WeakMap);
TestDescriptor(this, WeakSet);
359 360


361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382
// Regression test for WeakMap prototype.
assertTrue(WeakMap.prototype.constructor === WeakMap)
assertTrue(Object.getPrototypeOf(WeakMap.prototype) === Object.prototype)


// Regression test for issue 1617: The prototype of the WeakMap constructor
// needs to be unique (i.e. different from the one of the Object constructor).
assertFalse(WeakMap.prototype === Object.prototype);
var o = Object.create({});
assertFalse("get" in o);
assertFalse("set" in o);
assertEquals(undefined, o.get);
assertEquals(undefined, o.set);
var o = Object.create({}, { myValue: {
  value: 10,
  enumerable: false,
  configurable: true,
  writable: true
}});
assertEquals(10, o.myValue);


383 384 385 386 387 388 389
// Regression test for issue 1884: Invoking any of the methods for Harmony
// maps, sets, or weak maps, with a wrong type of receiver should be throwing
// a proper TypeError.
var alwaysBogus = [ undefined, null, true, "x", 23, {} ];
var bogusReceiversTestSet = [
  { proto: Set.prototype,
    funcs: [ 'add', 'has', 'delete' ],
390
    receivers: alwaysBogus.concat([ new Map, new WeakMap, new WeakSet ]),
391 392 393
  },
  { proto: Map.prototype,
    funcs: [ 'get', 'set', 'has', 'delete' ],
394
    receivers: alwaysBogus.concat([ new Set, new WeakMap, new WeakSet ]),
395 396 397
  },
  { proto: WeakMap.prototype,
    funcs: [ 'get', 'set', 'has', 'delete' ],
398 399 400 401 402
    receivers: alwaysBogus.concat([ new Set, new Map, new WeakSet ]),
  },
  { proto: WeakSet.prototype,
    funcs: [ 'add', 'has', 'delete' ],
    receivers: alwaysBogus.concat([ new Set, new Map, new WeakMap ]),
403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420
  },
];
function TestBogusReceivers(testSet) {
  for (var i = 0; i < testSet.length; i++) {
    var proto = testSet[i].proto;
    var funcs = testSet[i].funcs;
    var receivers = testSet[i].receivers;
    for (var j = 0; j < funcs.length; j++) {
      var func = proto[funcs[j]];
      for (var k = 0; k < receivers.length; k++) {
        assertThrows(function () { func.call(receivers[k], {}) }, TypeError);
      }
    }
  }
}
TestBogusReceivers(bogusReceiversTestSet);


421 422 423
// Stress Test
// There is a proposed stress-test available at the es-discuss mailing list
// which cannot be reasonably automated.  Check it out by hand if you like:
424 425 426 427 428 429 430 431 432 433 434
// https://mail.mozilla.org/pipermail/es-discuss/2011-May/014096.html


// Set and Map size getters
var setSizeDescriptor = Object.getOwnPropertyDescriptor(Set.prototype, 'size');
assertEquals(undefined, setSizeDescriptor.value);
assertEquals(undefined, setSizeDescriptor.set);
assertTrue(setSizeDescriptor.get instanceof Function);
assertEquals(undefined, setSizeDescriptor.get.prototype);
assertFalse(setSizeDescriptor.enumerable);
assertTrue(setSizeDescriptor.configurable);
435
assertEquals('get size', setSizeDescriptor.get.name);
436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455

var s = new Set();
assertFalse(s.hasOwnProperty('size'));
for (var i = 0; i < 10; i++) {
  assertEquals(i, s.size);
  s.add(i);
}
for (var i = 9; i >= 0; i--) {
  s.delete(i);
  assertEquals(i, s.size);
}


var mapSizeDescriptor = Object.getOwnPropertyDescriptor(Map.prototype, 'size');
assertEquals(undefined, mapSizeDescriptor.value);
assertEquals(undefined, mapSizeDescriptor.set);
assertTrue(mapSizeDescriptor.get instanceof Function);
assertEquals(undefined, mapSizeDescriptor.get.prototype);
assertFalse(mapSizeDescriptor.enumerable);
assertTrue(mapSizeDescriptor.configurable);
456
assertEquals('get size', mapSizeDescriptor.get.name);
457 458 459 460 461 462 463 464 465 466 467

var m = new Map();
assertFalse(m.hasOwnProperty('size'));
for (var i = 0; i < 10; i++) {
  assertEquals(i, m.size);
  m.set(i, i);
}
for (var i = 9; i >= 0; i--) {
  m.delete(i);
  assertEquals(i, m.size);
}
468 469


470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493
// Test Set clear
(function() {
  var s = new Set();
  s.add(42);
  assertTrue(s.has(42));
  assertEquals(1, s.size);
  s.clear();
  assertFalse(s.has(42));
  assertEquals(0, s.size);
})();


// Test Map clear
(function() {
  var m = new Map();
  m.set(42, true);
  assertTrue(m.has(42));
  assertEquals(1, m.size);
  m.clear();
  assertFalse(m.has(42));
  assertEquals(0, m.size);
})();


494
(function TestMinusZeroSet() {
495 496 497 498 499 500 501
  var s = new Set();
  s.add(-0);
  assertSame(0, s.values().next().value);
  s.add(0);
  assertEquals(1, s.size);
  assertTrue(s.has(0));
  assertTrue(s.has(-0));
502 503 504 505 506 507
})();


(function TestMinusZeroMap() {
  var m = new Map();
  m.set(-0, 'minus');
508 509
  assertSame(0, m.keys().next().value);
  m.set(0, 'plus');
510 511 512
  assertEquals(1, m.size);
  assertTrue(m.has(0));
  assertTrue(m.has(-0));
513 514
  assertEquals('plus', m.get(0));
  assertEquals('plus', m.get(-0));
515
})();
516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689


(function TestSetForEachInvalidTypes() {
  assertThrows(function() {
    Set.prototype.set.forEach.call({});
  }, TypeError);

  var set = new Set();
  assertThrows(function() {
    set.forEach({});
  }, TypeError);
})();


(function TestSetForEach() {
  var set = new Set();
  set.add('a');
  set.add('b');
  set.add('c');

  var buffer = '';
  var receiver = {};
  set.forEach(function(v, k, s) {
    assertSame(v, k);
    assertSame(set, s);
    assertSame(this, receiver);
    buffer += v;
    if (v === 'a') {
      set.delete('b');
      set.add('d');
      set.add('e');
      set.add('f');
    } else if (v === 'c') {
      set.add('b');
      set.delete('e');
    }
  }, receiver);

  assertEquals('acdfb', buffer);
})();


(function TestSetForEachAddAtEnd() {
  var set = new Set();
  set.add('a');
  set.add('b');

  var buffer = '';
  set.forEach(function(v) {
    buffer += v;
    if (v === 'b') {
      set.add('c');
    }
  });

  assertEquals('abc', buffer);
})();


(function TestSetForEachDeleteNext() {
  var set = new Set();
  set.add('a');
  set.add('b');
  set.add('c');

  var buffer = '';
  set.forEach(function(v) {
    buffer += v;
    if (v === 'b') {
      set.delete('c');
    }
  });

  assertEquals('ab', buffer);
})();


(function TestSetForEachDeleteVisitedAndAddAgain() {
  var set = new Set();
  set.add('a');
  set.add('b');
  set.add('c');

  var buffer = '';
  set.forEach(function(v) {
    buffer += v;
    if (v === 'b') {
      set.delete('a');
    } else if (v === 'c') {
      set.add('a');
    }
  });

  assertEquals('abca', buffer);
})();


(function TestSetForEachClear() {
  var set = new Set();
  set.add('a');
  set.add('b');
  set.add('c');

  var buffer = '';
  set.forEach(function(v) {
    buffer += v;
    if (v === 'a') {
      set.clear();
      set.add('d');
      set.add('e');
    }
  });

  assertEquals('ade', buffer);
})();


(function TestSetForEachNested() {
  var set = new Set();
  set.add('a');
  set.add('b');
  set.add('c');

  var buffer = '';
  set.forEach(function(v) {
    buffer += v;
    set.forEach(function(v) {
      buffer += v;
      if (v === 'a') {
        set.delete('b');
      }
    });
  });

  assertEquals('aaccac', buffer);
})();


(function TestSetForEachEarlyExit() {
  var set = new Set();
  set.add('a');
  set.add('b');
  set.add('c');

  var buffer = '';
  var ex = {};
  try {
    set.forEach(function(v) {
      buffer += v;
      throw ex;
    });
  } catch (e) {
    assertEquals(ex, e);
  }
  assertEquals('a', buffer);
})();


(function TestSetForEachGC() {
  var set = new Set();
  for (var i = 0; i < 100; i++) {
    set.add(i);
  }

  var accumulated = 0;
  set.forEach(function(v) {
    accumulated += v;
    if (v % 10 === 0) {
      gc();
    }
  });
  assertEquals(4950, accumulated);
})();

690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716

(function TestSetForEachReceiverAsObject() {
  var set = new Set(["1", "2"]);

  // Create a new object in each function call when receiver is a
  // primitive value. See ECMA-262, Annex C.
  var a = [];
  set.forEach(function() { a.push(this) }, "");
  assertTrue(a[0] !== a[1]);

  // Do not create a new object otherwise.
  a = [];
  set.forEach(function() { a.push(this); }, {});
  assertEquals(a[0], a[1]);
})();


(function TestSetForEachReceiverAsObjectInStrictMode() {
  var set = new Set(["1", "2"]);

  // In strict mode primitive values should not be coerced to an object.
  var a = [];
  set.forEach(function() { 'use strict'; a.push(this); }, "");
  assertTrue(a[0] === "" && a[0] === a[1]);
})();


717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886
(function TestMapForEachInvalidTypes() {
  assertThrows(function() {
    Map.prototype.map.forEach.call({});
  }, TypeError);

  var map = new Map();
  assertThrows(function() {
    map.forEach({});
  }, TypeError);
})();


(function TestMapForEach() {
  var map = new Map();
  map.set(0, 'a');
  map.set(1, 'b');
  map.set(2, 'c');

  var buffer = [];
  var receiver = {};
  map.forEach(function(v, k, m) {
    assertEquals(map, m);
    assertEquals(this, receiver);
    buffer.push(k, v);
    if (k === 0) {
      map.delete(1);
      map.set(3, 'd');
      map.set(4, 'e');
      map.set(5, 'f');
    } else if (k === 2) {
      map.set(1, 'B');
      map.delete(4);
    }
  }, receiver);

  assertArrayEquals([0, 'a', 2, 'c', 3, 'd', 5, 'f', 1, 'B'], buffer);
})();


(function TestMapForEachAddAtEnd() {
  var map = new Map();
  map.set(0, 'a');
  map.set(1, 'b');

  var buffer = [];
  map.forEach(function(v, k) {
    buffer.push(k, v);
    if (k === 1) {
      map.set(2, 'c');
    }
  });

  assertArrayEquals([0, 'a', 1, 'b', 2, 'c'], buffer);
})();


(function TestMapForEachDeleteNext() {
  var map = new Map();
  map.set(0, 'a');
  map.set(1, 'b');
  map.set(2, 'c');

  var buffer = [];
  map.forEach(function(v, k) {
    buffer.push(k, v);
    if (k === 1) {
      map.delete(2);
    }
  });

  assertArrayEquals([0, 'a', 1, 'b'], buffer);
})();


(function TestSetForEachDeleteVisitedAndAddAgain() {
  var map = new Map();
  map.set(0, 'a');
  map.set(1, 'b');
  map.set(2, 'c');

  var buffer = [];
  map.forEach(function(v, k) {
    buffer.push(k, v);
    if (k === 1) {
      map.delete(0);
    } else if (k === 2) {
      map.set(0, 'a');
    }
  });

  assertArrayEquals([0, 'a', 1, 'b', 2, 'c', 0, 'a'], buffer);
})();


(function TestMapForEachClear() {
  var map = new Map();
  map.set(0, 'a');
  map.set(1, 'b');
  map.set(2, 'c');

  var buffer = [];
  map.forEach(function(v, k) {
    buffer.push(k, v);
    if (k === 0) {
      map.clear();
      map.set(3, 'd');
      map.set(4, 'e');
    }
  });

  assertArrayEquals([0, 'a', 3, 'd', 4, 'e'], buffer);
})();


(function TestMapForEachNested() {
  var map = new Map();
  map.set(0, 'a');
  map.set(1, 'b');
  map.set(2, 'c');

  var buffer = [];
  map.forEach(function(v, k) {
    buffer.push(k, v);
    map.forEach(function(v, k) {
      buffer.push(k, v);
      if (k === 0) {
        map.delete(1);
      }
    });
  });

  assertArrayEquals([0, 'a', 0, 'a', 2, 'c', 2, 'c', 0, 'a', 2, 'c'], buffer);
})();


(function TestMapForEachEarlyExit() {
  var map = new Map();
  map.set(0, 'a');
  map.set(1, 'b');
  map.set(2, 'c');

  var buffer = [];
  var ex = {};
  try {
    map.forEach(function(v, k) {
      buffer.push(k, v);
      throw ex;
    });
  } catch (e) {
    assertEquals(ex, e);
  }
  assertArrayEquals([0, 'a'], buffer);
})();


(function TestMapForEachGC() {
  var map = new Map();
  for (var i = 0; i < 100; i++) {
    map.set(i, i);
  }

  var accumulated = 0;
  map.forEach(function(v) {
    accumulated += v;
    if (v % 10 === 0) {
      gc();
    }
  });
  assertEquals(4950, accumulated);
})();
887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021


(function TestMapForEachAllRemovedTransition() {
  var map = new Map;
  map.set(0, 0);

  var buffer = [];
  map.forEach(function(v) {
    buffer.push(v);
    if (v === 0) {
      for (var i = 1; i < 4; i++) {
        map.set(i, i);
      }
    }

    if (v === 3) {
      for (var i = 0; i < 4; i++) {
        map.delete(i);
      }
      for (var i = 4; i < 8; i++) {
        map.set(i, i);
      }
    }
  });

  assertArrayEquals([0, 1, 2, 3, 4, 5, 6, 7], buffer);
})();


(function TestMapForEachClearTransition() {
  var map = new Map;
  map.set(0, 0);

  var i = 0;
  var buffer = [];
  map.forEach(function(v) {
    buffer.push(v);
    if (++i < 5) {
      for (var j = 0; j < 5; j++) {
        map.clear();
        map.set(i, i);
      }
    }
  });

  assertArrayEquals([0, 1, 2, 3, 4], buffer);
})();


(function TestMapForEachNestedNonTrivialTransition() {
  var map = new Map;
  map.set(0, 0);
  map.set(1, 1);
  map.set(2, 2);
  map.set(3, 3);
  map.delete(0);

  var i = 0;
  var buffer = [];
  map.forEach(function(v) {
    if (++i > 10) return;

    buffer.push(v);

    if (v == 3) {
      map.delete(1);
      for (var j = 4; j < 10; j++) {
        map.set(j, j);
      }
      for (var j = 4; j < 10; j += 2) {
        map.delete(j);
      }
      map.delete(2);

      for (var j = 10; j < 20; j++) {
        map.set(j, j);
      }
      for (var j = 10; j < 20; j += 2) {
        map.delete(j);
      }

      map.delete(3);
    }
  });

  assertArrayEquals([1, 2, 3, 5, 7, 9, 11, 13, 15, 17], buffer);
})();


(function TestMapForEachAllRemovedTransitionNoClear() {
  var map = new Map;
  map.set(0, 0);

  var buffer = [];
  map.forEach(function(v) {
    buffer.push(v);
    if (v === 0) {
      for (var i = 1; i < 8; i++) {
        map.set(i, i);
      }
    }

    if (v === 4) {
      for (var i = 0; i < 8; i++) {
        map.delete(i);
      }
    }
  });

  assertArrayEquals([0, 1, 2, 3, 4], buffer);
})();


(function TestMapForEachNoMoreElementsAfterTransition() {
  var map = new Map;
  map.set(0, 0);

  var buffer = [];
  map.forEach(function(v) {
    buffer.push(v);
    if (v === 0) {
      for (var i = 1; i < 16; i++) {
        map.set(i, i);
      }
    }

    if (v === 4) {
      for (var i = 5; i < 16; i++) {
        map.delete(i);
      }
    }
  });

  assertArrayEquals([0, 1, 2, 3, 4], buffer);
})();
1022 1023


1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053
(function TestMapForEachReceiverAsObject() {
  var map = new Map();
  map.set("key1", "value1");
  map.set("key2", "value2");

  // Create a new object in each function call when receiver is a
  // primitive value. See ECMA-262, Annex C.
  var a = [];
  map.forEach(function() { a.push(this) }, "");
  assertTrue(a[0] !== a[1]);

  // Do not create a new object otherwise.
  a = [];
  map.forEach(function() { a.push(this); }, {});
  assertEquals(a[0], a[1]);
})();


(function TestMapForEachReceiverAsObjectInStrictMode() {
  var map = new Map();
  map.set("key1", "value1");
  map.set("key2", "value2");

  // In strict mode primitive values should not be coerced to an object.
  var a = [];
  map.forEach(function() { 'use strict'; a.push(this); }, "");
  assertTrue(a[0] === "" && a[0] === a[1]);
})();


1054 1055 1056 1057 1058 1059 1060
// Allows testing iterator-based constructors easily.
var oneAndTwo = new Map();
var k0 = {key: 0};
var k1 = {key: 1};
var k2 = {key: 2};
oneAndTwo.set(k1, 1);
oneAndTwo.set(k2, 2);
1061

1062 1063 1064 1065 1066 1067 1068

function TestSetConstructor(ctor) {
  var s = new ctor(null);
  assertSize(0, s);

  s = new ctor(undefined);
  assertSize(0, s);
1069 1070 1071

  // No @@iterator
  assertThrows(function() {
1072
    new ctor({});
1073
  }, TypeError);
1074 1075 1076
  assertThrows(function() {
    new ctor(true);
  }, TypeError);
1077 1078 1079 1080 1081

  // @@iterator not callable
  assertThrows(function() {
    var object = {};
    object[Symbol.iterator] = 42;
1082
    new ctor(object);
1083 1084 1085 1086 1087 1088 1089 1090
  }, TypeError);

  // @@iterator result not object
  assertThrows(function() {
    var object = {};
    object[Symbol.iterator] = function() {
      return 42;
    };
1091
    new ctor(object);
1092 1093 1094
  }, TypeError);

  var s2 = new Set();
1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105
  s2.add(k0);
  s2.add(k1);
  s2.add(k2);
  s = new ctor(s2.values());
  assertSize(3, s);
  assertTrue(s.has(k0));
  assertTrue(s.has(k1));
  assertTrue(s.has(k2));
}
TestSetConstructor(Set);
TestSetConstructor(WeakSet);
1106 1107


1108 1109
function TestSetConstructorAddNotCallable(ctor) {
  var originalPrototypeAdd = ctor.prototype.add;
1110
  assertThrows(function() {
1111 1112
    ctor.prototype.add = 42;
    new ctor(oneAndTwo.values());
1113
  }, TypeError);
1114 1115 1116 1117
  ctor.prototype.add = originalPrototypeAdd;
}
TestSetConstructorAddNotCallable(Set);
TestSetConstructorAddNotCallable(WeakSet);
1118 1119


1120 1121
function TestSetConstructorGetAddOnce(ctor) {
  var originalPrototypeAdd = ctor.prototype.add;
1122
  var getAddCount = 0;
1123
  Object.defineProperty(ctor.prototype, 'add', {
1124 1125 1126 1127 1128
    get: function() {
      getAddCount++;
      return function() {};
    }
  });
1129 1130 1131 1132 1133
  var s = new ctor(oneAndTwo.values());
  assertEquals(1, getAddCount);
  assertSize(0, s);
  Object.defineProperty(ctor.prototype, 'add', {
    value: originalPrototypeAdd,
1134 1135
    writable: true
  });
1136 1137 1138
}
TestSetConstructorGetAddOnce(Set);
TestSetConstructorGetAddOnce(WeakSet);
1139 1140


1141 1142
function TestSetConstructorAddReplaced(ctor) {
  var originalPrototypeAdd = ctor.prototype.add;
1143
  var addCount = 0;
1144
  ctor.prototype.add = function(value) {
1145
    addCount++;
1146 1147
    originalPrototypeAdd.call(this, value);
    ctor.prototype.add = null;
1148
  };
1149 1150 1151 1152 1153 1154 1155
  var s = new ctor(oneAndTwo.keys());
  assertEquals(2, addCount);
  assertSize(2, s);
  ctor.prototype.add = originalPrototypeAdd;
}
TestSetConstructorAddReplaced(Set);
TestSetConstructorAddReplaced(WeakSet);
1156 1157


1158
function TestSetConstructorOrderOfDoneValue(ctor) {
1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176
  var valueCount = 0, doneCount = 0;
  var iterator = {
    next: function() {
      return {
        get value() {
          valueCount++;
        },
        get done() {
          doneCount++;
          throw new Error();
        }
      };
    }
  };
  iterator[Symbol.iterator] = function() {
    return this;
  };
  assertThrows(function() {
1177
    new ctor(iterator);
1178
  });
1179 1180 1181 1182 1183
  assertEquals(1, doneCount);
  assertEquals(0, valueCount);
}
TestSetConstructorOrderOfDoneValue(Set);
TestSetConstructorOrderOfDoneValue(WeakSet);
1184 1185


1186
function TestSetConstructorNextNotAnObject(ctor) {
1187 1188 1189 1190 1191 1192 1193 1194 1195
  var iterator = {
    next: function() {
      return 'abc';
    }
  };
  iterator[Symbol.iterator] = function() {
    return this;
  };
  assertThrows(function() {
1196
    new ctor(iterator);
1197
  }, TypeError);
1198 1199 1200
}
TestSetConstructorNextNotAnObject(Set);
TestSetConstructorNextNotAnObject(WeakSet);
1201 1202


1203 1204 1205 1206 1207 1208 1209
(function TestWeakSetConstructorNonObjectKeys() {
  assertThrows(function() {
    new WeakSet([1]);
  }, TypeError);
})();


1210 1211 1212 1213 1214
function TestSetConstructorIterableValue(ctor) {
  'use strict';
  // Strict mode is required to prevent implicit wrapping in the getter.
  Object.defineProperty(Number.prototype, Symbol.iterator, {
    get: function() {
arv's avatar
arv committed
1215
      assertEquals('number', typeof this);
1216
      return function() {
arv's avatar
arv committed
1217
        assertEquals('number', typeof this);
1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243
        return oneAndTwo.keys();
      };
    },
    configurable: true
  });

  var set = new ctor(42);
  assertSize(2, set);
  assertTrue(set.has(k1));
  assertTrue(set.has(k2));

  delete Number.prototype[Symbol.iterator];
}
TestSetConstructorIterableValue(Set);
TestSetConstructorIterableValue(WeakSet);


(function TestSetConstructorStringValue() {
  var s = new Set('abc');
  assertSize(3, s);
  assertTrue(s.has('a'));
  assertTrue(s.has('b'));
  assertTrue(s.has('c'));
})();


1244 1245 1246
function TestMapConstructor(ctor) {
  var m = new ctor(null);
  assertSize(0, m);
1247

1248 1249
  m = new ctor(undefined);
  assertSize(0, m);
1250 1251 1252

  // No @@iterator
  assertThrows(function() {
1253
    new ctor({});
1254
  }, TypeError);
1255 1256 1257
  assertThrows(function() {
    new ctor(true);
  }, TypeError);
1258 1259 1260 1261 1262

  // @@iterator not callable
  assertThrows(function() {
    var object = {};
    object[Symbol.iterator] = 42;
1263
    new ctor(object);
1264 1265 1266 1267 1268 1269 1270 1271
  }, TypeError);

  // @@iterator result not object
  assertThrows(function() {
    var object = {};
    object[Symbol.iterator] = function() {
      return 42;
    };
1272
    new ctor(object);
1273 1274 1275
  }, TypeError);

  var m2 = new Map();
1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286
  m2.set(k0, 'a');
  m2.set(k1, 'b');
  m2.set(k2, 'c');
  m = new ctor(m2.entries());
  assertSize(3, m);
  assertEquals('a', m.get(k0));
  assertEquals('b', m.get(k1));
  assertEquals('c', m.get(k2));
}
TestMapConstructor(Map);
TestMapConstructor(WeakMap);
1287 1288


1289 1290
function TestMapConstructorSetNotCallable(ctor) {
  var originalPrototypeSet = ctor.prototype.set;
1291
  assertThrows(function() {
1292 1293
    ctor.prototype.set = 42;
    new ctor(oneAndTwo.entries());
1294
  }, TypeError);
1295 1296 1297 1298
  ctor.prototype.set = originalPrototypeSet;
}
TestMapConstructorSetNotCallable(Map);
TestMapConstructorSetNotCallable(WeakMap);
1299 1300


1301 1302
function TestMapConstructorGetAddOnce(ctor) {
  var originalPrototypeSet = ctor.prototype.set;
1303
  var getSetCount = 0;
1304
  Object.defineProperty(ctor.prototype, 'set', {
1305 1306 1307 1308 1309
    get: function() {
      getSetCount++;
      return function() {};
    }
  });
1310 1311 1312 1313 1314
  var m = new ctor(oneAndTwo.entries());
  assertEquals(1, getSetCount);
  assertSize(0, m);
  Object.defineProperty(ctor.prototype, 'set', {
    value: originalPrototypeSet,
1315 1316
    writable: true
  });
1317 1318 1319
}
TestMapConstructorGetAddOnce(Map);
TestMapConstructorGetAddOnce(WeakMap);
1320 1321


1322 1323
function TestMapConstructorSetReplaced(ctor) {
  var originalPrototypeSet = ctor.prototype.set;
1324
  var setCount = 0;
1325
  ctor.prototype.set = function(key, value) {
1326
    setCount++;
1327 1328
    originalPrototypeSet.call(this, key, value);
    ctor.prototype.set = null;
1329
  };
1330 1331 1332 1333 1334 1335 1336
  var m = new ctor(oneAndTwo.entries());
  assertEquals(2, setCount);
  assertSize(2, m);
  ctor.prototype.set = originalPrototypeSet;
}
TestMapConstructorSetReplaced(Map);
TestMapConstructorSetReplaced(WeakMap);
1337 1338


1339
function TestMapConstructorOrderOfDoneValue(ctor) {
1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358
  var valueCount = 0, doneCount = 0;
  function FakeError() {}
  var iterator = {
    next: function() {
      return {
        get value() {
          valueCount++;
        },
        get done() {
          doneCount++;
          throw new FakeError();
        }
      };
    }
  };
  iterator[Symbol.iterator] = function() {
    return this;
  };
  assertThrows(function() {
1359
    new ctor(iterator);
1360
  }, FakeError);
1361 1362 1363 1364 1365
  assertEquals(1, doneCount);
  assertEquals(0, valueCount);
}
TestMapConstructorOrderOfDoneValue(Map);
TestMapConstructorOrderOfDoneValue(WeakMap);
1366 1367


1368
function TestMapConstructorNextNotAnObject(ctor) {
1369 1370 1371 1372 1373 1374 1375 1376 1377
  var iterator = {
    next: function() {
      return 'abc';
    }
  };
  iterator[Symbol.iterator] = function() {
    return this;
  };
  assertThrows(function() {
1378
    new ctor(iterator);
1379
  }, TypeError);
1380 1381 1382
}
TestMapConstructorNextNotAnObject(Map);
TestMapConstructorNextNotAnObject(WeakMap);
1383 1384


1385
function TestMapConstructorIteratorNotObjectValues(ctor) {
1386
  assertThrows(function() {
1387
    new ctor(oneAndTwo.values());
1388
  }, TypeError);
1389 1390 1391
}
TestMapConstructorIteratorNotObjectValues(Map);
TestMapConstructorIteratorNotObjectValues(WeakMap);
1392 1393 1394 1395 1396 1397 1398


(function TestWeakMapConstructorNonObjectKeys() {
  assertThrows(function() {
    new WeakMap([[1, 2]])
  }, TypeError);
})();
1399 1400 1401 1402 1403 1404 1405


function TestMapConstructorIterableValue(ctor) {
  'use strict';
  // Strict mode is required to prevent implicit wrapping in the getter.
  Object.defineProperty(Number.prototype, Symbol.iterator, {
    get: function() {
arv's avatar
arv committed
1406
      assertEquals('number', typeof this);
1407
      return function() {
arv's avatar
arv committed
1408
        assertEquals('number', typeof this);
1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423
        return oneAndTwo.entries();
      };
    },
    configurable: true
  });

  var map = new ctor(42);
  assertSize(2, map);
  assertEquals(1, map.get(k1));
  assertEquals(2, map.get(k2));

  delete Number.prototype[Symbol.iterator];
}
TestMapConstructorIterableValue(Map);
TestMapConstructorIterableValue(WeakMap);
1424 1425 1426 1427 1428 1429 1430 1431 1432

function TestCollectionToString(C) {
  assertEquals("[object " + C.name + "]",
      Object.prototype.toString.call(new C()));
}
TestCollectionToString(Map);
TestCollectionToString(Set);
TestCollectionToString(WeakMap);
TestCollectionToString(WeakSet);
1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467


function TestConstructorOrderOfAdderIterator(ctor, adderName) {
  var iterable = new Map();
  iterable.set({}, {});
  iterable.set({}, {});
  var iterableFunction = iterable[Symbol.iterator];
  Object.defineProperty(iterable, Symbol.iterator, {
    get: function() {
      log += 'iterator';
      return iterableFunction;
    }
  });

  var log = '';
  var adderFunction = ctor.prototype[adderName];

  Object.defineProperty(ctor.prototype, adderName, {
    get: function() {
      log += adderName;
      return adderFunction;
    }
  });

  new ctor(iterable);
  assertEquals(adderName + 'iterator', log);

  Object.defineProperty(ctor.prototype, adderName, {
    value: adderFunction
  });
}
TestConstructorOrderOfAdderIterator(Map, 'set');
TestConstructorOrderOfAdderIterator(Set, 'add');
TestConstructorOrderOfAdderIterator(WeakMap, 'set');
TestConstructorOrderOfAdderIterator(WeakSet, 'add');