denmardiyana

data books

Jun 21st, 2021 (edited)
173
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. const STORAGE_KEY = "BOOK_APPS";
  2.  
  3. let books = [];
  4.  
  5. function isStorageExist() /* boolean */  {
  6.    if(typeof(Storage) === undefined){
  7.        alert("Browser kamu tidak mendukung local storage");
  8.        return false
  9.    }
  10.    return true;
  11. }
  12. function saveData() {
  13.    const parsed = JSON.stringify(books);
  14.    localStorage.setItem(STORAGE_KEY, parsed);
  15.    document.dispatchEvent(new Event("ondatasaved"));
  16. }
  17.  
  18. function loadDataFromStorage() {
  19.    const serializedData = localStorage.getItem(STORAGE_KEY);
  20.    
  21.    let data = JSON.parse(serializedData);
  22.    
  23.    if(data !== null)
  24.        books = data;
  25.  
  26.    document.dispatchEvent(new Event("ondataloaded"));
  27. }
  28.  
  29. function updateDataToStorage() {
  30.    if(isStorageExist())
  31.        saveData();
  32. }
  33.  
  34. function composeBookObject(title, author, year, isCompleted) {
  35.    return {
  36.        id: +new Date(),
  37.        title,
  38.        author,
  39.        year,
  40.        isCompleted
  41.    };
  42. }
  43.  
  44. function findBook(bookId) {
  45.    for(book of books){
  46.        if(book.id === bookId)
  47.            return book;
  48.    }
  49.    return null;
  50. }
  51.  
  52.  
  53. function findBookIndex(bookId) {
  54.    let index = 0
  55.    for (book of books) {
  56.        if(book.id === bookId)
  57.            return index;
  58.  
  59.        index++;
  60.    }
  61.  
  62.    return -1;
  63. }
  64.  function refreshDataFromBooks() {
  65.     const listUncompleted = document.getElementById(UNCOMPLETED_LIST_BOOK_ID);
  66.     let listCompleted = document.getElementById(COMPLETED_LIST_BOOK_ID);
  67.  
  68.  
  69.     for(book of books){
  70.         const newBook = makeBook(book.title, book.author, book.year, book.isCompleted);
  71.         newBook[BOOK_ITEMID] = book.id;
  72.  
  73.  
  74.         if(book.isCompleted){
  75.             listCompleted.append(newBook);
  76.         } else {
  77.             listUncompleted.append(newBook);
  78.         }
  79.     }
  80.  }
Add Comment
Please, Sign In to add comment