Skip to content

Instantly share code, notes, and snippets.

@matthewd673
Last active November 20, 2021 03:35
Show Gist options
  • Save matthewd673/8f183f4007535339884f6203f87cd378 to your computer and use it in GitHub Desktop.
Save matthewd673/8f183f4007535339884f6203f87cd378 to your computer and use it in GitHub Desktop.
Check if two words rhyme
//download dictionary from https://svn.code.sf.net/p/cmusphinx/code/trunk/cmudict/cmudict.0.7a
//dictionary format: ['RHYME', 'R AY1 M']
const rhymeDict = [];
//despite the size of the file, this parses reasonably quickly
function populateRhymeDict() {
fetch('cmudict.0.7a.txt')
.then(response => response.text())
.then(data => {
dictLines = data.split('\n');
for (let i = 55; i < dictLines.length; i++) {
let content = dictLines[i].split(' ');
rhymeDict[content[0]] = content[1];
}
dictReady = true;
});
}
function arraySegmentsEqual(arr1, arr2, i1, i2) {
if (arr1.length - i1 != arr2.length - i2) { return false; } //must have same amount
for (let i = 0; i < arr1.length - i1; i++) {
if (arr1[i1 + i] !== arr2[i2 + i]) { return false; }
}
return true;
}
function checkRhyme(a, b) {
let phonA = rhymeDict[a.toUpperCase()];
let phonB = rhymeDict[b.toUpperCase()];
if (phonA == undefined || phonB == undefined) { return false; }
//find first point of emphasis
let syllA = phonA.split(' ');
let syllB = phonB.split(' ');
let emphIndexA = -1;
let emphIndexB = -1;
for (let i = 0; i < syllA.length; i++) {
if (syllA[i].indexOf('1') > -1) { emphIndexA = i; break; }
}
for (let i = 0; i < syllB.length; i++) {
if (syllB[i].indexOf('1') > -1) { emphIndexB = i; break; }
}
if (arraySegmentsEqual(syllA, syllB, emphIndexA, emphIndexB)) { return true; }
return false;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment