-
Notifications
You must be signed in to change notification settings - Fork 0
/
solution.js
66 lines (60 loc) · 2.11 KB
/
solution.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
// 59: Reflect - apply (solution)
// To do: make all tests pass, leave the assert lines unchanged!
describe('`Reflect.apply` calls a target function', function() {
it('it is a static method', function() {
const expectedType = 'function';
assert.equal(typeof Reflect.apply, expectedType)
});
describe('the 1st parameter', () => {
it('is a callable, e.g. a function', () => {
let fn = () => 42;
assert.equal(Reflect.apply(fn, void 0, []), 42);
});
it('passing it a non-callable throws a TypeError', function() {
let applyOnUncallable = () => {
Reflect.apply(Array);
};
assert.throws(applyOnUncallable, TypeError);
});
});
describe('the 2nd parameter', () => {
it('is the scope (or the `this`)', function() {
class FourtyTwo {
constructor() { this.value = 42}
fn() {return this.value}
}
let instance = new FourtyTwo();
const fourtyTwo = Reflect.apply(instance.fn, instance, []);
assert.deepEqual(fourtyTwo, 42);
});
});
describe('the 3rd parameter', () => {
it('must be an array (or array-like)', () => {
const thirdParam = [];
assert.doesNotThrow(() => Reflect.apply(() => void 0, null, thirdParam));
});
it('is an array of parameters passed to the call', function() {
let emptyArrayWithFiveElements = Reflect.apply(Array, undefined, [5]);
assert.deepEqual(emptyArrayWithFiveElements.fill(42), [42, 42, 42, 42, 42]);
});
});
describe('example usages', () => {
it('simple function call', () => {
const fn = () => 'the return value';
assert.equal(Reflect.apply(fn, void 0, []), 'the return value');
});
it('call a function on an array', () => {
const fn = [].slice;
assert.deepEqual(Reflect.apply(fn, [0, 23, 42], [1]), [23, 42]);
});
it('pass in the `this` that the function to call needs', () => {
class Bob {
constructor() { this._name = 'Bob'; }
name() { return this._name; }
}
const bob = new Bob();
const scope = bob;
assert.equal(Reflect.apply(bob.name, scope, []), 'Bob');
});
});
});