pronounceability
Version:
Calculate pronounceability for a given word.
122 lines (121 loc) • 4.06 kB
JavaScript
;
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.Pronounceable = void 0;
const tuples_json_1 = __importDefault(require("./data/tuples.json"));
const triples_json_1 = __importDefault(require("./data/triples.json"));
const tuples = tuples_json_1.default;
const triples = triples_json_1.default;
class Pronounceable {
hasVowels(word) {
return word.search(/[aeiouy]/) >= 0;
}
clean(word) {
return word.replace(/[^a-zA-Z]/g, '').toLowerCase();
}
percent(score, count) {
return (score / count) * 100;
}
trainTuples(words) {
const probability = {};
let count = 0;
for (let word of words) {
word = this.clean(word);
for (let i = 0; i < word.length - 1; i++) {
const cc = word[i];
const nc = word[i + 1];
if (!probability[cc]) {
probability[cc] = {};
}
if (!probability[cc][nc]) {
probability[cc][nc] = 1;
}
else {
probability[cc][nc]++;
}
count++;
}
}
for (const first of Object.keys(probability)) {
for (const second of Object.keys(probability[first])) {
probability[first][second] = this.percent(probability[first][second], count);
}
}
return probability;
}
trainTriples(words) {
const probability = {};
let count = 0;
for (let word of words) {
word = this.clean(word);
for (let i = 0; i < word.length - 2; i++) {
const cc = word[i];
const nc = word[i + 1];
const nnc = word[i + 2];
if (!probability[cc]) {
probability[cc] = {};
}
if (!probability[cc][nc]) {
probability[cc][nc] = {};
}
if (!probability[cc][nc][nnc]) {
probability[cc][nc][nnc] = 1;
}
else {
probability[cc][nc][nnc]++;
}
count++;
}
}
for (const first of Object.keys(probability)) {
for (const second of Object.keys(probability[first])) {
for (const third of Object.keys(probability[first][second])) {
probability[first][second][third] = this.percent(probability[first][second][third], count);
}
}
}
return probability;
}
score(word) {
word = this.clean(word);
let score = 0;
if (!this.hasVowels(word)) {
return 0;
}
switch (word.length) {
case 1:
return 1;
case 2:
for (let i = 0; i < word.length - 1; i++) {
const cc = word[i];
const nc = word[i + 1];
if (tuples[cc] && tuples[cc][nc]) {
score += tuples[cc][nc];
}
else {
score -= 1;
}
}
break;
default:
for (let i = 0; i < word.length - 2; i++) {
const cc = word[i];
const nc = word[i + 1];
const nnc = word[i + 2];
if (triples[cc] && triples[cc][nc] && triples[cc][nc][nnc]) {
score += triples[cc][nc][nnc];
}
else {
score -= 1;
}
}
}
if (word.length > 3) {
score /= word.length;
}
return score;
}
}
exports.Pronounceable = Pronounceable;