environmnets_store.js.es6 1.92 KB
Newer Older
1 2 3 4 5
(() => {
  window.gl = window.gl || {};
  window.gl.environmentsList = window.gl.environmentsList || {};
  
  gl.environmentsList.EnvironmentsStore = {
6
    state: {},
7 8
    
    create () {
9
      this.state.environments = [];
10 11 12
    },
    
    /**
13 14 15
     * In order to display a tree view we need to modify the received 
     * data in to a tree structure based on `environment_type` 
     * sorted alphabetically.
16
     * 
17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33
     * @example
     * it will transform this:
     * [
     *   { name: "environment", environment_type: "review" },
     *   { name: "environment_1", environment_type: null }
     *   { name: "environment_2, environment_type: "review" }
     * ]
     * into this:
     * [
     *   { name: "review", children: 
     *      [
     *        { name: "environment", environment_type: "review"},
     *        { name: "environment_2", environment_type: "review"}
     *      ]
     *   },
     *  {name: "environment_1", environment_type: null}
     * ]
Filipa Lacerda's avatar
Filipa Lacerda committed
34 35 36 37
     * 
     * 
     * @param  {Array} environments List of environments.
     * @returns {Array} Tree structured array with the received environments.
38 39
     */
    storeEnvironments(environments) {
Filipa Lacerda's avatar
Filipa Lacerda committed
40
      const environmentsTree = environments.reduce((acc, environment) => {
41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60
        if (environment.environment_type !== null) {
          const occurs = acc.find((element, index, array) => {
            return element.name === environment.environment_type;
          });

          if (occurs !== undefined) {
            acc[acc.indexOf(occurs)].children.push(environment);
            acc[acc.indexOf(occurs)].children.sort();
          } else {
            acc.push({
              name: environment.environment_type,
              children: [environment]
            });
          }
        } else {
          acc.push(environment);
        }

        return acc;
      }, []).sort();
Filipa Lacerda's avatar
Filipa Lacerda committed
61 62 63 64
    
      this.state.environments = environmentsTree;
      
      return environmentsTree;
65
    }
66
  }
67
})();