Created
February 1, 2023 16:21
-
-
Save daftAnorak/d527a8d9622a7bde78d1e87c7751a4b0 to your computer and use it in GitHub Desktop.
Coding Exercise for JS position
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const tilePoints = { | |
a: 10, | |
b: 5, | |
c: 2, | |
t: 1, | |
// TODO - add more tile points for different letters | |
_: 0, | |
}; | |
/** | |
* Returns the amount of points given for a term if it is | |
* contained within a given set a tiles. Otherwise, will return error | |
* if it is NOT contained in | |
* | |
* @param {string} term - search term being used | |
* @param {string[]} tiles - given tiles for user | |
* | |
* @returns {number} tile points for term if contained in tiles or ERROR | |
*/ | |
function tilePointsWithTerm(term, tiles) { | |
// create simple count-map of available tiles | |
const tilesCount = tiles.reduce((countObj, tile) => { | |
countObj[tile] = (countObj[tile] || 0) + 1; | |
return countObj; | |
}, {}); | |
// return the total points of term (or ERROR) with available count-map | |
return term | |
.split('') | |
.reduce((finalPoints, char) => { | |
const takeChar = tilesCount[char] ? char : | |
tilesCount['_'] ? '_' : | |
'END'; | |
if (takeChar === 'END') throw Error('NOT POSSIBLE!'); | |
finalPoints += tilePoints[takeChar]; | |
tilesCount[takeChar] = tilesCount[takeChar] - 1; | |
return finalPoints; | |
}, 0); | |
} | |
/** | |
* Returns the term with the highest amount of points, or UNDEFINED if | |
* no term exists within the given tiles | |
* | |
* @param {string[]} terms | |
* @param {string[]} tiles | |
* | |
* @returns {string|undefined} term within tiles with higest values (points) | |
*/ | |
function bestTermWithTiles(terms, tiles) { | |
return terms | |
.flatMap(term => { | |
try { | |
return [[term, tilePointsWithTerm(term, tiles)]]; | |
} catch (e) { | |
return []; | |
} | |
}) | |
.sort((a, b) => b[1] - a[1])[0]?.[0]; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment