Skip to content

Instantly share code, notes, and snippets.

View caasi's full-sized avatar
🏝️
Spiritual Homeland

Isaac Huang caasi

🏝️
Spiritual Homeland
View GitHub Profile
const ZERO = 'a'.charCodeAt(0);
const WIDTH = 5;
const f = Math.floor;
function vPath(n: number): string {
if (n === 0) return '';
if (n > 0) return 'D'.repeat(n);
if (n < 0) return 'U'.repeat(-n);
return '' as never;
import { useState, useMemo, useEffect } from 'react';
import { Observable, BehaviorSubject } from 'rxjs';
// It's like the `useObservable` from 'rxjs-hooks' but with a better interface.
function useObservable<State>(
input$: Observable<State>,
initialState?: State,
) {
const [state, setState] = useState(initialState);
const state$ = useMemo(() => new BehaviorSubject(initialState), []);
import { of } from 'rxjs';
import { flatMap, tap } from 'rxjs/operators';
describe('containers', () => {
it('promise works', () => {
const c =
Promise.resolve(1).then(a =>
Promise.resolve(2).then(b =>
a + b
)
@caasi
caasi / nominal-enum.ts
Created February 26, 2020 14:58
nominal types as enums
type Foo = 0 & { readonly brand?: unique symbol };
type Bar = 1 & { readonly brand?: unique symbol };
type Baz = 0 & { readonly brand?: unique symbol };
type Foobar = Foo | Bar;
const Foobar = {
FOO: 0 as Foo,
BAR: 1 as Bar,
};
@caasi
caasi / ImageData.re
Last active February 25, 2020 17:25
Play with ReasonML
open Webapi.Dom;
open Webapi.Canvas;
open HtmlImageElement;
module MyCanvas2d = {
include Canvas2d;
[@bs.send.pipe : Canvas2d.t] external drawImage : (HtmlImageElement.t, float, float) => unit = "drawImage";
}
let useImageData = url => {
type ICallback = (i: number) => string
class Foo {
cb: ICallback = () => ''
registerCb(cb: ICallback) {
this.cb = cb
}
}
const foo = new Foo()
// Some helper types from:
// https://dev.to/miracleblue/how-2-typescript-get-the-last-item-type-from-a-tuple-of-types-3fh3
// Borrowed from SimplyTyped:
type Prev<T extends number> = [-1, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62][T];
// Actual, legit sorcery
// Borrowed from pelotom/hkts:
type GetLength<original extends any[]> = original extends { length: infer L } ? L : never;
type GetLast<original extends any[]> = original[Prev<GetLength<original>>];
const xs = [1, 3, 5, 8, 9];
let sum = 0;
for (let i = 0; i < xs.length; ++i) {
sum += xs[i];
}
console.log(sum);
let sum2 = 0;
for (let key in xs) {
@caasi
caasi / if-err.ls
Created September 20, 2019 06:07
if err in livescript backcalls
success = (f) -> f undefined, 1
failure = (f) -> f new Error('oops')
err, value <- success
console.error err if err
console.log value
err, value <- failure
console.error err if err
foo(0, 1, 2, function(x) {
return bar(0, 1, function(y) {
return x + y;
});
});
// v.s.
foo(0, 1, 2, (x) =>
bar(0, 1, (y) =>