-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy path2-emulation.js
More file actions
40 lines (32 loc) · 1.2 KB
/
2-emulation.js
File metadata and controls
40 lines (32 loc) · 1.2 KB
1
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
28
29
30
31
32
33
34
35
36
37
38
39
40
'use strict';
// Ad-hoc polymorphism: overloading emulation
const getTypeName = (value) => {
if (value instanceof Date) return 'Date';
if (typeof value === 'number') return 'number';
if (typeof value === 'string') return 'string';
return value.constructor?.name || typeof value;
};
const adhocHandlers = new Map();
const formatDate = (...args) => {
if (args.length === 1) args.push('en-US');
const signature = `(${args.map(getTypeName).join(', ')})`;
const handler = adhocHandlers.get(signature);
if (!handler) {
throw new TypeError(`No handler for signature ${signature}`);
}
return handler(...args);
};
adhocHandlers.set('(Date, string)', (date, locales) =>
date.toLocaleDateString(locales),
);
adhocHandlers.set('(number, string)', (timestamp, locales) => {
const date = new Date(timestamp);
return date.toLocaleDateString(locales);
});
adhocHandlers.set('(string, string)', (str, locales) => {
const date = new Date(Date.parse(str));
return date.toLocaleDateString(locales);
});
console.log('formatDate(Date):', formatDate(new Date('2025-10-31')));
console.log('formatDate(string):', formatDate('2025-10-31T12:30:00Z'));
console.log('formatDate(timestamp):', formatDate(Date.now()));