///
import { Cell, Default, derive, handler, NAME, recipe, UI } from "commontools";
interface LinkedList {
value: string;
next?: LinkedList;
}
interface InputSchema {
title: Default;
}
type InputEventType = {
detail: {
message: string;
};
};
interface ListState {
items_list: Cell;
}
// Helper function to add a node to the linked list
function addNodeToList(list: LinkedList, value: string): LinkedList {
return {
value: value,
next: list,
};
}
function listToString(
list: LinkedList | null | undefined,
separator: string = " -> ",
): string {
if (!list) return "";
if (!list.next) return list.value;
return list.value + separator + listToString(list.next, separator);
}
const addItem = handler(
(event: InputEventType, state: ListState) => {
// Add node to linked list
const currentList = state.items_list.get();
const newList = addNodeToList(currentList, event.detail.message);
state.items_list.set(newList);
},
);
export default recipe(({ title }) => {
const items_list = Cell.of({ value: "1" });
// Create a derived value for the linked list string representation
// FIXME(@ellyxir): use inputschema instead of just creating it here
const linkedListString = derive(
items_list,
(list) => listToString(list.get(), "\n"),
);
return {
[NAME]: title,
[UI]: (
{title}
Super Simple LinkedList
Linked List:
{linkedListString}
),
title,
addItem: addItem({ items_list }),
};
});