-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathex4.js
More file actions
42 lines (34 loc) · 1.1 KB
/
ex4.js
File metadata and controls
42 lines (34 loc) · 1.1 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
41
42
'use strict';
/*
Problem:
Implement `createNamespacedRegistry(namespace)`.
Return API:
- key(name): symbol
- name(sym): string | null
Rules:
- Use Symbol.for with namespaced keys: `${namespace}:${name}`.
- Same namespace+name must return same symbol across modules/instances.
- name(sym) must return original name only for symbols in this namespace.
- Non-registry symbols or other namespaces => null.
Starter code is intentionally incorrect:
- Uses Symbol(), so identity is not shared globally.
- name(sym) relies on description and can misclassify non-registry symbols.
*/
function createNamespacedRegistry(namespace) {
if (typeof namespace !== 'string' || namespace.length === 0) {
throw new TypeError('namespace must be a non-empty string');
}
return {
key(name) {
return Symbol(`${namespace}:${name}`);
},
name(sym) {
if (typeof sym !== 'symbol') return null;
const d = sym.description || '';
const prefix = `${namespace}:`;
if (!d.startsWith(prefix)) return null;
return d.slice(prefix.length);
},
};
}
module.exports = { createNamespacedRegistry };