aceDavon/todo-list

JavaScript best practices : DRY, KISS, YAGNI

Opened this issue · 0 comments

Personal review ✍️

I have gone through my code base and found the following issues:

Action.js

  • const local = JSON.parse(localStorage.getItem('todo'));
    const arr = [];
    local.forEach((item) => {
    const newId = { ...item, id: arr.length + 1 };
    arr.push(newId);
    localStorage.setItem('todo', JSON.stringify(arr));
    });
    };
    const Complete = (id) => {
    const local = JSON.parse(localStorage.getItem('todo'));
    local.forEach((item) => {
    if (item.id == id) {
    if (!item.completed) {
    item.completed = !item.completed;
    }
    }
    localStorage.setItem('todo', JSON.stringify(local));
    });
    };
    export const Remove = (e, id) => {
    const local = JSON.parse(localStorage.getItem('todo'));
  • There were many repetitions of the local storage instance, I could define the variable globally and call it at the points I needed it.

Controller.js

  • const local = JSON.parse(localStorage.getItem('todo'));
    if (local === null) {
    localStorage.setItem('todo', JSON.stringify(data));
    } else {
    data.map((x, i) => {
    x.id = i + 1;
    local.push(x);
    });
    localStorage.setItem('todo', JSON.stringify(data));
    document.location.reload();
    }
    };
    const Create = () => {
    const inputValue = document.getElementById('addNew');
    const btn = document.getElementById('submit');
    let arr = JSON.parse(localStorage.getItem('todo'));
    btn.addEventListener('click', () => {
    const obj = {};
    obj.completed = false;
    obj.description = inputValue.value;
    obj.id = arr !== null && arr.length + 1;
    if (arr !== null) {
    arr.push(obj);
    } else {
    arr = [obj];
    }
    saveLocal(arr);
    window.location.reload();
    });
    };
    const Read = ({
    styles, kebab, parent, child,
    }) => {
    if (local) {
    for (let i = 0; i <= local.length - 1; i++) {
    const tasks = local[i];
    const others = [styles, tasks, kebab];
    Appendage(parent, child, others);
    }
    } else {
    styles = 'empty';
    InitialState({ styles, parent, child });
    }
    };
    const Update = (id) => {
    const data = JSON.parse(localStorage.getItem('todo'));
  • Redefined a global variable multiple times for the same purpose, I should remove the local declarations and call the global declaration at the points I need them since I don't get to mutate the value of the variable at any point.

These issues can be said to make the code not DRY, and have lots of variables I do not need. They also make the code base quite not simple as the redeclared variable can become so hard to keep track of.