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/image-url.jpg%20%22Image%20title%22?q=function&page=51&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 21953 results for "function"(831ms)

TastkItqueries.ts19 matches

@diegoivo•Updated 1 day ago
4
5// Função simples para hash de senha
6async function hashPassword(password: string): Promise<string> {
7 // Em produção, use uma biblioteca de hash mais segura
8 // Esta é uma implementação básica para demonstração
15
16// Função para verificar senha
17async function verifyPasswordHash(password: string, hash: string): Promise<boolean> {
18 const calculatedHash = await hashPassword(password);
19 return calculatedHash === hash;
22// ==================== Funções de Usuário ====================
23
24export async function createUser(input: CreateUserInput): Promise<User> {
25 try {
26 // Verificar novamente se o email ou username já existem (para evitar condições de corrida)
55}
56
57export async function getUserByUsername(username: string): Promise<User | null> {
58 const result = await sqlite.execute(
59 `SELECT id, username, email, password_hash, created_at, updated_at
66}
67
68export async function getUserByEmail(email: string): Promise<User | null> {
69 const result = await sqlite.execute(
70 `SELECT id, username, email, password_hash, created_at, updated_at
77}
78
79export async function getUserById(id: number): Promise<User | null> {
80 const result = await sqlite.execute(
81 `SELECT id, username, email, created_at, updated_at
88}
89
90export async function verifyPassword(plainPassword: string, hashedPassword: string): Promise<boolean> {
91 return await verifyPasswordHash(plainPassword, hashedPassword);
92}
94// ==================== Funções de Projeto ====================
95
96export async function createProject(input: CreateProjectInput): Promise<Project> {
97 const result = await sqlite.execute(
98 `INSERT INTO ${PROJECTS_TABLE} (name, color, user_id)
105}
106
107export async function getProjectsByUserId(userId: number): Promise<Project[]> {
108 const result = await sqlite.execute(
109 `SELECT id, name, color, user_id, created_at, updated_at
117}
118
119export async function getProjectById(id: number, userId: number): Promise<Project | null> {
120 const result = await sqlite.execute(
121 `SELECT id, name, color, user_id, created_at, updated_at
128}
129
130export async function updateProject(id: number, userId: number, name: string, color?: string): Promise<Project | null> {
131 const updateFields = [];
132 const params = [];
162}
163
164export async function deleteProject(id: number, userId: number): Promise<boolean> {
165 const result = await sqlite.execute(
166 `DELETE FROM ${PROJECTS_TABLE}
174// ==================== Funções de Tarefa ====================
175
176export async function createTask(input: CreateTaskInput): Promise<Task> {
177 const result = await sqlite.execute(
178 `INSERT INTO ${TASKS_TABLE} (title, description, due_date, priority, project_id, user_id)
192}
193
194export async function getTasksByProjectId(projectId: number, userId: number): Promise<Task[]> {
195 const result = await sqlite.execute(
196 `SELECT id, title, description, due_date, priority, completed, project_id, user_id, created_at, updated_at
211}
212
213export async function getTasksByUserId(userId: number): Promise<Task[]> {
214 const result = await sqlite.execute(
215 `SELECT id, title, description, due_date, priority, completed, project_id, user_id, created_at, updated_at
230}
231
232export async function getTaskById(id: number, userId: number): Promise<Task | null> {
233 const result = await sqlite.execute(
234 `SELECT id, title, description, due_date, priority, completed, project_id, user_id, created_at, updated_at
241}
242
243export async function updateTask(id: number, userId: number, input: UpdateTaskInput): Promise<Task | null> {
244 const updateFields = [];
245 const params = [];
295}
296
297export async function toggleTaskCompletion(id: number, userId: number): Promise<Task | null> {
298 const result = await sqlite.execute(
299 `UPDATE ${TASKS_TABLE}
308}
309
310export async function deleteTask(id: number, userId: number): Promise<boolean> {
311 const result = await sqlite.execute(
312 `DELETE FROM ${TASKS_TABLE}
Oronet11

Oronet1101_script.tsx1 match

@oronet11•Updated 1 day ago
1// This script returns a random fun fact
2// You can run scripts manually in this view or call it from other vals.
3export default function getRandomFact() {
4 const funFacts = [
5 "Honey never spoils.",

OroOroNet1 match

@oronet11•Updated 1 day ago
1export default async function (req: Request): Promise<Response> {
2 return Response.json({ ok: true })
3}

Oroindex.ts5 matches

@oronet11•Updated 1 day ago
2
3// Fetch top cryptocurrencies data from CoinGecko API
4async function fetchCryptoData(limit = 50) {
5 try {
6 // CoinGecko has rate limits, so we need to add a delay and retry mechanism
29
30// Mock data for testing when API fails
31function getMockCryptoData(limit = 10) {
32 const mockCoins = [
33 {
157
158// Fetch detailed data for a specific cryptocurrency
159async function fetchCryptoDetails(id: string) {
160 try {
161 const response = await fetch(
183
184// Mock data for testing when API fails
185function getMockCryptoDetails(id: string) {
186 const mockDetails: Record<string, any> = {
187 "bitcoin": {
259}
260
261export default async function(req: Request) {
262 const url = new URL(req.url);
263

Oroindex.html17 matches

@oronet11•Updated 1 day ago
143 <script>
144 // Format numbers with commas and appropriate decimal places
145 function formatNumber(num, decimals = 2) {
146 if (num === null || num === undefined) return 'N/A';
147 return new Intl.NumberFormat('en-US', {
152
153 // Format currency with $ symbol
154 function formatCurrency(num, decimals = 2) {
155 if (num === null || num === undefined) return 'N/A';
156 return '$' + formatNumber(num, decimals);
158
159 // Format large numbers with abbreviations (K, M, B, T)
160 function formatLargeNumber(num) {
161 if (num === null || num === undefined) return 'N/A';
162 if (num < 1000) return formatNumber(num);
171
172 // Format percentage
173 function formatPercentage(num) {
174 if (num === null || num === undefined) return 'N/A';
175 return formatNumber(num) + '%';
177
178 // Format date
179 function formatDate(dateString) {
180 if (!dateString) return 'N/A';
181 const date = new Date(dateString);
184
185 // Get CSS class for price change
186 function getPriceChangeClass(change) {
187 return change >= 0 ? 'positive' : 'negative';
188 }
189
190 // Get icon for price change
191 function getPriceChangeIcon(change) {
192 return change >= 0 ? 'fa-caret-up' : 'fa-caret-down';
193 }
194
195 // Fetch cryptocurrency data
196 async function fetchCryptoData() {
197 try {
198 const response = await fetch('/api/crypto');
209
210 // Fetch detailed data for a specific cryptocurrency
211 async function fetchCryptoDetails(id) {
212 try {
213 const response = await fetch(`/api/crypto/${id}`);
223
224 // Populate the crypto table
225 function populateCryptoTable(data) {
226 const tableBody = document.getElementById('cryptoTableBody');
227 tableBody.innerHTML = '';
266
267 // Filter cryptocurrencies based on search input
268 function filterCryptoTable() {
269 const searchInput = document.getElementById('searchInput');
270 const filter = searchInput.value.toLowerCase();
283
284 // Open cryptocurrency detail modal
285 async function openCryptoModal(id) {
286 const modal = document.getElementById('cryptoModal');
287 modal.classList.remove('hidden');
332
333 // Create a dummy price chart (in a real app, you'd use historical data)
334 function createDummyPriceChart(currentPrice) {
335 const ctx = document.getElementById('priceChart').getContext('2d');
336
374 tooltip: {
375 callbacks: {
376 label: function(context) {
377 return formatCurrency(context.raw);
378 }
389 y: {
390 ticks: {
391 callback: function(value) {
392 return formatCurrency(value);
393 }
400
401 // Close cryptocurrency detail modal
402 function closeCryptoModal() {
403 const modal = document.getElementById('cryptoModal');
404 modal.classList.add('hidden');
406
407 // Initialize the app
408 async function initApp() {
409 // Set up view source link
410 const viewSourceLink = document.getElementById('viewSourceLink');

Orocrypto-tracker.tsx1 match

@oronet11•Updated 1 day ago
2// Fetches and displays current prices for popular cryptocurrencies
3
4export default async function (req: Request) {
5 try {
6 // Fetch cryptocurrency data from CoinGecko API

Orocrypto-chance.tsx8 matches

@oronet11•Updated 1 day ago
11
12// Initialize or get existing stats
13async function getStats(): Promise<GameStats> {
14 try {
15 const stats = await blob.getJSON("crypto_chance_stats") as GameStats;
27
28// Update stats after a game
29async function updateStats(win: boolean): Promise<GameStats> {
30 const stats = await getStats();
31 stats.totalFlips++;
41
42// Simulate a coin flip
43function flipCoin(): "heads" | "tails" {
44 return Math.random() < 0.5 ? "heads" : "tails";
45}
46
47// Get a crypto-themed message based on the result
48function getCryptoMessage(win: boolean): string {
49 if (win) {
50 const messages = [
68}
69
70// Main handler function
71export default async function(req: Request): Promise<Response> {
72 // Handle different HTTP methods
73 if (req.method === "POST") {
195 const losses = document.getElementById('losses');
196
197 function disableButtons(disable) {
198 headBtn.disabled = disable;
199 tailsBtn.disabled = disable;
207 }
208
209 async function playGame(choice) {
210 disableButtons(true);
211 resultDiv.classList.add('hidden');

Oro04_email.tsx1 match

@oronet11•Updated 1 day ago
2// Click "Run", copy and paste the email address and send an email to it.
3// This example will log the email details received.
4export default async function emailHandler(email: Email){
5 console.log("Email received!", email.from, email.subject, email.text);
6 for (const file of email.attachments) {

Oro03_cron.tsx1 match

@oronet11•Updated 1 day ago
2// Configure the timer with the 🕒 icon in the top right.
3// This example just logs the current time.
4export function scheduledHandler() {
5 const timestamp = new Date().toISOString();
6 console.log(`Cron val executed at: ${timestamp}`);

Oro02_http.tsx1 match

@oronet11•Updated 1 day ago
2// Access it via its public URL (you can also pick a nicer subdomain).
3// Try adding ?name=YourName to the URL!
4export default function httpHandler(req: Request): Response {
5 const url = new URL(req.url);
6 const name = url.searchParams.get("name") || "Friend";

getFileEmail4 file matches

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

tuna8 file matches

@jxnblk•Updated 1 month 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.