Skip to content

Instantly share code, notes, and snippets.

@jameswomack
Last active August 29, 2015 13:59
Show Gist options
  • Save jameswomack/10616633 to your computer and use it in GitHub Desktop.
Save jameswomack/10616633 to your computer and use it in GitHub Desktop.
Right & Wrong: Loop recursion
function Students(classroom){
this.relationships = {};
this.reverseSearchMap = {};
this.students = classroom.students;
}
Students.prototype.populate = function(){
for(var index = 0; index < this.students.length; index++){
var student = students[index];
var studentName = this.fullNameForStudent(student);
relationships[studentName] = [];
this.addOthersToStudentWithName(studentName);
}
};
Students.prototype.fullNameForStudent = function(student){
return student.firstName.concat(' ', student.lastName);
};
Students.prototype.addOthersToStudentWithName = function(studentName){
for(var index = 0; index < this.students.length; index++){
var otherStudentName = this.fullNameForStudent(this.students[index]);
if(otherStudentName.is(studentName))
relationships[studentName].push(otherStudentName);
var name = Array.prototype.slice.call(otherStudentName);
addNameToInitials(studentName, name);
}
};
Students.prototype.addNameToInitials = function(studentName, name){
for(var index = 0; index < name.length; index++){
var otherStudentInitial = name[index];
this.reverseSearchMap[otherStudentInitial] = this.reverseSearchMap[otherStudentInitial] || [];
this.reverseSearchMap[otherStudentInitial].push(studentName);
}
}
var students = new Students({
title: 'Foo Classroom',
students: ['Ryan', 'Shane', 'Ana', 'Junnan', 'Hayley']
});
students.populate();
/* Wrong */
function uniqueRelationshipsFromClassroom(classroom) {
var relationships = {};
var reverseSearchMap = {};
var students = classroom.students;
for(var i = 0; i < students.length; i++){
var student = students[i];
var studentName = student.firstName.concat(' ', student.lastName);
relationships[studentName] = [];
for(var j = 0; j < students.length; j++){
var otherStudent = students[j];
var otherStudentName = otherStudent.firstName.concat(' ', otherStudent.lastName);
var shouldAdd = otherStudentName.is(studentName);
shouldAdd && (relationships[studentName].push(otherStudentName));
var name = Array.prototype.slice.call(otherStudentName);
for(var k = 0; k < name.length; k++){
var otherStudentInitial = name[k];
reverseSearchMap[otherStudentInitial] = otherStudentInitial || [];
reverseSearchMap[otherStudentInitial].push(studentName);
}
}
}
}
var classroom = {
title: 'Foo Classroom',
students: ['Ryan', 'Shane', 'Ana', 'Junnan', 'Hayley']
};
uniqueRelationshipsFromClassroom(classroom);
@jameswomack
Copy link
Author

One is longer, but it's much easier to determine what level you're at, and isolate your analyzation to a specific area of code.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment