MIRROR: javascript for 馃悳's, a tiny runtime with big ambitions
1
fork

Configure Feed

Select the types of activity you want to include in your feed.

at master 72 lines 2.4 kB view raw
1// Test WeakMap functionality 2console.log('=== WeakMap Tests ==='); 3 4const wm = new WeakMap(); 5 6// Test with object keys 7const key1 = { id: 1 }; 8const key2 = { id: 2 }; 9const key3 = { id: 3 }; 10 11// Test set and get 12wm.set(key1, 'value1'); 13wm.set(key2, { data: 42 }); 14wm.set(key3, true); 15 16console.log('Get key1:', wm.get(key1)); // Should be 'value1' 17console.log('Get key2:', wm.get(key2)); // Should be { data: 42 } 18console.log('Get key3:', wm.get(key3)); // Should be true 19 20// Test has() 21console.log('Has key1:', wm.has(key1)); // Should be true 22console.log('Has key2:', wm.has(key2)); // Should be true 23const key4 = { id: 4 }; 24console.log('Has key4 (not added):', wm.has(key4)); // Should be false 25 26// Test delete() 27console.log('Delete key2:', wm.delete(key2)); // Should be true 28console.log('Has key2 after delete:', wm.has(key2)); // Should be false 29console.log('Get key2 after delete:', wm.get(key2)); // Should be undefined 30 31// Test that key1 and key3 are still there 32console.log('Has key1 after delete key2:', wm.has(key1)); // Should be true 33console.log('Has key3 after delete key2:', wm.has(key3)); // Should be true 34 35// Test overwrite 36wm.set(key1, 'newvalue1'); 37console.log('Get key1 after overwrite:', wm.get(key1)); // Should be 'newvalue1' 38 39// Test that primitive keys throw errors 40try { 41 wm.set('string', 'value'); 42 console.log('ERROR: Should have thrown for string key'); 43} catch (e) { 44 console.log('Correctly threw error for string key:', e.message); 45} 46 47try { 48 wm.set(123, 'value'); 49 console.log('ERROR: Should have thrown for number key'); 50} catch (e) { 51 console.log('Correctly threw error for number key:', e.message); 52} 53 54try { 55 wm.set(null, 'value'); 56 console.log('ERROR: Should have thrown for null key'); 57} catch (e) { 58 console.log('Correctly threw error for null key:', e.message); 59} 60 61// Test get/has/delete with non-object keys (should return undefined/false) 62console.log('Get with string key:', wm.get('string')); // Should be undefined 63console.log('Has with number key:', wm.has(123)); // Should be false 64console.log('Delete with boolean key:', wm.delete(true)); // Should be false 65 66// Test multiple WeakMaps 67const wm2 = new WeakMap(); 68wm2.set(key1, 'different value'); 69console.log('Get key1 from wm:', wm.get(key1)); // Should be 'newvalue1' 70console.log('Get key1 from wm2:', wm2.get(key1)); // Should be 'different value' 71 72console.log('WeakMap tests completed!');