Skip to content

Instantly share code, notes, and snippets.

View rbiggs's full-sized avatar

Robert Biggs rbiggs

View GitHub Profile
@rbiggs
rbiggs / tagged-union.js
Created June 18, 2019 12:36
A function to create tagged unions.
const hasOwnProperty = Object.prototype.hasOwnProperty
/**
* Create a union of string tags.
* @param {string[]} types
*/
function createUnion(types) {
const variants = Object.create(null)
let checkTag = x => x && x.type
@rbiggs
rbiggs / .json
Created February 24, 2019 13:50
jsconfig file for turning on TypeScript linting for JavaScript
{
"compilerOptions": {
"checkJs": true
},
"exclude": [
"node_modules",
"**/node_modules/*"
]
}
@rbiggs
rbiggs / .js
Last active February 3, 2019 18:37
Adding a subscription
subscriptions(state, send) {
return () => {
document.addEventListener('keypress', function (e) {
if (e.keyCode === 13) {
send({ type: 'addItem' })
}
})
}
}
@rbiggs
rbiggs / .js
Last active October 25, 2019 03:16
Clone state for actions for immutability
udate(state, message) {
// Create clone of state with destructing:
const prevState = {...state}
// Pass cloned state to actions:
return actions(prevState, message)
}
@rbiggs
rbiggs / .js
Last active October 25, 2019 03:05
Adding an action to delete an item from the list component based on the key value in the message
// actions gets two arguments: state and the message we send
function actions(state, message) {
switch(message) {
case 'updateInputValue':
// Update state with new value:
state.inputValue = message.value
// Don't forget to return state:
return state
case 'addItem':
// Add new item to array:
@rbiggs
rbiggs / .js
Created February 3, 2019 17:49
Using an event to send a message to delete an item from the list component
<li key={item.key}>
<span>{item.value}</span>
<button class="delete-item" onclick={() => send({type: 'deleteItem', value: item.key})}>X</button>
</li>
@rbiggs
rbiggs / .js
Last active October 25, 2019 03:08
Handing the message to add a new item to the list component
// actions gets two arguments: state and the message we send
function actions(state, message) {
switch(message) {
case 'updateInputValue':
// Update state with new value:
state.inputValue = message.value
// Don't forget to return state:
return state
case 'addItem':
// Add new item to array:
@rbiggs
rbiggs / .js
Created February 3, 2019 17:47
Adding an event to the Add button to send a message
<button class="add-item" onclick={() => send({type: 'addItem'})}>Add</button>
@rbiggs
rbiggs / .js
Created February 3, 2019 17:46
Using actions inside a program's update method
update(state, message) {
return actions(state, message)
}
@rbiggs
rbiggs / .js
Last active October 25, 2019 03:08
Actions for the program's update method
// actions gets two arguments: state and the message we send
function actions(state, message) {
switch(message) {
case 'updateInputValue':
// Update state with new value:
state.inputValue = message.value
// Don't forget to return state:
return state
}
}