This repository has been archived by the owner on Oct 18, 2024. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathconsole-shim.es6.js
114 lines (99 loc) · 2.1 KB
/
console-shim.es6.js
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
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
// https://github.com/liamnewmarch/console-shim 2014 CC-BY @liamnewmarch
/**
* Methods we want to (try to) map onto the native window.console. Methods that
* don’t exist will get passed to console.log.
*/
const methodsToShim = [
'assert',
'count',
'debug',
'dir',
'dirxml',
'error',
'exception',
'group',
'groupCollapsed',
'groupEnd',
'info',
'log',
'table',
'trace',
'warn',
];
/**
* Methods we can’t replicate and are handled by a no-op function.
*/
const methodsToIgnore = [
'clear',
'count',
'profile',
'profileEnd',
'timeStamp',
];
/**
* The console shim class.
*/
class ConsoleShim {
/**
* Initialise the buffer, setup methods and watch for console.
*
* @constructor
*/
constructor() {
this.__buffer = [];
this.__mapMethods();
this.__watchForConsole();
}
/**
* Add a method to mirror window.console.
*
* @param {string} key Name of the console method.
* @private
*/
__addMethod(key) {
return (...args) => this.__buffer.push(key, args);
}
/**
* Call a method on the native window.console.
*
* @param {string} method Method to call.
* @param {array} args Args to pass to method.
* @private
*/
__callNativeMethod(method, args) {
method = method in window.console || 'log';
window.console.log(...args);
}
/**
* Iterate method keys, and shim or ignore as appropriate.
*
* @private
*/
__mapMethods() {
const noop = function() {/* noop */};
methodsToShim.forEach(key => this[key] = this.__addMethod(key));
methodsToIgnore.forEach(key => this[key] = noop);
}
/**
* Watch for the native window.console. If it’s not available wait a second
* and try again.
*
* @private
*/
__watchForConsole() {
if (window.console instanceof ConsoleShim) {
return;
}
if ('check' in this) {
clearTimeout(this.check);
}
this.__buffer.forEach(args => {
this.__logToConsole(...args);
});
this.check = setTimeout(this.__watchForConsole, 1000);
}
}
/**
* Expose our console shim instance.
*/
export default new ConsoleShim();