Search
round
@mxdvl
Round numbers with arbitrary decimal precision
Script
/** round with abitrary decimal precision */
export function round(number: number, precision = 5) {
return Math.round(number * Math.pow(10, precision)) / Math.pow(10, precision);
![rwev avatar](https://images.clerk.dev/oauth_github/img_2P1GmVdCqM7W2xjFiz7WHB8nFkM.png)
adjustMsToWeekday
@rwev
An interactive, runnable TypeScript val by rwev
Script
import { msToIsoDate } from "https://esm.town/v/rwev/msToIsoDate";
import { msDay as msDay2 } from "https://esm.town/v/stevekrouse/msDay?v=1";
export function adjustMsToWeekday(msDay) {
let date = new Date(msDay);
while (date.getDay() == 0 || date.getDay() == 6) {
basic_auth
@dandivelbiss
Basic Auth Middleware A middleware for wrapping an HTTP val with Basic authentication. See https://developer.mozilla.org/en-US/docs/Web/HTTP/Authentication See also: https://www.val.town/v/pomdtr/basicAuth for a different approach
HTTP
const { username, password } = options;
return `Basic ${btoa(`${username}:${password}`)}`;
export function authMiddleware(
handler: (Request) => Promise<Response>,
options: Options,
return new Response("Unauthorized", { status: 401 });
return handler(request);
export default async function(req: Request): Promise<Response> {
return new Response("This is middleware only");
![dantaeyoung avatar](https://images.clerk.dev/oauth_github/img_2PhRJV5CizAxF2bsCR64RgR1hVx.jpeg)
btcPriceAlert
@dantaeyoung
BTC Price Alert This val monitors the price of Bitcoin (BTC) and sends an email alert if the price fluctuates significantly. Specifically, it checks the current BTC price against the last recorded price and triggers an email notification if the change exceeds 20%. The email includes the new price, formatted as currency. Fork this val to get these notifications on your inbox.
Cron
import { email } from "https://esm.town/v/std/email?v=9";
import { currency } from "https://esm.town/v/stevekrouse/currency";
export async function btcPriceAlert() {
const lastBtcPrice: number = await blob.getJSON("lastBtcPrice");
let btcPrice = await currency("usd", "btc");
btcPriceAlert
@richardkaplan
BTC Price Alert This val monitors the price of Bitcoin (BTC) and sends an email alert if the price fluctuates significantly. Specifically, it checks the current BTC price against the last recorded price and triggers an email notification if the change exceeds 20%. The email includes the new price, formatted as currency. Fork this val to get these notifications on your inbox.
Cron
import { email } from "https://esm.town/v/std/email?v=9";
import { currency } from "https://esm.town/v/stevekrouse/currency";
export async function btcPriceAlert() {
const lastBtcPrice: number = await blob.getJSON("lastBtcPrice");
let btcPrice = await currency("usd", "btc");
emailMeExchangeRate
@frankdilo
An interactive, runnable TypeScript val by frankdilo
Script
import { formatCurrency } from "https://esm.town/v/frankdilo/formatCurrency";
import { convertCurrency } from "https://esm.town/v/frankdilo/convertCurrency";
export async function emailMeExchangeRate() {
const rate = await convertCurrency("eur");
const formattedRate = formatCurrency(rate, 3, "EUR");
![stevekrouse avatar](https://images.clerk.dev/uploaded/img_2PqHa2Gsy93xQrjh2w78Xu0cChW.jpeg)
stripFences
@stevekrouse
Strip Fences Useful for stripping out code fences, ie from a reply from an llm where you want code and it replies with markdown code fences around that code.
Script
export default function stripFences(content: string) {
return content.replace(/```[\s\S]*?\n([\s\S]*?)\n```/g, "$1");
![vladimyr avatar](https://images.clerk.dev/oauth_github/img_2TYEBDWl6QE7Nsk4AHoXsDuwvBE.png)
dataURL
@vladimyr
// SPDX-License-Identifier: 0BSD
Script
// SPDX-License-Identifier: 0BSD
import ky from "npm:ky";
export async function convertUrlToDataURL(url: string | URL): Promise<string> {
const blob = await ky.get(url).blob();
return convertBlobToDataURL(blob);
export function convertBlobToDataURL(blob: Blob): Promise<string> {
return new Promise((resolve, reject) => {
const reader = new FileReader();
jamz
@all
@jsxImportSource https://esm.sh/react
HTTP
/** @jsxImportSource https://esm.sh/react */
// Set to true to disable all editing functionality
const READ_ONLY = true;
created_at: string;
function AddSongForm({ onAdd }: { onAdd: (song: Omit<Song, "id" | "created_at">) => void }) {
const [url, setUrl] = React.useState("");
</form>
function SongCard(
{ song, onDelete, onEdit }: {
</div>
function App() {
const [songs, setSongs] = React.useState<Song[]>([]);
</div>
function client() {
createRoot(document.getElementById("root")!).render(<App />);
client();
export default async function server(req: Request): Promise<Response> {
const { sqlite } = await import("https://esm.town/v/stevekrouse/sqlite");
stripFrontmatter
@nbbaier
utility to strip yaml frontmatter from a md file
Script
import { unified } from "https://esm.sh/unified";
import { matter } from "npm:vfile-matter";
export async function stripMetadata(markdown: string) {
const file = await unified()
.use(remarkParse)
substrateBadgeMiddleware
@substrate
How to use: import wrapper from "https://esm.town/v/substrate/substrateBadgeMiddleware";
async function handler(req: Request): Promise<Response> {
const html = `
<h1>Hello, world</h1>
`;
return new Response(html, {
headers: {
"Content-Type": "text/html; charset=utf-8",
},
});
}
export default wrapper(handler, import.meta.url); reference: https://www.val.town/v/jxnblk/valTownBadge
Script
import wrapper from "https://esm.town/v/substrate/substrateBadgeMiddleware";
async function handler(req: Request): Promise<Response> {
const html = `
import valTownBadge from "https://esm.town/v/substrate/substrateBadge";
export default function badgeMiddleware(handler, url: string) {
return async function(req: Request): Promise<Response> {
if (req.method !== "GET") return await handler(req);
![jakub_tel avatar](https://secure.gravatar.com/avatar/c927a332d976a1a8b72a8aa7deaf5d98.jpg?s=200&d=identicon)
missingRosePony
@jakub_tel
BTC Price Alert This val monitors the price of Bitcoin (BTC) and sends an email alert if the price fluctuates significantly. Specifically, it checks the current BTC price against the last recorded price and triggers an email notification if the change exceeds 20%. The email includes the new price, formatted as currency. Fork this val to get these notifications on your inbox.
Cron
import { email } from "https://esm.town/v/std/email?v=9";
import { currency } from "https://esm.town/v/stevekrouse/currency";
export default async function btcPriceAlert() {
const lastBtcPrice: number = await blob.getJSON("lastBtcPrice");
let btcPrice = await currency("usd", "btc");
htmlBuilder
@xkonti
* Renders the provided tag into HTML string.
Script
* Renders the provided tag into HTML string.
export function renderTag(tag: TagDescriptor): string {
const content = renderTags(tag.content);
* Renders provided tags into a list of HTML strings.
export function renderTags(tags: Array<HtmlContent>): string[] {
return tags.map(element => {
return renderTag(element);
export function basicTag(tagName: string, content: HtmlContents | undefined = undefined): Tag {
const tag = new Tag(tagName);
return tag;
export function selfClosingTag(tagName: string): Tag {
return new Tag(tagName).makeSelfClose();
export function fragment(content: HtmlContents | undefined = undefined): Tag {
return basicTag("");
![stevekrouse avatar](https://images.clerk.dev/uploaded/img_2PqHa2Gsy93xQrjh2w78Xu0cChW.jpeg)
ab2str
@stevekrouse
Convert an ArrayBuffer into a string
from https://developer.chrome.com/blog/how-to-convert-arraybuffer-to-and-from-string/
Script
Convert an ArrayBuffer into a string
from https://developer.chrome.com/blog/how-to-convert-arraybuffer-to-and-from-string/
export function ab2str(buf) {
return String.fromCharCode.apply(null, new Uint8Array(buf));
weatherForecastDashboard
@bhavana
@jsxImportSource https://esm.sh/react@18.2.0
HTTP
import { createRoot } from "https://esm.sh/react-dom@18.2.0/client";
function WeatherDashboard() {
const [weather, setWeather] = useState(null);
useEffect(() => {
function handleClickOutside(event) {
if (suggestionRef.current && !suggestionRef.current.contains(event.target)) {
return () => document.removeEventListener('mousedown', handleClickOutside);
async function fetchLocationSuggestions(query) {
if (query.length < 2) {
fetchLocationSuggestions(value);
async function selectLocation(selectedLocation) {
setLocationInput(selectedLocation.name);
await fetchWeatherData(selectedLocation);
async function fetchWeatherData(coords) {
try {
setError('Failed to fetch weather data');
async function handleLocationSubmit(e) {
e.preventDefault();
</div>
function client() {
createRoot(document.getElementById("root")).render(<WeatherDashboard />);
if (typeof document !== "undefined") { client(); }
export default async function server(request: Request): Promise<Response> {
return new Response(`