Skip to content

Instantly share code, notes, and snippets.

@melissamarima
Last active November 12, 2015 17:29
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 melissamarima/2b9e8594892103dbc02c to your computer and use it in GitHub Desktop.
Save melissamarima/2b9e8594892103dbc02c to your computer and use it in GitHub Desktop.
// collectionA and collectionB are arrays of Doc objects
collectionA = [];
collectionB = [];
addToCollectionB: function (newField1, newField2){
var newDocB = new Doc(newField, newField2);
// 1. If collection A is empty, push newDocB onto collection B, and stop
if (collectionA.length == 0){
collectionB.push(newDocB);
return; // ends addToCollectionB()
}
// 2. Get the current collection A's first element
var docA = collectionA[0];
// 3. check loop condition
while (docA.field2 > 0){
// 4. check which of the two ways to modify newDocB
if ( docA.field1 > 0 ){
// 5. one way removes docA from collectionA
newDocB.field1 -= docA.field1;
collectionA.splice(0,1);
} else {
// 6. the other way breaks out of the loop
newDocB.field1 = 0;
break; // break out of the while loop
}
// 7. if collectionA is empty, break out of the loop
if (collectionA.length == 0){
break;
}
// 8. loads the new docA and continues to the next loop
docA = collectionA[0];
}
// 9. Loop is done, check if newDocB needs to be saved
if (newDocB.field1 >= 0) {
collectionB.push(newDocB);
return; // ends addToCollectionB()
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment