Val Town Code SearchReturn to Val Town

API Access

You can access search results via JSON API by adding format=json to your query:

https://codesearch.val.run/?q=function&page=1483&format=json

For typeahead suggestions, use the /typeahead endpoint:

https://codesearch.val.run/typeahead?q=function

Returns an array of strings in format "username" or "username/projectName"

Found 18369 results for "function"(3331ms)

glideImportDemomain.tsx2 matches

@dvdsgl•Updated 9 months ago
1// 1. Start by importing the Glide helper library.
2//
3// Soon, this functionality will be part of the official
4// @glideapps/tables npm package.
5import * as Glide from "https://esm.town/v/dvdsgl/glide?v=661";
18// For example, you could call an API in a loop, using yield for each
19// batch of rows to import.
20async function* getRows() {
21 // Yield rows to import them:
22 yield { name: "David", favoriteTool: "Glide" };

glidemain.tsx11 matches

@dvdsgl•Updated 9 months ago
21export const layer = (info: GlideInfo) => Layer.succeed(Glide, Glide.of(info));
22
23const getGlide: Effect.Effect<GlideInfo, GlideError> = Effect.gen(function*() {
24 const provided = yield* Effect.serviceOption(Glide);
25
37});
38
39function removeUnsupportedColumnTypes(row: any): any {
40 const pr = { ...row };
41 for (const [k, v] of Object.entries(pr)) {
49
50// Handles calling fetch, checking for API errors
51function fetchGlide<A>(
52 method: "GET" | "POST" | "PUT",
53 url: string,
54 body: unknown,
55): Effect.Effect<A, GlideError> {
56 return Effect.gen(function*() {
57 const { token } = yield* getGlide;
58 const result = yield* Effect.tryPromise(() =>
90 rows: Stash | any[],
91): Effect.Effect<PutResult, GlideError> =>
92 Effect.gen(function*() {
93 // Some tables have a prefix, e.g. "native-table-" but this API
94 // does not accept it.
118 serial: string | number,
119): Effect.Effect<Stash, GlideError> =>
120 Effect.gen(function*() {
121 const id = typeof stash === "string" ? stash : stash.$stashID;
122
136};
137
138async function* bufferAsyncIterable<T>(
139 asyncIterable: AsyncIterable<T | T[]>,
140 max = 1_000,
152}
153
154export function importTableEffect<Row>(props: Import<Row>) {
155 const { table, getRows } = props;
156
157 return Effect.gen(function*() {
158 yield* Effect.logDebug(`ingest start`);
159
170 let serial = 0;
171 yield* Stream.runForEach(stream, (rows) =>
172 Effect.gen(function*() {
173 totalRows += rows.length;
174 yield* Effect.logDebug(`ingest ${totalRows} total rows`);
181
182// Runs an injestion job.
183export async function importTable<Row>(
184 props: Import<Row> & { debug?: boolean },
185) {

azureCheetahmain.tsx14 matches

@tmcw•Updated 9 months ago
16import { renderToString } from "npm:react-dom/server";
17
18export default function(
19 { tempValsParentFolderId }: { tempValsParentFolderId: string },
20) {
38 the simplest way to achieve the goal, though you can add some inline comments to explain your
39 reasoning (not for every line, but for major groups of lines). Don't use any environment variables
40 unless strictly necessary, for example use APIs that don't require a key, prefer internal function
41 imports (using esm.town), and prefer putting API keys as inline variables. Use built-in Deno
42 functions where possible. Unless specified, don't add error handling,
43 make sure that errors bubble up to the caller.
44 Avoid external images or base64 images, use emojis, unicode symtols, or icon fonts/libraries instead, unless that's
51 \`\`\`
52 There should be no comments like "more content here", it should be complete and directly runnable.
53 The val should create a "export default async function main" which is the main function that gets
54 executed on every HTTP request.
55 `.replace("\n", " ");
56
57 // Your response should start with \`\`\`ts and end with \`\`\`.
58 // The val should create a "export default async function main() {" which
59 // is the main function that gets executed, without any arguments. Don't return a Response object,
60 // just return a plain Javascript object, array, or string.
61
98 const writer = writable.getWriter();
99 const textEncoder = new TextEncoder();
100 function write(text) {
101 writer.write(textEncoder.encode(text));
102 }
174 </div>
175 <script>
176 function updateValName(valName) {
177 const valUrl = valName ? \`https://val.town/v/${username}/\${valName}\` : "";
178 const previewUrl = valName ? \`https://${username}-\${valName}.web.val.run\` : "";
182 document.getElementById('open-link').href = previewUrl;
183 }
184 function saveVal() {
185 if (window.codeMirrorEditor) {
186 document.getElementById("save-icon").classList.remove("hidden");
202 return false;
203 })
204 function openTab(tab) {
205 const tabButtonCode = document.getElementById("tab-button-code");
206 const tabButtonPreview = document.getElementById("tab-button-preview");
222 }
223 }
224 function toggleTab() {
225 openTab(document.getElementById("tab-panel-code").style.visibility === "visible" ? "preview" : "code");
226 }
281 (() => {
282 const scrollingElement = document.getElementById("conversation-container");
283 const callback = function (mutationsList, observer) {
284 scrollingElement.scrollTo({ left: 0, top: scrollingElement.scrollHeight, behavior: "instant" });
285 };
390 window.setCodeMirrorContent({ doc: '', old: ''});
391 let fullStr = "";
392 window.addToken = function(str) {
393 fullStr += str;
394 const code = fullStr.replaceAll("\`\`\`ts\\n", "").replaceAll("\`\`\`", "").replace(/^ts\\n/, '');
429 },
430 );
431 (async function() {
432 try {
433 await sleep(300);

VALLErunmain.tsx14 matches

@tmcw•Updated 9 months ago
16import { renderToString } from "npm:react-dom/server";
17
18export default function(
19 { tempValsParentFolderId }: { tempValsParentFolderId: string },
20) {
38 the simplest way to achieve the goal, though you can add some inline comments to explain your
39 reasoning (not for every line, but for major groups of lines). Don't use any environment variables
40 unless strictly necessary, for example use APIs that don't require a key, prefer internal function
41 imports (using esm.town), and prefer putting API keys as inline variables. Use built-in Deno
42 functions where possible. Unless specified, don't add error handling,
43 make sure that errors bubble up to the caller.
44 Avoid external images or base64 images, use emojis, unicode symtols, or icon fonts/libraries instead, unless that's
51 \`\`\`
52 There should be no comments like "more content here", it should be complete and directly runnable.
53 The val should create a "export default async function main" which is the main function that gets
54 executed on every HTTP request.
55 `.replace("\n", " ");
56
57 // Your response should start with \`\`\`ts and end with \`\`\`.
58 // The val should create a "export default async function main() {" which
59 // is the main function that gets executed, without any arguments. Don't return a Response object,
60 // just return a plain Javascript object, array, or string.
61
98 const writer = writable.getWriter();
99 const textEncoder = new TextEncoder();
100 function write(text) {
101 writer.write(textEncoder.encode(text));
102 }
174 </div>
175 <script>
176 function updateValName(valName) {
177 const valUrl = valName ? \`https://val.town/v/${username}/\${valName}\` : "";
178 const previewUrl = valName ? \`https://${username}-\${valName}.web.val.run\` : "";
182 document.getElementById('open-link').href = previewUrl;
183 }
184 function saveVal() {
185 if (window.codeMirrorEditor) {
186 document.getElementById("save-icon").classList.remove("hidden");
202 return false;
203 })
204 function openTab(tab) {
205 const tabButtonCode = document.getElementById("tab-button-code");
206 const tabButtonPreview = document.getElementById("tab-button-preview");
222 }
223 }
224 function toggleTab() {
225 openTab(document.getElementById("tab-panel-code").style.visibility === "visible" ? "preview" : "code");
226 }
281 (() => {
282 const scrollingElement = document.getElementById("conversation-container");
283 const callback = function (mutationsList, observer) {
284 scrollingElement.scrollTo({ left: 0, top: scrollingElement.scrollHeight, behavior: "instant" });
285 };
390 window.setCodeMirrorContent({ doc: '', old: ''});
391 let fullStr = "";
392 window.addToken = function(str) {
393 fullStr += str;
394 const code = fullStr.replaceAll("\`\`\`ts\\n", "").replaceAll("\`\`\`", "").replace(/^ts\\n/, '');
429 },
430 );
431 (async function() {
432 try {
433 await sleep(300);

subaudiomain.tsx4 matches

@kortina•Updated 9 months ago
22The first timestamp should be 0.`;
23
24async function processAudio(audio_uri) {
25 const substrate = new Substrate({ apiKey: Deno.env.get("SUBSTRATE_API_KEY") });
26 const opts = { cache_age: 60 * 60 * 24 * 7 };
91
92// Render site
93export default async function(req: Request): Promise<Response> {
94 const url = new URL(req.url);
95 const audio_uri = url.searchParams.get("url");
400 let currentChapterIndex = 0;
401
402 function updateText() {
403 const currentTime = audioPlayer.currentTime;
404 let segmentToDisplay = null;
515 const updateInterval = 1000 / 40;
516
517 function updateLoop(timestamp) {
518 if (timestamp - lastUpdateTime > updateInterval) {
519 updateText();

httpValErrorCatchermain.tsx13 matches

@janpaul123•Updated 9 months ago
6// Checks for minimum response size and presence of <html> tag.
7
8export default async function main(req: Request): Promise<Response> {
9 const url = new URL(req.url);
10 const valName = url.searchParams.get("val");
17 // Dynamically import the specified val
18 const module = await import(`https://esm.town/v/${valName}`);
19 const valFunction = module.default;
20
21 if (typeof valFunction !== "function") {
22 throw new Error("Imported val is not a function");
23 }
24
25 // Execute the imported val function
26 const response = await valFunction(req);
27 const originalHtml = await response.text();
28
42}
43
44function injectErrorHandlingScript(html: string): string {
45 const script = `
46 <script>
47 window.onerror = function(message, source, lineno, colno, error) {
48 window.parent.postMessage({ messageType: "valBrowserRuntimeError", errorString: "window.onerror: " + message }, "*");
49 };
50 window.addEventListener('unhandledrejection', function(event) {
51 window.parent.postMessage({ messageType: "valBrowserRuntimeError", errorString: "unhandledrejection: " + event.reason }, "*");
52 });
53 console.error = function(...args) {
54 window.parent.postMessage({ messageType: "valBrowserRuntimeError", errorString: "console.error: " + args.join(' ') }, "*");
55 };
56 window.addEventListener('load', function() {
57 setTimeout(function() {
58 window.parent.postMessage({ messageType: "success" }, "*");
59 }, 3000);
65}
66
67function createErrorResponse(errorString: string): Response {
68 const errorHtml = `
69 <html>

crypto_prices_infomain.tsx1 match

@ghsaboias•Updated 9 months ago
55};
56
57export default async function(interval) {
58 const cryptoPrices = await getCryptoPrices();
59 const formatted = formatCryptoPrices(cryptoPrices);

smallboatsapimain.tsx1 match

@joseph_c100•Updated 9 months ago
42console.log(jsonTable);
43
44export default async function(req: Request): Promise<Response> {
45 return new Response(JSON.stringify(jsonTable), {
46 headers: { "Content-Type": "application/json" },

sqliteExplorerAppREADME.md1 match

@nickgolden•Updated 9 months ago
33- [x] fix wonky sidebar separator height problem (thanks to @stevekrouse)
34- [x] make result tables scrollable
35- [x] add export to CSV, and JSON (CSV and JSON helper functions written in [this val](https://www.val.town/v/nbbaier/sqliteExportHelpers). Thanks to @pomdtr for merging the initial version!)
36- [x] add listener for cmd+enter to submit query

debugmain.tsx1 match

@moe•Updated 9 months ago
1export default async function(req: Request) {
2 return Response.json({ test: "Hello, world!", "import.meta.url": import.meta.url });
3}

getFileEmail4 file matches

@shouser•Updated 1 week ago
A helper function to build a file's email
tuna

tuna8 file matches

@jxnblk•Updated 2 weeks ago
Simple functional CSS library for Val Town
lost1991
import { OpenAI } from "https://esm.town/v/std/openai"; export default async function(req: Request): Promise<Response> { if (req.method === "OPTIONS") { return new Response(null, { headers: { "Access-Control-Allow-Origin": "*",
webup
LangChain (https://langchain.com) Ambassador, KubeSphere (https://kubesphere.io) Ambassador, CNCF OpenFunction (https://openfunction.dev) TOC Member.