Skip to content

Instantly share code, notes, and snippets.

@nolleto
Last active June 8, 2018 18:08
Show Gist options
  • Save nolleto/3cbac79e94cdde6d7b5f4f67484b1306 to your computer and use it in GitHub Desktop.
Save nolleto/3cbac79e94cdde6d7b5f4f67484b1306 to your computer and use it in GitHub Desktop.
const getSize = matrix => ({
width: matrix[0].length,
height: matrix.length
})
const goDiagonally = (func, matrix, columnLimit) => (line, column) => {
while (line >= 0) {
matrix[line][column] = func()
line--
column++
if (column > columnLimit) break
}
}
const getEmptyMatrix = height => Array.from({ length: height }).map(_ => [])
const diagonaze = (matrix, func) => {
const { width, height } = getSize(matrix)
const newMatrix = getEmptyMatrix(height)
const lineLimit = (height - 1)
const columnLimit = (width - 1)
const goDiagonal = goDiagonally(func, newMatrix, columnLimit)
let currentLine = 0
let currentColumn = 0
goDiagonal(currentLine, currentColumn)
while (currentLine < lineLimit || currentColumn < columnLimit) {
if (currentLine < lineLimit) currentLine++
else if (currentColumn < columnLimit) currentColumn++
goDiagonal(currentLine, currentColumn)
}
return newMatrix
}
const flattern = matrix =>
matrix.reduce((acc, array) => [ ...acc, ...array ], [])
const kataMaldito = matrix => {
const string = flattern(matrix)
return diagonaze(matrix, () => string.shift())
}
export default kataMaldito
import expect from 'expect'
import kataMaldito from './diagonalKata'
expect(kataMaldito([
['c', 'h', 'a'],
['r', 'a', 'c'],
['t', 'e', 'r']
])).toEqual([
['c', 'a', 'c'],
['h', 'a', 'e'],
['r', 't', 'r']
])
expect(kataMaldito([
['J', 'A', 'V', 'A'],
['C', 'O', 'D', 'E'],
['T', 'A', 'C', 'O'],
])).toEqual([
['J', 'V', 'O', 'T'],
['A', 'C', 'E', 'C'],
['A', 'D', 'A', 'O']
])
expect(kataMaldito([
['T', 'h', 'i', 's', 'A', 'r', 'r', 'a', 'y'],
['i', 'S', 's', 'O', 'c', 'r', 'a', 'z', 'Y'],
['I', 't', 's', 'R', 'l', 'y', 'B', 'a', 'd']
])).toEqual([
['T', 'i', 'r', 'y', 's', 'r', 'Y', 's', 'y'],
['h', 'A', 'a', 'S', 'c', 'z', 't', 'l', 'a'],
['s', 'r', 'i', 'O', 'a', 'I', 'R', 'B', 'd']
])
expect(kataMaldito([
['c', 'h'],
['r', 'a'],
['t', 'e'],
['a', 'b']
])).toEqual([
['c', 'r'],
['h', 't'],
['a', 'a'],
['e', 'b']
])
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment