Skip to content

Instantly share code, notes, and snippets.

@masious
Created December 8, 2018 08:13
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save masious/d3c860d0c4facc7f97556075df3f7dff to your computer and use it in GitHub Desktop.
Save masious/d3c860d0c4facc7f97556075df3f7dff to your computer and use it in GitHub Desktop.
JavaScript Flatten Implementation
export default function flatten (arr) {
return arr.reduce((result, current) => {
let items;
if (Array.isArray(current)) {
items = flatten(current);
} else if (typeof current === "number") {
items = [current];
} else {
throw new Error(`Expected item to be number or array: ${current}`);
}
return result.concat(items);
}, []);
};
import flatten from "./flatten";
describe("flatten function", function() {
it("is already flat", function() {
expect(flatten([1, 2, 3, 4])).toEqual([1, 2, 3, 4]);
});
it("should flatten nested", function() {
expect(flatten([[1,2,[3]],4])).toEqual([1, 2, 3, 4]);
});
it("should not accept string", function() {
expect(flatten([1, 2, "a"])).toThrow(
new Error("Expected item to be number or array: a")
);
});
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment