Skip to content

Instantly share code, notes, and snippets.

@kyleplo
Last active January 10, 2021 22:39
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 kyleplo/fb793ad9f1e50ef5b1ce1bcd61699f3e to your computer and use it in GitHub Desktop.
Save kyleplo/fb793ad9f1e50ef5b1ce1bcd61699f3e to your computer and use it in GitHub Desktop.
Dihybrid Punnet Generator written in JavaScript, because I was too bored to do it manually in biology class. Not sure if writing this saved me any time, but it works.
/*
To use, run the function where m and f are the genotypes of the parents, and c is an object of the alleles and what they do. For example:
generatePunnet("RRBb","rrbb",{"R":"running","r":"waltzing","B":"black", "b":"brown"})
will output:
R: running
r: waltzing
B: black
b: brown
rb rb rb rb
RB RBrb RBrb RBrb RBrb
Rb Rbrb Rbrb Rbrb Rbrb
Rb Rbrb Rbrb Rbrb Rbrb
RB RBrb RBrb RBrb RBrb
Genotypes: 8 RBrb, 8 Rbrb
Phenotypes:
running, black: 8
running, brown: 8
*/
function generatePunnet(m, f, c){
var al = Object.keys(c);
var p = [[], [], [], []];
var ml = [m[0] + m[2], m[0] + m[3], m[1] + m[3], m[1] + m[2]]
var fl = [f[0] + f[2], f[0] + f[3], f[1] + f[3], f[1] + f[2]]
var ph = {};
for(var x = 0; x < 4; x++){
for(var y = 0; y < 4; y++){
p[x][y] = ml[x] + fl[y];
if(ph[p[x][y]]){
ph[p[x][y]]++;
}else{
ph[p[x][y]] = 1
}
}
}
var r = "";
var spaces = " ";
for(var i = 0;i < al[0].length;i++){
spaces += " "
};
r += al[0] + ": " + c[al[0]] + "\n";
r += al[1] + ": " + c[al[1]] + "\n";
r += al[2] + ": " + c[al[2]] + "\n";
r += al[3] + ": " + c[al[3]] + "\n\n";
r += spaces + " " + fl[0] + spaces + fl[1] + spaces + fl[2] + spaces + fl[3] + spaces + "\n";
for(var x = 0;x < 4; x++){
r += ml[x] + spaces;
for(var y = 0;y < 4; y++){
r += p[x][y] + " "
}
r += "\n"
}
r += "\nGenotypes: ";
for(var o = 0;o < Object.keys(ph).length;o++){
r += ph[Object.keys(ph)[o]] + " " + Object.keys(ph)[o];
if((o + 1) < Object.keys(ph).length){
r += ", "
}
}
r += "\nPhenotypes:\n";
var ph = {};
for(var x = 0;x < 4;x++){
for(var y = 0;y < 4;y++){
var a = p[x][y];
var phe = "";
var desc = [];
if(a.indexOf(al[0]) > -1){
phe += al[0];
desc.push(c[al[0]])
}else{
phe += al[1];
desc.push(c[al[1]])
};
if(a.indexOf(al[2]) > -1){
phe += al[2];
desc.push(c[al[2]])
}else{
phe += al[3];
desc.push(c[al[3]])
};
if(ph[phe]){
ph[phe].count++;
}else{
ph[phe] = {count: 1, desc: desc}
}
}
};
var phc = Object.keys(ph);
for(var i = 0;i < phc.length;i++){
r += ph[phc[i]].desc.join(", ") + ": " + ph[phc[i]].count + "\n";
}
return r;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment