-
Notifications
You must be signed in to change notification settings - Fork 0
/
solution.js
70 lines (59 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
67
68
69
70
// 71: String - `repeat()` (solution)
// To do: make all tests pass, leave the assert lines unchanged!
describe('`str.repeat(x)` appends `x` copies of `str` to each other and returns it', function() {
describe('pass the count to `str.repeat(count)`', function() {
it('for `1` the string stays the same', function() {
const what = 'one'.repeat(1);
assert.equal(what, 'one');
});
it('for `3` the string `x` becomes `xxx`', function() {
const actual = 'x'.repeat(3);
assert.equal(actual, 'xxx');
});
it('for `0` an empty string is returned', function() {
const dontRepeat = 0;
assert.equal('shrink'.repeat(dontRepeat), '');
});
it('the count is not an int, such as "3", it gets coerced to an int', function() {
const repeated = 'three'.repeat('3');
assert.equal(repeated, 'threethreethree');
});
});
describe('throws an error for', function() {
it('a count of <0', function() {
const belowZero = -1;
assert.throws(() => { ''.repeat(belowZero); }, RangeError);
});
it('a count of +Infinty', function() {
let infinity = Infinity;
assert.throws(() => { ''.repeat(infinity); }, RangeError);
});
});
describe('accepts everything that can be coerced to a string', function() {
it('e.g. a boolean', function() {
let aBool = false;
assert.equal(String.prototype.repeat.call(aBool, 2), 'falsefalse');
});
it('e.g. a number', function() {
let aNumber = 1;
assert.equal(String.prototype.repeat.call(aNumber, 2), '11');
});
});
describe('for my own (string) class', function() {
it('calls `toString()` to make it a string', function() {
class MyString { toString() { return 'my string'; } }
const expectedString = new MyString();
assert.equal(String(new MyString()).repeat(1), expectedString);
});
it('`toString()` is only called once', function() {
let counter = 1;
class X {
toString() {
return counter++;
}
}
let repeated = String(new X()).repeat(2);
assert.equal(repeated, '11');
});
});
});