Advertisement
Guest User

Untitled

a guest
Aug 9th, 2019
2,166
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. //Create an array which will store our results
  2. //`level` is a helper object to assist with search.
  3. //It means that the result array is considered a reference in `level.result`
  4. //so each iteration we build on top of `result`.
  5. let result = [];
  6. let level = { result };
  7.  
  8. function reducer(accumulator, currentValue) {
  9.  
  10.     debugger;
  11.  
  12.     //If we already have an entry for this in the accumulator, we can just return it
  13.     //Then, the next iteration of `currentValue` is known to be a child of this entry.
  14.     if(accumulator[currentValue]) {
  15.         return accumulator[currentValue];
  16.     }
  17.  
  18.     //Otherwise, let's add this entry and then return it, again the next iteration
  19.     //is going to be a child of this entry.
  20.     accumulator[currentValue] = {
  21.         result: []
  22.     };
  23.  
  24.     //Note: everything in the accumulator is eventually discarded - we only care about the `result` which we are
  25.     //continuously building from the ground up using references.
  26.  
  27.     let el = {
  28.         name: currentValue,
  29.         children: accumulator[currentValue].result
  30.     };
  31.  
  32.     //push the current element to `result`, which is equal to the precedening element (parents) children. (??)
  33.     accumulator.result.push(el);
  34.  
  35.     //For the next iteration, the accumulator will be set to accumulator[currentValue]
  36.     return accumulator[currentValue];
  37. };
  38.  
  39. paths.forEach(path => {
  40.     let pathParts = path.split('/');
  41.  
  42.     //The accumulator will take the initial value of `level`
  43.     pathParts.reduce(reducer, level)
  44. })
  45.  
  46. //result has been continuously built upon - using the reference in the initial `level`.
  47. console.log(result)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement