Skip to content

Commit

Permalink
Code Base
Browse files Browse the repository at this point in the history
  • Loading branch information
DrxcoDev committed Jul 18, 2024
1 parent f503e11 commit 73a94c4
Showing 1 changed file with 42 additions and 0 deletions.
42 changes: 42 additions & 0 deletions src/core.js
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,8 @@ class Optimus {
this.state = {};
this.events = {}; // Objeto para almacenar los eventos registrados
this.prevState = {};
this.hooks = [];
this.hookIndex = 0;
this.init();
}

Expand All @@ -18,6 +20,20 @@ class Optimus {
}
}

useState(initialValue) {
const hookIndex = this.hookIndex++;
if (this.hooks[hookIndex] === undefined) {
this.hooks[hookIndex] = initialValue;
}

const setState = (newState) => {
this.hooks[hookIndex] = newState;
this.render();
};

return [this.hooks[hookIndex], setState];
}

setState(newState) {
try {
this.state = { ...this.state, ...newState };
Expand All @@ -27,6 +43,32 @@ class Optimus {
}
}

useEffect(callback, deps) {
const hookIndex = this.hookIndex++;
const hasNoDeps = !deps;
const hasChangedDeps = this.prevDeps
? !deps.every((dep, i) => dep === this.prevDeps[hookIndex][i])
: true;

if (hasNoDeps || hasChangedDeps) {
callback();
this.prevDeps[hookIndex] = deps;
}
}

useReducer(reducer, initialState) {
const [state, setState] = this.useState(initialState);
const dispatch = (action) => {
const newState = reducer(state, action);
setState(newState);
};
return [state, dispatch];
}

resetHooks() {
this.hookIndex = 0;
}

async render() {
try {
const root = document.querySelector(this.options.el);
Expand Down

0 comments on commit 73a94c4

Please sign in to comment.