객체 지향 자바스크립트를 사용하여 테이블 생성

Javascript 인터뷰에서 Object-Oriented Javascript를 사용하여 무언가를 구현해야 하는 문제가 있어서 여기서는 Table 클래스를 구현하려고 합니다.

다음은 js 코드입니다.

(function () {
  'use strict'

  // Table class
  // it will create a table from JSON array
  // create header from first array element i.e. Object
  // Sort table based on header key
  // iterate through array and insert rows
  var tData = [
    { name: "Monte Falco", height: 1658, place: "Parco Foreste Casentinesi" },
    { name: "Monte Falterona", height: 1654, place: "Parco Foreste Casentinesi" },
    { name: "Poggio Scali", height: 1520, place: "Parco Foreste Casentinesi" },
    { name: "Pratomagno", height: 1592, place: "Parco Foreste Casentinesi" },
    { name: "Monte Amiata", height: 1738, place: "Siena" }
  ];  

  const getCellValue = (tr, idx) => tr.children[idx].innerText || tr.children[idx].textContent;

  const comparer = (idx, asc) => (a, b) => ((v1, v2) => 
      v1 !== '' && v2 !== '' && !isNaN(v1) && !isNaN(v2) ? v1 - v2 : v1.toString().localeCompare(v2)
      )(getCellValue(asc ? a : b, idx), getCellValue(asc ? b : a, idx));

  function Table(Data) {
    this.tData = Data || []
    this.node = document.createElement('table')

    Table.prototype.renderTable = function(){
      this.generateTableHead(Object.keys(this.tData[0]));
      this.generateTableRows(this.tData);
    }

    Table.prototype.generateTableHead = function(headerData) {
      let thead = this.node.createTHead();
      let row = thead.insertRow();
      for (let key of headerData) {
        let th = document.createElement("th");
        let text = document.createTextNode(key);
        th.appendChild(text);
        th.addEventListener('click', (() => {
          const table = th.closest('table');
          Array.from(table.querySelectorAll('tr:nth-child(n+2)'))
              .sort(comparer(Array.from(th.parentNode.children).indexOf(th), this.asc = !this.asc))
              .forEach(tr => table.appendChild(tr) );
        }));
        row.appendChild(th);
      }
    }

    Table.prototype.generateTableRows = function(rowData){
      for (let element of rowData) {
        let row = this.node.insertRow();
        for (let key in element) {
          let cell = row.insertCell();
          let text = document.createTextNode(element[key]);
          cell.appendChild(text);
        }
      }
    }

    // todos...
    // Searching 
    // Client Side Pagination
    // Anyone wants to implement these functionality
    // pls do comment ur code  
  }

  document.body.onload = function () {
    var table = new Table(tData)
    table.renderTable();
    document.getElementById("main-container").appendChild(table.node)
  }

}())

여기 index.html이 있습니다.

<!DOCTYPE html>
<html>
<head>
</head>
<body>
  <div id="main-container"></div>
  <script type="text/javascript" src="index.js"></script>
</body>
</html>

좋은 웹페이지 즐겨찾기