March 31, 2022
TestsSource
- flat()
- flat() with a string as parameter
- flatMap()
Source Code
The source code we wrote during the event.
flatMap-flat.spec.js
import {strict as assert} from 'assert';
describe('flat()', () => {
it('an array of arrays returns a flat array', () => {
const twoDimensionalArray = [['a'], ['b'], ['c']];
const flattenedArray = twoDimensionalArray.flat();
assert.deepEqual(flattenedArray, ['a', 'b', 'c']);
});
it('flat() without parameter flattens an n-dimensional array into a n-1-dimensional array', () => {
const threeDimensionalArray = [[['a']]];
assert.deepEqual(threeDimensionalArray.flat(), [['a']]);
});
it('flat(X) flattens an n dimensional array into an n-X dimensional array', () => {
const threeDimensionalArray = [[['a']]];
assert.deepEqual(threeDimensionalArray.flat(2), ['a']);
});
it('flat() returns the same thing as flat(1)', () => {
const flattenedWithoutDepthParameter = [[['a']]].flat();
const flattenedWithOne = [[['a']]].flat(1);
assert.deepEqual(flattenedWithOne, flattenedWithoutDepthParameter);
});
it('flat(0) returns a copy of the array', () => {
const a = ['a'];
const b = a.flat(0);
assert.notEqual(a, b, 'Should not be the same object');
assert.deepEqual(a, b, 'Should have the same values');
});
it('flat(N) of an array of depth smaller then N flattens to a one dimensional array', () => {
const threeDimensionalArray = [[['a']]];
const flattened = threeDimensionalArray.flat(4);
assert.deepEqual(flattened, ['a']);
});
describe('flat() with a string as parameter', () => {
it('where the string can be converted to a number, flattening works as with a number', () => {
const threeDimensionalArray = [[['a']]];
const flattened = threeDimensionalArray.flat('1');
assert.deepEqual(flattened, [['a']]);
});
it('where the string is not numerical, flattening uses 0 as argument', () => {
const threeDimensionalArray = [[['a']]];
const flattened = threeDimensionalArray.flat(' a ');
assert.deepEqual(flattened, threeDimensionalArray);
});
});
});
describe('flatMap()', () => {
it('the result of flatMap() is equivalent to the result map().flat()', () => {
const threeDimensionalArray = [[['a']]];
const identity = x => x;
assert.deepEqual(
threeDimensionalArray.flatMap(identity),
threeDimensionalArray.map(identity).flat()
);
});
});