Last active
November 12, 2015 17:29
-
-
Save melissamarima/2b9e8594892103dbc02c to your computer and use it in GitHub Desktop.
For my SO question http://stackoverflow.com/q/33175305/4825465
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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