Skip to content

Instantly share code, notes, and snippets.

@ArnaudBuchholz
Created December 8, 2023 16:14
Show Gist options
  • Save ArnaudBuchholz/22723ec0c3b526b64c2e9d732e1cf3c8 to your computer and use it in GitHub Desktop.
Save ArnaudBuchholz/22723ec0c3b526b64c2e9d732e1cf3c8 to your computer and use it in GitHub Desktop.
function trunkSize (n) {
return Math.floor(n / 3)
}
function drawTopOfTree (chars, n) {
const width = (n - 1) * 2 + 1
let currentPos = 0
return new Array(n).fill(0).map((_, index) => {
const placeholders = new Array(index + 1).fill('x').join(' ')
const spaceLeft = width - placeholders.length
const borders = ''.padStart(spaceLeft / 2, ' ')
return borders + placeholders.replace(/x/g, () => chars[currentPos++ % chars.length]) + borders
})
}
module.exports = {
trunkSize,
drawTopOfTree
}
if (require.main === module) {
const [,, chars, rawN] = process.argv
const n = parseInt(rawN, 10)
console.log(drawTopOfTree(chars, n).join('\n'))
for (let i = 0; i < trunkSize(n); ++i) {
console.log('|'.padStart(n, ' '))
}
}
const assert = require('assert/strict')
const { trunkSize, drawTopOfTree } = require('..')
describe('Christmas Tree', () => {
describe('Computing the trunk size', () => {
const expectations = [{
size: 3,
trunk: 1
}, {
size: 4,
trunk: 1
}, {
size: 5,
trunk: 1
}, {
size: 6,
trunk: 2
}, {
size: 8,
trunk: 2
}, {
size: 13,
trunk: 4
}]
expectations.forEach(({ size, trunk }) => {
it(`returns ${trunk} for n = ${size}`, () => {
assert.equal(trunkSize(size), trunk)
})
})
})
describe('Top of the tree', () => {
it('drawing the tree with \'x\' char and n = 3', () => {
assert.deepEqual(drawTopOfTree('x', 3), [
' x ',
' x x ',
'x x x'
])
})
it('drawing the tree with \'*\' char and n = 3', () => {
assert.deepEqual(drawTopOfTree('*', 3), [
' * ',
' * * ',
'* * *'
])
})
it('drawing the tree with \'*@\' chars and n = 3', () => {
assert.deepEqual(drawTopOfTree('*@', 3), [
' * ',
' @ * ',
'@ * @'
])
})
it('drawing the tree with \'x\' char and n = 4', () => {
assert.deepEqual(drawTopOfTree('x', 4), [
' x ',
' x x ',
' x x x ',
'x x x x'
])
})
it('drawing the tree with \'1234\' chars and n = 4', () => {
assert.deepEqual(drawTopOfTree('1234', 4), [
' 1 ',
' 2 3 ',
' 4 1 2 ',
'3 4 1 2'
])
})
})
})
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment