JSFiddle - React, Tailwind, and code Playground

by joplomacedo

JavaScript

class StoreModule {
	constructor(obj) {
		this.actions = obj.actions;
		this.mutations = obj.mutations;
		this.getters = obj.getters;
		this.state = obj.state;
	}

	do(methodType, methodName, ...args) {
		const method = this[methodType][methodName];

		return method.call(
			this,
			{
				state: this.state,
				commit: this.commit.bind(this),
				get: this.get.bind(this),
				dispatch: this.dispatch.bind(this)
			},
			...args
		);
	}

	dispatch(actionName, ...args) {
		return this.do("actions", actionName, ...args);
	}

	commit(mutationName, ...args) {
		return this.do("mutations", mutationName, ...args);
	}

	get(getterName, ...args) {
		return this.do("getters", getterName, ...args);
	}
};


const createStore = storeModulesDescriptors => {
    const storeModulesNames = Object.keys(storeModulesDescriptors);
    const storeModules = {};

    storeModulesNames.forEach(name => {
        const descriptor = storeModulesDescriptors[name];
        const modul = new StoreModule(descriptor);
        storeModules[name] = modul;
    });

    return {
        ...storeModules,

        dispatch(moduleAndActionNames, ...args) {
            const [ moduleName, actionName ] = moduleAndActionNames.split('.');
            const modl = storeModules[moduleName];
            return modl.dispatch(actionName, ...args);
        },
        commit(moduleAndMutationNames, ...args) {
            const [ moduleName, mutationName ] = moduleAndMutationNames.split('.');
            const modl = storeModules[moduleName];
            return modl.commit(mutationName, ...args);
        },
        get(moduleAndGetterNames, ...args) {
            const [ moduleName, getterName ] = moduleAndGetterNames.split('.');
            const modl = storeModules[moduleName];
            return modl.get(getterName, ...args);
        },
    }
}


const store = createStore({
		tags: {
			state: {
				a: 5
			},
			mutations: {
				incABy({ state }, amount) {
					state.a += amount;
				}
			},
			actions:...