Skip to content

Commit a65e6d7

Browse files
authored
Merge pull request #13 from Asondo/master
Add polyfill module implementing NodeJS-like behavior
2 parents 63b4012 + c4a67f2 commit a65e6d7

File tree

1 file changed

+68
-0
lines changed

1 file changed

+68
-0
lines changed

fs/polyfill.js

Lines changed: 68 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,68 @@
1+
// TODO: implement error & warn/debug/stack methods
2+
let console = {log: print, error: print};
3+
let module = {exports: null, _cache: {}};
4+
5+
function __resolvePath(p) {
6+
let sf = '.js';
7+
let f = p.length - 3;
8+
let e = p.indexOf(sf, f < 0 ? 0 : f);
9+
if (e === -1) {
10+
return p + sf;
11+
}
12+
13+
return p;
14+
}
15+
16+
function require(path) {
17+
// Add .js if not set
18+
path = __resolvePath(path);
19+
20+
// Prevent duplicate load, return from cache
21+
let c = module._cache[path];
22+
if (c !== undefined) {
23+
return c;
24+
}
25+
26+
// noinspection JSUnresolvedFunction
27+
load(path);
28+
29+
// Add module to cache
30+
c = module._cache[path] = module.exports;
31+
// clean exports data to prevent modules duplication
32+
module.exports = null;
33+
34+
return c;
35+
}
36+
37+
// Load Timer lib only on demand & cache result
38+
let __timer = null;
39+
40+
function __getTimer() {
41+
if (!__timer) {
42+
// TODO: add module.export to api_timer & use require with caching
43+
// noinspection JSUnresolvedFunction
44+
load('api_timer.js');
45+
46+
__timer = Timer;
47+
}
48+
49+
return __timer;
50+
}
51+
52+
function setInterval(fn, timeout) {
53+
let t = __getTimer();
54+
55+
return t.set(timeout, t.REPEAT, fn, null);
56+
}
57+
58+
function setTimeout(fn, timeout) {
59+
return __getTimer().set(timeout, 0, fn, null);
60+
}
61+
62+
function clearTimeout(id) {
63+
return __getTimer().del(id);
64+
}
65+
66+
function clearInterval(id) {
67+
return clearTimeout(id);
68+
}

0 commit comments

Comments
 (0)