Browse Source

Bringing back the mapValues logic cause I think it's cleaner

Kirk Trombley 5 years ago
parent
commit
0a3222a463
1 changed files with 7 additions and 6 deletions
  1. 7 6
      client/src/store.js

+ 7 - 6
client/src/store.js

@@ -2,11 +2,11 @@ import { useState, useEffect } from "react";
 
 const shallowEq = (x, y) => x === y;
 
+const mapValues = (obj, fn) => Object.fromEntries(Object.entries(obj).map(([key, val]) => [key, fn(val)]))
+
 export const createStore = (initial, actions = {}) => {
   const store = {};
   const hooks = {};
-  const dispatch = {};
-  const selector = {};
   Object.entries(initial).forEach(([key, value]) => {
     let _val = value;
     let _listeners = [];
@@ -36,9 +36,10 @@ export const createStore = (initial, actions = {}) => {
     const hookName = "use" + key.charAt(0).toUpperCase() + key.slice(1);
     hooks[hookName] = useValue;
   });
-  Object.entries(actions).forEach(([name, act]) => {
-    dispatch[name] = (...args) => Object.entries(act(...args)).forEach(([key, newValue]) => store[key]?._set(newValue))
-  });
-  Object.entries(store).forEach(([key, obs]) => { selector[key] = obs._get });
+
+  const dispatch = mapValues(actions, act => (...args) => Object.entries(act(...args)).forEach(([key, newValue]) => store[key]?._set(newValue)));
+
+  const selector = mapValues(store, obs => obs._get);
+
   return [hooks, dispatch, selector];
 }