How can I change this JavaScript code to a function?

How can I change this JavaScript code to a function?

Hi,

Could someone please help me to change this JavaScript code snippet to a function?

  1. <script>
  2. var headertext = [],
  3. headers = document.querySelectorAll("#responsiveTable th"),
  4. tablerows = document.querySelectorAll("#responsiveTable th"),
  5. tablebody = document.querySelector("#responsiveTable tbody");

  6. for(var i = 0; i < headers.length; i++) {
  7.   var current = headers[i];
  8.   headertext.push(current.textContent.replace(/\r?\n|\r/,""));
  9. }
  10. for (var i = 0, row; row = tablebody.rows[i]; i++) {
  11.   for (var j = 0, col; col = row.cells[j]; j++) {
  12.     col.setAttribute("data-th", headertext[j]);
  13.   }
  14. }
  15. </script>