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=781&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 8273 results for "function"(496ms)

switchbotmain.tsx2 matches

@stevekrouse•Updated 8 months ago
18const ValTownOfficeDeviceId = "CD6F3A810848";
19
20async function switchbotRequest(path, args) {
21 const token = Deno.env.get("SWITCHBOT_TOKEN");
22 const secret = Deno.env.get("SWITCHBOT_KEY");
42}
43
44function botPress(device) {
45 return switchbotRequest(`v1.1/devices/${device}/commands`, {
46 method: "POST",

switchbotmain.tsx2 matches

@stevekrouse•Updated 8 months ago
18const ValTownOfficeDeviceId = "CD6F3A810848";
19
20async function switchbotRequest(path, args) {
21 const token = Deno.env.get("SWITCHBOT_TOKEN");
22 const secret = Deno.env.get("SWITCHBOT_KEY");
42}
43
44function botPress(device) {
45 return switchbotRequest(`v1.1/devices/${device}/commands`, {
46 method: "POST",

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`

hardwarebingomain.tsx1 match

@stevekrouse•Updated 9 months ago
97if (typeof document !== "undefined") { createRoot(document.getElementById("root")).render(<App />); }
98
99export default async function(req: Request): Promise<Response> {
100 return new Response(
101 renderToString(

emailmain.tsx1 match

@std•Updated 9 months ago
12 * The email address(es) to send the email to. Only available to Val Town Pro subscribers.
13 * Can be a single string, IAddress object, or an array of strings/IAddress objects.
14 * @default the email of the logged user calling this function.
15 */
16 to?: (IAddress | string)[] | IAddress | string;

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

getFileEmail4 file matches

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

TwilioHelperFunctions

@vawogbemi•Updated 2 months ago