Skip to content

Instantly share code, notes, and snippets.

@r3nya r3nya/flatten.js
Last active May 4, 2019

Embed
What would you like to do?
Array#flatten()

Hello! :)

» npm t

 PASS  ./flatten.test.js
  flatten
    when input value is not Array
      when input value is undefined
        ✓ returns "undefined" (3ms)
      when input value is null
        ✓ returns "undefined"
      when input value is number
        ✓ returns "undefined" (1ms)
      when input value is string
        ✓ returns "undefined"
      when input value is object
        ✓ returns "undefined"
    when input value is Array
      when array is empty
        ✓ returns flattened array (1ms)
      when array is flat
        ✓ returns flattened array
      when array is not a flat
        ✓ returns flattened array
        ✓ returns flattened array

Test Suites: 1 passed, 1 total
Tests:       9 passed, 9 total
Snapshots:   0 total
Time:        0.775s, estimated 1s
Ran all test suites.
export const flatten = (arr) => {
if (!(arr && Array.isArray(arr))) {
return undefined;
}
return arr.reduce(
(acc, currentValue) => (
acc.concat(Array.isArray(currentValue)
? flatten(currentValue)
: currentValue)
),
[]
);
};
export default flatten;
import { flatten } from './flatten';
describe('flatten', () => {
let result;
let inputValue;
beforeEach(() => result = flatten(inputValue));
describe('when input value is not Array', () => {
describe.each`
input | type
${undefined} | ${undefined}
${null} | ${null}
${123} | ${'number'}
${'iHopeYouWillSeeIt'} | ${'string'}
${{ a: 1 }} | ${'object'}
`('when input value is $type', ({ input, type }) => {
beforeAll(() => inputValue = input);
it('returns "undefined"', () => {
expect(result).toBeUndefined();
});
});
});
describe('when input value is Array', () => {
describe.each`
input | comment | expectedValue
${[]} | ${'empty'} | ${[]}
${[1, 2, 3]} | ${'flat'} | ${[1, 2, 3]}
${[1, [2]]} | ${'not a flat'} | ${[1, 2]}
${[1, [[2]]]} | ${'not a flat'} | ${[1, 2]}
`('when array is $comment', ({ input, comment, expectedValue }) => {
beforeAll(() => inputValue = input);
it(`returns flattened array`, () => {
expect(result).toEqual(expectedValue);
});
});
});
});
{
"name": "flatten",
"version": "1.0.0",
"description": "flatten for Array",
"main": "index.js",
"scripts": {
"test": "jest"
},
"keywords": [],
"author": "",
"license": "ISC",
"devDependencies": {
"@babel/core": "^7.4.4",
"@babel/preset-env": "^7.4.4",
"@types/jest": "^24.0.12",
"babel-jest": "^24.7.1",
"jest": "^24.7.1"
},
"jest": {
"clearMocks": true,
"testEnvironment": "node"
},
"babel": {
"presets": [
[
"@babel/preset-env",
{
"targets": {
"node": "current"
}
}
]
]
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.