MIRROR: javascript for 馃悳's, a tiny runtime with big ambitions
1let d = new Date();
2
3// Test 1: Default behavior
4console.log(d[Symbol.toPrimitive]('default')); // Should call toString
5
6// Test 2: String hint
7console.log(d[Symbol.toPrimitive]('string')); // Should call toString
8
9// Test 3: Number hint
10console.log(d[Symbol.toPrimitive]('number')); // Should call valueOf (timestamp)
11
12// Test 4: Coercion tests
13console.log(d + ''); // Uses default hint -> string
14console.log(+d); // Uses number hint -> number
15console.log(d - 0); // Uses number hint -> number
16
17// Test 5: Verify order - SAVE ORIGINAL METHODS FIRST
18const originalValueOf = Date.prototype.valueOf;
19const originalToString = Date.prototype.toString;
20
21Date.prototype.valueOf = function () {
22 console.log('valueOf called');
23 return originalValueOf.call(this); // Call the SAVED original
24};
25Date.prototype.toString = function () {
26 console.log('toString called');
27 return originalToString.call(this); // Call the SAVED original
28};
29
30let d2 = new Date();
31console.log('\nTesting string hint:');
32d2[Symbol.toPrimitive]('string'); // Should log: toString only (returns primitive)
33
34console.log('\nTesting number hint:');
35d2[Symbol.toPrimitive]('number'); // Should log: valueOf only (returns primitive)
36
37console.log('\nTesting default hint:');
38d2[Symbol.toPrimitive]('default'); // Should log: toString only (returns primitive)
39
40// Restore original methods
41Date.prototype.valueOf = originalValueOf;
42Date.prototype.toString = originalToString;