Created
May 1, 2017 23:00
-
-
Save the-vampiire/fa2591b07113aaa791817419c40f8dfa to your computer and use it in GitHub Desktop.
Inventory Update Advanced Algorithm
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
| // I am a fucking savage. | |
| function updateInventory(arr1, arr2){ | |
| var merged = arr1.concat(arr2); | |
| var JSON_merged = {}; | |
| // utilizes fact that objects can not have repeating properties with the same name | |
| // to filter out duplicates | |
| // will retain the last seen duplicate element during loop | |
| // newInv.concat(curInv) retains current inventory duplicate item and item count | |
| // curInv.concat(newInv) retains new inventory duplicate item and item count | |
| for(var i in merged){ | |
| JSON_merged[merged[i][1]] = merged[i][0]; | |
| } | |
| // once the list is merged loop through the original inventory and the new duplicate-filtered | |
| // JSON_merged object. For each matching pair check if the JSON_merged value is the same | |
| // as the curInv item count. If it is the same then skip it, if they are different then | |
| // update the count by adding the new count stored in the JSON_merged object | |
| // and the old count stored in the curInv array | |
| for(i in arr1){ | |
| for(var j in JSON_merged){ | |
| if(arr1[i][1] === j){ | |
| if(arr1[i][0] !== JSON_merged[arr1[i][1]]){ | |
| JSON_merged[arr1[i][1]] = JSON_merged[arr1[i][1]] + arr1[i][0]; | |
| } | |
| } | |
| } | |
| } | |
| merged = []; // clear merged array to push duplicate-filtered elements back into it | |
| // push object properties into array in original format | |
| // original format: [item count, 'item'] | |
| for(var prop in JSON_merged){ | |
| if(JSON_merged.hasOwnProperty(prop)){ | |
| merged.push([JSON_merged[prop], prop]); | |
| } | |
| } | |
| // sorting alphabetically based on item name, arr[x][1] | |
| function sorting_hat(a,b){ | |
| return a[1].localeCompare(b[1]); | |
| } | |
| return merged.sort(sorting_hat); | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment