Last active
December 30, 2023 02:21
-
-
Save PatrickJS/55f89079a279411d49a17b581a4c4bb2 to your computer and use it in GitHub Desktop.
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
| let data = Array.from({ length: 10 }, (_, i) => `item${i + 1}`); | |
| let packageNameCounter = 0; | |
| // Function to group array elements into packages | |
| function groupArrayElements(list, groupSize) { | |
| // Base case: if the list is small enough, return it as a single package | |
| if (list.length <= groupSize) { | |
| return [{ | |
| packageName: 'Pkg' + packageNameCounter++, | |
| items: list | |
| }]; | |
| } | |
| let groupedPackages = []; | |
| // Split the list into smaller groups, each becoming a package | |
| while (list.length > 0) { | |
| let slice = list.splice(0, groupSize); | |
| groupedPackages.push({ | |
| packageName: 'Pkg' + packageNameCounter++, | |
| items: slice | |
| }); | |
| } | |
| // Recursive case: Group packages further if they exceed the group size | |
| if (groupedPackages.length > groupSize) { | |
| return groupArrayElements(groupedPackages, groupSize); | |
| } | |
| return groupedPackages; | |
| } | |
| let packageData = groupArrayElements(data, 2); |
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
| // Helper function to walk through the package tree | |
| function walkPackageTree(packageTree, callback) { | |
| packageTree.forEach(pkg => { | |
| // Execute the callback on the current package | |
| callback(pkg); | |
| // If the package has items that are themselves packages, recursively walk through them | |
| if (pkg.items && pkg.items[0] && pkg.items[0].packageName) { | |
| walkPackageTree(pkg.items, callback); | |
| } | |
| }); | |
| } | |
| // Example usage: Print package names | |
| walkPackageTree(packageData, (pkg) => { | |
| console.log('Package Name:', pkg.packageName); | |
| }); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment