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=762&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 7802 results for "function"(676ms)

whenfilmedmain.tsx7 matches

@tmcw•Updated 9 months ago
13}
14
15async function fetchRandomMovies() {
16 const currentYear = new Date().getFullYear()
17 const movies = []
35}
36
37function generateQuizHTML(movies, uuid) {
38 const currentYear = new Date().getFullYear()
39 return `
52 </style>
53 <script>
54 function updateInputs(index, value) {
55 document.getElementById('guess' + index).value = value;
56 document.getElementById('guessInput' + index).value = value;
91}
92
93function calculateScore(movies, guesses) {
94 return movies.reduce((score, movie, index) => {
95 const actualYear = new Date(movie.release_date).getFullYear()
102}
103
104function generateResultsHTML(movies, guesses, score) {
105 return `
106 <html>
152}
153
154function generateAllGuessesHTML(allGuesses) {
155 return `
156 <html>
198}
199
200export default async function main(req: Request): Promise<Response> {
201 const { author, name } = extractValInfo(import.meta.url)
202 const guessesKey = `${author}.${name}.guesses`

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);

ReactStream_migratedREADME.md4 matches

@jxnblk•Updated 9 months ago
7import { render, React } from "https://esm.town/v/jxnblk/ReactStream";
8
9function App() {
10 const [count, setCount] = React.useState(0);
11 return (
62```tsx
63// example middleware
64async function api (req: Request, res: Response, next): Promise<Response> {
65 if (req.pathname !== "/api") return next();
66 if (req.method === "POST") {
78```tsx
79// example middleware
80async function getInitialProps (req: Request, res: Response, next) {
81 // fetch data or do async work to pass as props to the component
82 req.data = {
95import { render } from "https://esm.town/v/jxnblk/ReactStream";
96
97function App () {
98 return (
99 <html>

valleGetValsContextWindowmain.tsx7 matches

@stevekrouse•Updated 9 months ago
1export default async function getValsContextWindow(model: any) {
2 const readmeVals: any = await (await fetch("https://janpaul123-readmevals.web.val.run/")).json();
3
183 import { render } from "npm:preact-render-to-string";
184
185 export default async function(req: Request) {
186 return new Response(
187 render(
212 const FLAT_TEMPLATES = sections.flatMap((section) => section.templates);
213
214 function tsResponse(code) {
215 return "```ts\n" + code + "\n```";
216 }
383 ### Utilities
384
385 Our Blob SDK also includes some utility functions to make working with blobs easier.
386
387 ##### Copy
507 role: "assistant",
508 content:
509 "\n```ts\nexport default async function (req: Request): Promise<Response> {\n return Response.json(\"Hello world\")\n}\n```",
510 },
511 {
516 role: "assistant",
517 content:
518 "\n```ts\nexport default async function(req: Request): Promise<Response> {\n const query = new URL(req.url).searchParams;\n\n // Read name from the querystring or body. Defaults to \"you\" if not present.\n const name = query.get(\"name\") || (await req.json().catch(() => ({}))).name || \"you\";\n\n // Returns the HTML response\n return new Response(`<h1>Hi ${name}!</h1>`, {\n headers: { \"Content-Type\": \"text/html\" },\n });\n}\n```",
519 },
520 {
533 role: "assistant",
534 content:
535 "```ts\nexport default async function(req: Request): Promise<Response> {\n const apiKey = Deno.env.get(\"METEO_KEY\");\n const apiUrl = `https://api.open-meteo.com/v1/forecast?latitude=40.6782&longitude=-73.9442&hourly=temperature_2m&current_weather=true&apikey=${apiKey}`;\n\n const response = await fetch(apiUrl);\n const weatherData = await response.json();\n\n return new Response(JSON.stringify(weatherData), { headers: { \"Content-Type\": \"application/json\" } });\n}\n```",
536 },
537 {

infiniteSVGGraphmain.tsx6 matches

@maxm•Updated 9 months ago
35// Database querying.
36
37function parseResultSet<T>(row: ResultSet): T[] {
38 return row.rows.map((r) => Object.fromEntries(r.map((c, i) => [row.columns[i], c]))) as T[];
39}
67};
68
69// Client side javascript and template functions.
70
71const clientJavascript = async () => {
135 });
136
137 function createHeartBurst(event) {
138 const button = event.currentTarget;
139 const buttonContainer = button.closest(".heart-button-container");
174};
175
176function escapeHTML(html: string): string {
177 const escapeChars: { [char: string]: string } = {
178 "&": "&amp;",
408 let encoder = new TextEncoder();
409
410 function isValidSVG(svgString) {
411 const parser = new DOMParser({
412 errorHandler: {
488
489app.get("/:id/img.svg", async (c) => {
490 function addSVGNamespace(svgString) {
491 if (!/^<\?xml/.test(svgString)) svgString = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" + svgString;
492 if (!/xmlns="http:\/\/www.w3.org\/2000\/svg"/.test(svgString))

twitterAlertmain.tsx1 match

@tmcw•Updated 9 months ago
3const query = "\"val.town\" OR \"val town\" -_ValTown_ -is:retweet"
4
5export async function twitterAlert({ lastRunAt }: Interval) {
6 const results = await twitterSearch({
7 query,

valTownBadgeSVGmain.tsx2 matches

@jxnblk•Updated 9 months ago
9const padLeft = 48;
10
11export function Badge({
12 scale = 1,
13 label = "View source on",
66}
67
68export default async function(req: Request): Promise<Response> {
69 const svg = renderToStaticMarkup(
70 <Badge scale={1} />,

upgradeHTTPPreviewValsmain.tsx4 matches

@stevekrouse•Updated 9 months ago
3import OpenAI from "npm:openai";
4
5async function getVals(username, type, limit) {
6 const res = await db.execute({
7 sql: `
21}
22
23async function checkHTTPPreviewUpgrade(code) {
24 const openai = new OpenAI();
25 const completion = await openai.chat.completions.create({
53 content: `const number = Math.random();
54
55 export default function(req: Request) {
56 return Response.json(number);
57 }`,
80
81/* This example will return the contents of a documentID passed in as the path as JSON. */
82export default async function(req: Request): Promise<Response> {
83 const docId = new URL(req.url).pathname.substring(1);
84

upgradeHTTPPreviewValsREADME.md5 matches

@stevekrouse•Updated 9 months ago
16 "name": "harlequinChickadee",
17 "probabilityUpgradeNeeded": true,
18 "reason": "The current code structure has several functions and program logic outside the main handler, including word selection, game state management, and SVG generation. These parts would not re-run with the new runtime, potentially affecting functionality. They need to be moved inside the handler to ensure consistent behavior across requests."
19 },
20 {
31 "name": "untitled_pinkRoundworm",
32 "probabilityUpgradeNeeded": true,
33 "reason": "The functions `addComment` and `getComments` as well as the initialization \nof the KEY variable perform actions that are intended to be run per request. These need to be moved \ninside the relevant HTTP handler to ensure the behavior remains consistent in the new runtime."
34 },
35 {
46 "name": "untitled_maroonSwallow",
47 "probabilityUpgradeNeeded": false,
48 "reason": "All the code, including the check for authentication,\n is inside the handler function. This means the behavior will stay \n the same with the new runtime."
49 },
50 {
51 "name": "wikiOG",
52 "probabilityUpgradeNeeded": true,
53 "reason": "The function `getWikipediaInfo` defined outside of the handler makes network requests and processes data for each request. In the new runtime, this function would only be executed once and cached. To ensure the same behavior in the new runtime, this function should be moved into the handler."
54 },
55 {
61 "name": "discordEventReceiver",
62 "probabilityUpgradeNeeded": false,
63 "reason": "All the relevant code for handling requests and logging input is inside the handler.\n No code needs to be moved for the new runtime to function correctly."
64 }
65]

getFileEmail4 file matches

@shouser•Updated 6 days ago
A helper function to build a file's email

TwilioHelperFunctions

@vawogbemi•Updated 2 months ago