JSFiddle - React, Tailwind, and code Playground

by rexonms

JavaScript

// Grid width = 5
/*

a b c d e 
f g h i j
k l m n o
p q r s t
u v w x y
z

title = up
Movements represented by 'u', 'd', 'l', 'r'
return 'dddd!u!'

*/
    console.clear()

const convertCharToIndex = (char) => char.charCodeAt(0) - 97
const convertIndexToChar = (index) => String.fromCharCode(97 + index)
const direction = {
	down: 'd',
  up: 'u',
  left: 'l',
  right: 'r',
}

const findTitle = (gridWidth, title) => {
	const titleArr = title.split('')
	const chars = titleArr.map(item => convertCharToIndex(item))
  let currentPosition = 0
  let destination
  let toReturn=''
  
  chars.map(char => {
  	const destination = char - currentPosition
    const row = Math.floor(destination/gridWidth)
    const col = destination%gridWidth
		  
    if(row > 0) {
    	 for(var i = 0; i < row; i ++) {
    		toReturn = toReturn.concat('', direction.down)
    	}
    } else {
    for(var i = row; i < 0; i++) {
    		toReturn = toReturn.concat('', direction.up)
    	}
    }  
    
     if(col > 0) {
    	 for(var i = 0; i < col; i ++) {
    		toReturn = toReturn.concat('', direction.right)
    	}
    } else {
    for(var i = col; i < 0; i++) {
    		toReturn = toReturn.concat('', direction.left)
    	}
    }  
    
    toReturn = toReturn.concat('','!')
    currentPosition = char
  })
  return toReturn
}

console.log(findTitle(5, 'up'), 'dddd!u!')
console.log(findTitle(5, 'down'), 'rrr!ddr!ddll!')