Skip to content

Instantly share code, notes, and snippets.

@RodionGork
Created May 17, 2015 06:35
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save RodionGork/42a81bc4f8d919ffd015 to your computer and use it in GitHub Desktop.
Save RodionGork/42a81bc4f8d919ffd015 to your computer and use it in GitHub Desktop.
Language detector of CodeAbbey
function LanguageDetector() {
function countCharacters(s) {
var cnt = [];
for (var i = 0; i < 256; i++) {
cnt[i] = 0;
}
for (var j = 0; j < s.length; j++) {
var c = s.charCodeAt(j);
if (c >= 0 && c < 256) {
cnt[i]++;
}
}
return cnt;
}
this.detect = function(s) {
var cnt = countCharacters(s);
var len = s.length;
var lenBf = s.replace(/[^\+\-\.\,\[\]\<\>\:\;\s]/g, '').length;
if (lenBf / (len + 1) > 0.6 && s.indexOf('#include') < 0) {
return 'Brainfuck';
}
if (s.indexOf('var ') >= 0) {
return s.indexOf('using ') >= 0 ? 'C#' : 'JavaScript';
}
if (/\bdef\b/.test(s) && /\bend\b/.test(s)) {
return 'Ruby';
}
var endLines = s.match(/[\,\;\{\}][\040\t]*[\n\r]/);
endLines = endLines !== null ? endLines.length : 0;
if (endLines / (cnt[10] + 1) > 0.4) {
if (s.indexOf('#include') >= 0) {
return 'C/C++';
}
if (/main\s*\(\s*String/.test(s)) {
return 'Java';
}
if (cnt['$'.charCodeAt(0)] / len > 0.005) {
return 'PHP';
}
return 'C#';
} else {
if (/\([\+\*]/.test(s)) {
return 'LISP';
}
if (s.indexOf('dim ') >= 0) {
return 'VB';
}
if (s.indexOf('local ') >= 0) {
return 'Lua';
}
return 'Python';
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment