Skip to content

Instantly share code, notes, and snippets.

@reidev275
reidev275 / Validation.ts
Last active July 24, 2019 14:08
Validation with Monoidal Contravariant Functors
// a type to contain information about validation results
export type Validation =
| { kind: "Success" }
| { kind: "Failure"; errors: string[] };
// helper functions to create Validation objects
const success: Validation = { kind: "Success" };
const failure = (errors: string[]): Validation => ({
kind: "Failure",
errors: errors
import React from "react";
const delay = () => new Promise((res, rej) => setTimeout(res, 2000));
type Model = { count: number };
type Message = "increment" | "decrement" | "sendDelay";
const Counter: React.FC<Model> = (initial: Model) => {
const [model, emit] = React.useReducer((m: Model, msg: Message): Model => {
switch (msg) {
import * as React from "react";
import { Tea } from "./tea";
type Props = { start?: number };
type Message = "increment" | "decrement";
type Model = { count: number };
export class Counter extends Tea<Props, Message, Model> {
constructor(props: Props) {
super(props);
import React, { Component } from "react";
import { FormModel, Form } from "./Form";
type Person = {
firstName: string;
lastName: string;
birthdate: Date | undefined;
gender: "Male" | "Female" | "Trans" | "Other" | "";
children: number;
};
@reidev275
reidev275 / api.ts
Last active April 17, 2019 01:07
Type safe api and client. By defining an interface, some mapped types, and some generic helpers we're able to interpret the interface into a type safe server and client library.
//code that exists in the server project
import { AsEndpoint, Handler, generateClient } from "./endpoint"
import * as express from "express";
//Our Api for communication between server and client
export interface Api {
getPokemonByName(name: string): Pokemon | undefined;
allPokemon(): Pokemon[];
}
type Input<A> = { title: string; value: A };
type Form<A> = { [P in keyof A]: Input<A[P]> };
//An example model
type Person = {
firstName: string;
lastName: string;
children: number;
};
program ∷ State → Dsl State
program init =
forward init
>>= left
>>= forward
>>= right
>>= forward
>>= left
>>= forward
>>= backward
import Control.Monad.Free (Free, liftF, foldFree)
import Effect (Effect)
import Effect.Console (log)
leftImpl ∷ State → State
leftImpl (State s) =
case s.direction of
North → State s { direction = West }
South → State s { direction = East }
East → State s { direction = North }
turnAround ∷ State → Dsl State
turnAround init =
left init
>>= left
outAndBack ∷ State → Dsl State
outAndBack init =
forward init
>>= forward
>>= turnAround
import Control.Monad.Free (liftF)
forward ∷ State → Dsl State
forward state = liftF $ Forward state identity
backward ∷ State → Dsl State
backward state = liftF $ Backward state identity
-- ... it's the same for the others as well