Skip to content

Instantly share code, notes, and snippets.

@drueck
Created January 14, 2014 21:49
Show Gist options
  • Save drueck/8426483 to your computer and use it in GitHub Desktop.
Save drueck/8426483 to your computer and use it in GitHub Desktop.
var DNA_NUCLEOTIDES = ['A', 'T', 'C', 'G'];
var ALL_NUCLEOTIDES = DNA_NUCLEOTIDES.concat('U');
function initialCounts() {
return DNA_NUCLEOTIDES.reduce(function(counts, nucleotide) {
counts[nucleotide] = 0;
return counts;
}, {});
}
function countNucleotides(sequence) {
return sequence.split("").reduce(function(nucleotideCounts, nucleotide){
if (nucleotideCounts[nucleotide] >= 0) {
nucleotideCounts[nucleotide]++;
}
return nucleotideCounts;
}, initialCounts());
}
function validateNucleotide(nucleotide) {
if (ALL_NUCLEOTIDES.indexOf(nucleotide) === -1) {
throw new Error("Invalid Nucleotide");
}
}
function DNA(sequence) {
this.nucleotideCounts = countNucleotides(sequence);
}
DNA.prototype.count = function(nucleotide) {
validateNucleotide(nucleotide);
return this.nucleotideCounts[nucleotide] || 0;
};
module.exports = DNA;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment