Skip to content

Instantly share code, notes, and snippets.

type Subscriber<T> = (val: T) => void
type Unsubscriber = () => void
export default class Observable<T> {
private subscribers: Subscriber<T>[] = []
private unsubscriber: Unsubscriber
private _value: T
constructor(source?: (cb: Subscriber<T>) => Unsubscriber) {
if (source) {
@ktsn
ktsn / module.js
Created July 14, 2016 10:57
[Vuex] Suppress prefix or suffix in the module definition
// use shorter name in local
const ADD = `ADD_TOAST_MESSAGE`
const REMOVE = `REMOVE_TOAST_MESSAGE`
// export as longer name with suffix
export {
ADD as ADD_TOAST_MESSAGE,
REMOVE as REMOVE_TOAST_MESSAGE
}
@ktsn
ktsn / action.ts
Last active July 15, 2016 10:35
Vuex action helper
import {
INIT_SOME_DATA,
ADD_SOME_DATA,
MOVE_SOME_DATA,
REMOVE_SOME_DATA,
UPDATE_SOME_DATA
} from '../mutation_types'
import { ISomeData } from '../model/some_data'
export function traverse<T, U>(obj: Dictionary<T>, f: (t: T) => Array<U>) : Array<Dictionary<U>> {
return sequence(
mapValues(obj, t => {
return f(t)
})
)
}
export function sequence<T>(obj: Dictionary<Array<T>>) : Array<Dictionary<T>> {
function loop<T>(acc: Array<Dictionary<T>>, obj: Dictionary<Array<T>>) : Array<Dictionary<T>> {
@ktsn
ktsn / mouse-position.js
Created August 23, 2016 01:46
特定の要素上でマウスイベントが発生した時に、その要素におけるマウスの座標を取得する
el.addEventListener('mousemove', event => {
const rect = event.currentTarget.getBoundingClientRect()
const pos = {
left: event.clientX - rect.left,
top: event.clientY - rect.top
}
})
@ktsn
ktsn / undo_redo.js
Last active October 14, 2016 15:07
export const ({ shouldRecord, invertAction, isUndo, isRedo }) => {
const history = []
return store => next => action => {
if (isUndo(action)) {
const invert = invertAction(lastUndoable(history))
history.push(invert)
next(invert)
return
}
type FnMapperR<T> = {
[K in keyof T]: (...args: any[]) => T[K]
}
type FnMapper2<T, U, R> = {
[K in keyof U]: (t: T, u: U[K]) => R
}
declare function module <S, G, A, M> (module: {
namespaced?: boolean,
@ktsn
ktsn / module.ts
Last active January 26, 2017 16:44
import { inject, create } from '../../../src/interface'
import Counter from './counter'
const { Getters, Mutations, Actions } = inject('counter', Counter)
interface Todo {
id: number
isCompleted: boolean
title: string
}
@ktsn
ktsn / typed-vuex.ts
Last active July 24, 2017 16:26
Discovering type safe usage of Vuex
import { Store, ActionContext } from 'vuex'
type Actions<S, P> = {
[K in keyof P]: (ctx: ActionContext<S, any>, payload: P[K]) => void | Promise<any>
}
type Mutations<S, P> = {
[K in keyof P]: (state: S, payload: P[K]) => void
}
interface Emit<Payloads> {
<Name extends keyof Payloads>(name: Name, payload: Payloads[Name]): void
}
interface Observe<Payloads> {
<Name extends keyof Payloads>(
name: Name,
cb: (payload: Payloads[Name]) => void
): void
}