SHOW:
|
|
- or go back to the newest paste.
| 1 | // 29: array - `Array.from` static method | |
| 2 | // To do: make all tests pass, leave the assert lines unchanged! | |
| 3 | ||
| 4 | describe('`Array.from` converts an array-like object or list into an Array', () => { | |
| 5 | ||
| 6 | const arrayLike = {0: 'one', 1: 'two', length: 2}; | |
| 7 | ||
| 8 | it('call `Array.from` with an array-like object', function() { | |
| 9 | //Use built in function Array.from() | |
| 10 | const arr = Array.from(arrayLike); | |
| 11 | ||
| 12 | assert.deepEqual(arr, ['one', 'two']); | |
| 13 | }); | |
| 14 | ||
| 15 | it('a DOM node`s classList object can be converted', function() { | |
| 16 | document.body.classList.add('some'); | |
| 17 | document.body.classList.add('other'); | |
| 18 | //Make an array from the arraylike object | |
| 19 | const classList = Array.from(document.body.classList); | |
| 20 | ||
| 21 | assert.equal(''+classList, ''+['some', 'other']); | |
| 22 | }); | |
| 23 | ||
| 24 | it('convert a NodeList to an Array and `filter()` works on it', function() { | |
| 25 | //Again we want to build an array from an arraylike object | |
| 26 | const nodeList = Array.from(document.querySelectorAll('body')); | |
| 27 | const bodies = nodeList.filter((node) => node === document.body); | |
| 28 | ||
| 29 | assert.deepEqual(bodies, [document.body]); | |
| 30 | }); | |
| 31 | ||
| 32 | describe('custom conversion using a map function as second param', () => { | |
| 33 | it('we can modify the value before putting it in the array', function() { | |
| 34 | //Use toUpperCase() built in fn to cast to uppercase. | |
| 35 | const arr = Array.from(arrayLike, (value) => value.toUpperCase()); | |
| 36 | assert.deepEqual(arr, ['ONE', 'TWO']); | |
| 37 | }); | |
| 38 | ||
| 39 | it('and we also get the object`s key as second parameter', function() { | |
| 40 | //Add a second parameter called key. TBH it feels backwards but hey, it's kata time! Don't question it | |
| 41 | const arr = Array.from(arrayLike, (value, key) => `${key}=${value}`); | |
| 42 | assert.deepEqual(arr, ['0=one', '1=two']); | |
| 43 | }); | |
| 44 | }); | |
| 45 | ||
| 46 | }); |