kbrsh/moon

How to apply DRY principles in example code

ray-delossantos opened this issue · 3 comments

In the examples for the main website there's the TODO App. How can one use DRY principles for removing the duplicated code?

//Duplicated Code:

return {
		data: dataNew,
		view: (<Todos data={dataNew}/>)
	};
const updateTodo = ({ data, view }) => {
	const dataNew = {
		...data,
		todo: view.target.value
	};

	return {
		data: dataNew,
		view: (<Todos data={dataNew}/>)
	};
};

const createTodo = ({ data }) => {
	const dataNew = {
		todo: "",
		todos: [...data.todos, data.todo]
	};

	return {
		data: dataNew,
		view: (<Todos data={dataNew}/>)
	};
};

const removeTodo = index => ({ data }) => {
	const dataNew = {
		...data,
		todos: data.todos.filter(
			(todo, todoIndex) =>
				todoIndex !== index
		)
	};

	return {
		data: dataNew,
		view: (<Todos data={dataNew}/>)
	};
};

const Todos = ({ data }) => (
	<div>
		<h1>Todos</h1>
		<input
			type="text"
			placeholder="What needs to be done?"
			value={data.todo}
			@input={updateTodo}
		/>
		<button @click={createTodo}>Create</button>
		<for={todo, index}
			of={data.todos}
			name="ul"
		>
			<li @click={removeTodo(index)}>
				{todo}
			</li>
		</for>
	</div>
);

Moon.use({
	data: Moon.data.driver({
		todo: "",
		todos: [
			"Learn Moon",
			"Take a nap",
			"Go shopping"
		]
	}),
	view: Moon.view.driver("#root")
});

Moon.run(({ data }) => ({
	view: (<Todos data={data}/>)
}));

https://kbrsh.github.io/moon/play

kbrsh commented

You can make a function that returns both new data and a new view, like this:

const updateData = dataNew => ({
	data: dataNew,
	view: (<Todos data={dataNew}/>)
});

const updateTodo = ({ data, view }) => updateData({
  	...data,
	todo: view.target.value
});

const createTodo = ({ data, view }) => updateData({
	todo: "",
	todos: [...data.todos, data.todo]
});

const removeTodo = index => ({ data, view }) => updateData({
	...data,
	todos: data.todos.filter(
		(todo, todoIndex) =>
			todoIndex !== index
		)
});

Example

Nice, thanks for the info. I thought you had some shortcuts utility functions for this kind of repetitive code.

kbrsh commented

No problem. Utility functions for things like this usually end up being too specific. For example, this wouldn't really work if you were using more drivers (such as time or the new http driver). I would just encourage using the standard functional programming technique to stay DRY — creating functions!