find ajdacent letters

Benchmark created on


Setup

const boxes = [
    ['A', 'B', 'C', 'D'],
    ['E', 'F', 'G', 'H'],
    ['I', 'J', 'K', 'L'],
    ['M', 'N', 'O', 'P']
]

const findLetterPosition = (letter) => {
    // eslint-disable-next-line no-loops/no-loops
    for (const [rowIndex, row] of boxes.entries()) {
        const letterIndex = row.indexOf(letter)

        if (letterIndex === -1) {
            continue
        }

        return { rowIndex, letterIndex }
    }

    return null
}

const getAdjacentLetters = (letter) => {
    const position = findLetterPosition(letter)

    if (!position) {
        return []
    }

    const upperRowIndex = (position.rowIndex - 1)
    const lowerRowIndex = (position.rowIndex + 1)

    const adjacentPositions = [
        [upperRowIndex, position.letterIndex - 1],
        [upperRowIndex, position.letterIndex],
        [upperRowIndex, position.letterIndex + 1],

        [position.rowIndex, position.letterIndex - 1],
        [-1, -1],
        [position.rowIndex, position.letterIndex + 1],

        [lowerRowIndex, position.letterIndex - 1],
        [lowerRowIndex, position.letterIndex],
        [lowerRowIndex, position.letterIndex + 1],
    ]

    return adjacentPositions.reduce((letters, position) => {
        const [rowIndex, letterIndex] = position

        if (rowIndex === -1 || letterIndex === -1) {
            return letters
        }

        const row = boxes[rowIndex]

        if (!row) {
            return letters
        }

        const letter = row[letterIndex]

        if (!letter) {
            return letters
        }

        return [...letters, letter]
    }, [])
}

Test runner

Ready to run.

Testing in
TestOps/sec
getAdjacentLetters('F')
getAdjacentLetters('F')
ready
getAdjacentLetters('M')
getAdjacentLetters('M')
ready

Revisions

You can edit these tests or add more tests to this page by appending /edit to the URL.