Skip to content

Instantly share code, notes, and snippets.

View mvolkmann's full-sized avatar

Mark Volkmann mvolkmann

View GitHub Profile
@mvolkmann
mvolkmann / top-state.js
Created November 18, 2018 19:23
a custom React hook named "useTopState" that is similar to "useState", but allows multiple components to share the state and be rerendered when it changes
const stateMap = {};
function render(state) {
for (const component of state.components) component.forceUpdate();
}
export default function useTopState(name, initialValue) {
let state = stateMap[name];
if (!state) {
@mvolkmann
mvolkmann / gist:7876a4629ba11291ed65882c5d364f04
Created March 1, 2018 15:31
Prettier formatting of ternaries
// Original code
const score = 7;
const someVar =
score < 10 ? 'some long string' :
score < 20 ? 'this is looking promising' :
score < 30 ? 'passing' :
score < 40 ? 'proficient' :
'expert';
// What Prettier does
@mvolkmann
mvolkmann / type-classes.js
Created February 22, 2018 16:44
JavaScript version of what I'm trying to do in Haskell
const colorNameToHexMap = {
red: 'FF0000',
green: '00FF00',
blue: '0000FF'
};
const colorHexToNameMap = {
FF0000: 'red',
'00FF00': 'green',
'0000FF': 'blue'
@mvolkmann
mvolkmann / type-classes.hs
Created February 22, 2018 02:18
learning about Haskell type classes
import qualified Data.Map as Map
-- A tuple of three Ints
type RGB = (Int, Int, Int)
-- Colors can be specified in three ways.
data Color =
ColorName String |
ColorHex String |
ColorRgb Int Int Int
instance LogType (IO a) where
logn' arr = do
-- Call putStr on all the elements in arr.
mapM_ putStr arr -- functions that end in _ ignore their result
-- Output a newline.
putStrLn ""
-- The "do" block must return something.
return undefined
instance (Show a, LogType r) => LogType (a -> r) where
@mvolkmann
mvolkmann / matt-follett.js
Created May 18, 2017 20:02
Flow type discriminating
// @flow
type Action1Type = {
type: 'A1',
payload: {
name: string
}
};
type Action2Type = {
@mvolkmann
mvolkmann / demo.js
Last active May 11, 2017 21:14
Flow .js.flow declaration files
const double = require('./math').double;
console.log(double('20'));
@mvolkmann
mvolkmann / math.js
Created January 6, 2017 00:54
CommonJS Flow example
// @flow
function product(a, b) {
return a * b;
}
exports.product = product;
@mvolkmann
mvolkmann / foo.js
Created April 12, 2013 21:39
An example of how I would write code to read from a new Node.js stream ...
stream.on('readable', function () {
var data;
while (true) {
data = stream.read();
if (data === null) break;
// use the data
}
});
stream.on('end', function () {
@mvolkmann
mvolkmann / form.html
Created March 17, 2013 11:45
IE9 form test
<html>
<head>
<title>Test Form</title>
<script src="form.js"></script>
</head>
<body>
<form id="myform" method="post" action="http://localhost:3000">
<label for="name">Name:</label>
<input id="name" name="name" type="text"/>
<button type="submit">Go!</button>