Skip to content

Instantly share code, notes, and snippets.

@MikeBild
Created November 10, 2016 10:26
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save MikeBild/ad011e8cdb09c015ee91dcdc136b58b1 to your computer and use it in GitHub Desktop.
Save MikeBild/ad011e8cdb09c015ee91dcdc136b58b1 to your computer and use it in GitHub Desktop.
Q&A - I wanna understand TypeScript - Part TypeScript Union Types as Redux Action Tags
// demonstrate
const simulateActions = [
addTodo({text: 'todo 1'}),
addTodo({text: 'todo 2'}),
toggleTodo({index: 0}),
toggleTodo({index: 1}),
];
const actual = simulateActions.reduce(todosReducer, []);
console.log(actual);
// https://blog.mariusschulz.com/2016/11/03/typescript-2-0-tagged-union-types
const ADD_TODO = 'ADD_TODO';
const TOGGLE_TODO = 'TOOGLE_TODO';
const todo = (type, payload) => ({type, payload});
const addTodo = payload => todo(ADD_TODO, payload);
const toggleTodo = payload => todo(TOGGLE_TODO, payload);
const todosReducer = (state, action) => {
switch (action.type) {
case ADD_TODO:
return [...state, { text: action.payload.text, done: false }];
case TOGGLE_TODO:
return state.map((todo, index) => {
if (index !== action.payload.index) return todo;
return {
text: todo.text,
done: !todo.done,
};
});
default:
return state;
}
}
@MikeBild
Copy link
Author

@marius

I prefer an tech/language agnostic construct either(), because you can do it any "lambda" enabled language.

function either(f, g) {
	return function () {
		return f.apply(this, arguments) || g.apply(this, arguments);
	}
}

const gt10 = x => x > 10;
const even = x => x % 2 === 0;
const f = either(gt10, even);

console.log(f(7))
console.log(f(100))

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment