Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- const flattenArray = (array = []) => {
- let queue = [...array]
- let output = []
- while (queue.length) {
- const element = queue.shift()
- if (Number.isInteger(element)) {
- output.push(element)
- } else if (Array.isArray(element)) {
- queue.unshift(...element)
- } else if (!Number.isNaN(element % 1)) {
- // typeof would report the generic 'number', so create a special case to clarify
- // modulus 1 returns NaN for non-numbers, and we know element is not an integer
- throw new Error(`Undefined behavior for element of type: (non-integer) number`)
- } else {
- throw new Error(`Undefined behavior for element of type: ${typeof element}`)
- }
- }
- return output
- }
- module.exports = flattenArray
Add Comment
Please, Sign In to add comment