Advertisement
Dwitio

storage.js

Jan 25th, 2022
641
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. const CACHE_KEY = "calculation_history";
  2.  
  3. function checkForStorage() {
  4.     return typeof(Storage) !== "undefined"
  5. }
  6.  
  7. function putHistory(data) {
  8.     if (checkForStorage()) {
  9.         let historyData = null,
  10.         if (localStorage.getItem(CACHE_KEY) === null) {
  11.             historyData = [];
  12.         } else {
  13.             historyData = JSON.parse(localStorage.getItem(CACHE_KEY));
  14.         }
  15.  
  16.         historyData.unshift(data);
  17.  
  18.         if (historyData.length > 5) {
  19.             historyData.pop();
  20.         }
  21.  
  22.         localStorage.setItem(CACHE_KEY, JSON.stringify(historyData));
  23.     }
  24. }
  25.  
  26. function showHistory() {
  27.     if (checkForStorage()) {
  28.         return JSON.parse(localStorage.getItem(CACHE_KEY)) || [];
  29.     } else {
  30.         return [];
  31.     }
  32. }
  33.  
  34. function renderHistory() {
  35.     const historyData = showHistory();
  36.     let historyList = document.querySelector("#historyList");
  37.  
  38.     // Hapus kontent HTML pada historylist biar tidak menampilkan data ganda
  39.     historyList.innerHTML = "";
  40.  
  41.     for (let history of historyData) {
  42.         let row = document.createElement('tr');
  43.         row.innerHTML = "<td>" + history.firstNumber + "</td>";
  44.         row.innerHTML += "<td>" + history.operator + "</td>";
  45.         row.innerHTML += "<td>" + history.secondNumber + "</td>";
  46.         row.innerHTML += "<td>" + history.result + "</td>";
  47.  
  48.         historyList.appendChild(row);
  49.     }
  50. }
  51.  
  52. renderHistory();
Advertisement
Advertisement
Advertisement
RAW Paste Data Copied
Advertisement