Skip to content

Instantly share code, notes, and snippets.

@spgl
spgl / flatToMatrix.monoid.ts
Last active January 13, 2026 04:07
flatArray to matrixArray in TypeScript / モノイド合成で変換を表現
export interface HasLevel {
level: number;
}
export type TreeNode<T> = T & {
children: TreeNode<T>[];
};
// 「状態を受け取り新しい状態を返す関数」を変換の最小単位として扱う。
type Action<S> = (state: S) => S;
@spgl
spgl / flatToMatrix.imm-lite.ts
Last active January 13, 2026 04:07
flatArray to matrixArray in TypeScript / 完全イミュータブルだがコピー量を抑える
export interface HasLevel {
level: number;
}
export type TreeNode<T> = T & {
children: TreeNode<T>[];
};
type Action<S> = (state: S) => S;
@spgl
spgl / flatToMatrix.immutable.ts
Last active January 13, 2026 04:07
flatArray to matrixArray in TypeScript / 完全イミュータブルで参照透過を重視
/**
* フラットリストの要素に必要な最小要件を表す。
*/
export interface HasLevel {
level: number;
}
/**
* ツリー構造のノードを表す。元の型 T に children 配列を追加する。
*/
@spgl
spgl / flatToMatrix.ts
Last active January 13, 2026 04:08
flatArray to matrixArray in TypeScript / 実用重視の命令的実装
export interface HasLevel {
level: number;
}
export type TreeNode<T> = T & {
children: TreeNode<T>[];
};
export const flatToMatrix = <T extends HasLevel>(flatItems: T[]): TreeNode<T>[] => {
if (flatItems.length === 0) {