Created
December 8, 2018 08:13
-
-
Save masious/d3c860d0c4facc7f97556075df3f7dff to your computer and use it in GitHub Desktop.
JavaScript Flatten Implementation
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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); | |
}, []); | |
}; |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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