forked from sgrouples/javascript-assignment
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathex10.js
More file actions
52 lines (33 loc) · 1.22 KB
/
Copy pathex10.js
File metadata and controls
52 lines (33 loc) · 1.22 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
43
44
45
46
47
48
49
50
51
52
/*
SPY
Override a specified method of an object with new functionality while still maintaining all of the old behaviour.
Create a spy that keeps track of how many times a function is called.
## Example
var spy = Spy(console, 'error')
console.error('calling console.error')
console.error('calling console.error')
console.error('calling console.error')
console.log(spy.count) // 3
## Arguments
* target: an object containing the method `method`
* method: a string with the name of the method on `target` to spy on.
## Conditions
* Do not use any for/while loops or Array#forEach.
* Do not create any unnecessary functions e.g. helpers.
## Hint
* Functions have context, input and output. Make sure you consider the context, input to *and output from* the function you are spying on.
*/
function Spy(target, method) {
this.count = 0;
this.originalMethod = target[method];
target[method] = function() {
this.originalMethod.apply(target, arguments);
this.count = this.count + 1;
}.bind(this);
return this;
}
var spy = Spy(console, 'error')
console.error('calling console.error')
console.error('calling console.error')
console.error('calling console.error')
console.log(spy.count) // 3