Created
May 9, 2019 04:57
-
-
Save ProfAvery/d050d90d4bf5ac676d45d92205bae4ba to your computer and use it in GitHub Desktop.
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
let fractionCodes = { | |
189: "1/2", | |
8531: "1/3", | |
8532: "2/3", | |
188: "1/4", | |
190: "3/4", | |
8533: "1/5" | |
}; //fill in the rest from unicodefractions.com | |
function removeFractions(s) { | |
for (let [code, str] of Object.entries(fractionCodes)) { | |
let c = String.fromCharCode(code); | |
s = s.replace(c, str); | |
} | |
return s; | |
} | |
let s1 = " ¾ a pinch of ⅓ a lemon"; | |
let s2 = "This doesn't start with a number"; | |
let s3 = "1 1/2 cups stuff"; | |
s1 = removeFractions(s1); | |
s2 = removeFractions(s2); | |
s3 = removeFractions(s3); | |
console.log(s1); | |
console.log(s2); | |
console.log(s3); | |
const FRAC_RE = /^\s*(\d+)?\s+(\d+)\s*\/\s*(\d+)\s+/; | |
console.log(FRAC_RE.exec(s1)); | |
console.log(FRAC_RE.exec(s2)); | |
console.log(FRAC_RE.exec(s3)); | |
function convertFractions(s) { | |
let result = FRAC_RE.exec(s); | |
if (result) { | |
let match = result[0]; | |
let whole = result[1]; | |
let numerator = result[2]; | |
let denominator = result[3]; | |
let decimal = Number(whole) || 0; | |
decimal += numerator / denominator; | |
return s.replace(match, `${decimal} `); | |
} else { | |
return s; | |
} | |
} | |
s1 = convertFractions(s1); | |
s2 = convertFractions(s2); | |
s3 = convertFractions(s3); | |
console.log(s1); | |
console.log(s2); | |
console.log(s3); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
:)