Skip to content

Instantly share code, notes, and snippets.

@armw4
Last active December 2, 2016 00:50
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 armw4/d491e3822320f874d02d8414ec7852f0 to your computer and use it in GitHub Desktop.
Save armw4/d491e3822320f874d02d8414ec7852f0 to your computer and use it in GitHub Desktop.
Integer flatten example while taking depth into account (via node version v7.1.0)
const flattenInternal = (input, initialDepth, acculamator = [], depth = 0) => {
if (initialDepth !== undefined && depth > initialDepth) {
throw new Error(`array has exceeded the target depth of ${initialDepth}.`)
}
return input.reduce((acc, value) => {
if (Array.isArray(value)) {
if (initialDepth !== undefined) {
return flattenInternal(value, initialDepth, acc, depth + 1)
}
return flattenInternal(value, initialDepth, acc, depth)
}
if (!Number.isInteger(value)) {
throw new Error(`wrong again bra (expected ${value} to be an integer but got ${typeof value}). try again.`)
}
return [...acc, value]
}, acculamator)
}
module.exports = (input, depth = undefined) => {
if (depth !== undefined && !Number.isInteger(depth)) {
throw new Error('depth must be an integer.')
}
return flattenInternal(input, depth)
}
const flatten = require('./array-flatten')
const assert = require('assert')
describe('flatten integers', () => {
it('should throw if array depth is exceeded', () => {
assert.throws(() => flatten([[1,2,[3]],4], 1), /array has exceeded the target depth of 1./)
})
it('should throw if depth is not an integer', () => {
assert.throws(() => flatten([[1,2,[3]],4], 'not-an-integer'), /depth must be an integer\./)
})
it('should throw if depth is null', () => {
assert.throws(() => flatten([[1,2,[3]],4], null), /depth must be an integer\./)
})
it('should not throw if array depth is not exceeded', () => {
assert.deepEqual(flatten([[1,2,[3]],4], 2), [1,2,3,4])
})
it('should throw if any element is not an integer', () => {
assert.throws(() => flatten([[1,2,[3]],'oo']), /wrong again bra \(expected oo to be an integer but got string\)\. try again\./)
})
it('should allow an array of arbitrary depth if no depth is provided', () => {
assert.deepEqual(flatten([[1,2,[3, [118, [333], 12]]],88]), [1,2,3,118,333,12,88])
})
it('should allow an array of arbitrary depth if depth is undefined', () => {
assert.deepEqual(flatten([[1,2,[3, [118, [333], 12]]],88], undefined), [1,2,3,118,333,12,88])
})
})
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment