减少多个return语句并简化功能

时间:2019-05-09 06:44:44

标签: javascript performance typescript

我正在尝试将所有ordered-list-item & unordered-list-item类型归入新对象。

经过了如此多的高音之后,我提出了以下解决方案。效果很好。

但是现在的问题是代码质量。

我想简化功能并减少多个return语句。

如何简化以下功能,

下面是代码段,

请帮助

const data = {
  data: [{
    areas: [{
        sections: [{
          rjf: [{
              "type": "heading-1",
              "text": "A title",
            },
            {
              "type": "ordered-list-item",
              "text": "Ordered Item A",
            },
            {
              "type": "unordered-list-item",
              "text": "Ordered Item B",
            },
            {
              "type": "heading-1",
              "text": "A title",
            }
          ]
        }]
      },
      {
        sections: [{
          rjf: [{
              "type": "heading-1",
              "text": "Block 2 A title",
            },
            {
              "type": "ordered-list-item",
              "text": "Block 2 Ordered Item A",
            },
            {
              "type": "unordered-list-item",
              "text": "Block 2 Ordered Item B",
            },
            {
              "type": "heading-1",
              "text": "Block 2 A title",
            }
          ]
        }]
      }
    ]
  }]
};

function parseAreas() {
  data[0].areas.forEach(area => {
    this.moveToNewObject(area);
  })
}


function moveToNewObject(data) {
  const areas = data[0].areas;
  //console.log(data[0].areas)
  const listItemTypes = ['unordered-list-item', 'ordered-list-item'];
  return areas.map((area) => {
    var sec = area.sections;
    return sec.map((section) => {
      let lastHeadingIndex = -1;
      return section.rjf.reduce((acc, current, index) => {
        if (!current.type || !listItemTypes.includes(current.type)) {
          lastHeadingIndex = acc.length;
          return [...acc, current]
        } else {
          let listObject = acc.find((el, i) => i > lastHeadingIndex && i < index && el.type === 'list');
          if (!listObject) {
            listObject = {
              type: 'list',
              items: [current]
            }
            return [...acc, listObject];
          }
          listObject.items = [...listObject.items, current];
          return acc;
        }
      }, [])
    });
  });
}
console.log('sections', moveToNewObject(data.data));

0 个答案:

没有答案