Skip to content

Instantly share code, notes, and snippets.

@devenes
Last active March 29, 2022 00:06
Show Gist options
  • Save devenes/47a8c4cfc9e68adf91afbd8e507b3df6 to your computer and use it in GitHub Desktop.
Save devenes/47a8c4cfc9e68adf91afbd8e507b3df6 to your computer and use it in GitHub Desktop.
String Challenge
// - String Challenge -
// Have the function StringChallenge(str) read the str parameter being passed which
// will contain the written out version of the numbers 0 - 9
// and the words "minus" or "plus" and convert the expression into an actual final number written out as well.
// For example: if str is "foursixminustwotwoplusonezero" then this converts to "46 - 22 + 10"
// which evaluates to 34 and your program should return the final string threefour.
// If your final answer is negative it should include the word "negative."
// Examples:
// Input: "onezeropluseight"
// Output: oneeight
// Input: "oneminusoneone"
// Output: negativeonezero
function StringExpression(str) {
let newString = str.slice(0);
let dictionary = [
["zero", "0"],
["one", "1"],
["two", "2"],
["three", "3"],
["four", "4"],
["five", "5"],
["six", "6"],
["seven", "7"],
["eight", "8"],
["nine", "9"],
["minus", "-"],
["plus", "+"],
];
dictionary.forEach((val) => {
let regEx = new RegExp(val[0], "g");
newString = newString.replace(regEx, val[1]);
});
let resString = eval(newString).toString();
dictionary.slice(0, 10).forEach((val) => {
let regEx = new RegExp(val[1], "g");
resString = resString.replace(regEx, val[0]);
});
return resString.replace("-", "negative");
}
// keep this function call here
StringExpression(readline());
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment