Instantly share code, notes, and snippets.

@Peleke /isEnglish.js
Last active Apr 20, 2018

Embed
What would you like to do?
tryAll
'use strict'
const fs = require('fs')
// Save this list as `eng_10k.txt`: https://raw.githubusercontent.com/first20hours/google-10000-english/master/google-10000-english.txt
const _getFrequencyList = () => {
const frequencyList = fs.readFileSync(`${__dirname}/eng_10k.txt`).toString().split('\n').slice(1000)
const dict = {};
frequencyList.forEach(word => {
// Ignore weird consonant clusters
// match returns `null` if `word` contains no vowels
if (!word.match(/[aeuoi]/gi)) {
return;
}
dict[word] = word;
})
return dict;
}
const isEnglish = string => {
// Default threshold for how many English words we need before we consider the sentence "maybe English"
const threshold = 3;
if (string.split(/\s/).length < 6) {
// If this isn't a long enough sentence, be conservative: assume it's english
return true;
} else {
let count = 0;
const frequencyList = _getFrequencyList();
string.split(/\s/).forEach(function (string) {
const adjusted = string.toLowerCase().replace(/\./g, '')
if (frequencyList[adjusted]) {
count += 1;
}
})
return count > threshold;
}
}
module.exports = isEnglish;
const caesar = require('./caesar');
// Brute-force attack on Caesar's (non-)cipher
const tryAll = function (encryptedString) {
// The Caesar cipher
const decryptionAttempts = []
while (decryptionAttempts.length < 24) {
const decryptionKey = -decryptionAttempts.length;
const decryptionAttempt = caesar(encryptedString, decryptionKey);
decryptionAttempts.push(decryptionAttempt)
}
return decryptionAttempts;
};
const encryptedString = 'xt ny itjx.'
const decryptionAttempts = tryAll(encryptedString);
module.exports = tryAll;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment