Browse by Topic

Find code snippets organized by common programming tasks and patterns.

Arrays & Lists

Filter, map, reduce, sort, find, and manipulate arrays across languages.

Filter ArrayJavaScript
const evens = nums.filter(n => n % 2 === 0); const adults = users.filter(u => u.age >= 18);
Map ArrayPython
squares = [x**2 for x in nums] names = [user['name'] for user in users]
Sort ArrayPHP
sort($arr); // ascending usort($users, fn($a, $b) => $a['age'] - $b['age']);
Reduce ArrayJavaScript
const sum = nums.reduce((a, b) => a + b, 0); const grouped = items.reduce((acc, item) => { (acc[item.type] ||= []).push(item); return acc; }, {});
Find ElementJavaScript
const user = users.find(u => u.id === 123); const index = nums.findIndex(n => n > 10);
Unique ValuesJavaScript
const unique = [...new Set(arr)]; const uniqueById = [...new Map( items.map(i => [i.id, i]) ).values()];

Strings & Text

Parse, format, search, split, join, and transform strings.

Split & JoinJavaScript
const words = str.split(' '); const csv = arr.join(','); const slug = title.toLowerCase().split(' ').join('-');
String FormatPython
msg = f"Hello, {name}!" formatted = "{:.2f}".format(3.14159) padded = str(num).zfill(5) # "00042"
Trim & CaseJavaScript
const trimmed = str.trim(); const lower = str.toLowerCase(); const upper = str.toUpperCase();
String ReplacePHP
$new = str_replace('old', 'new', $str); $clean = preg_replace('/\s+/', ' ', $str);
SubstringJavaScript
const sub = str.substring(0, 10); const last = str.slice(-5); const excerpt = str.slice(0, 100) + '...';
Check ContainsPython
if 'hello' in text: print('Found!') starts = text.startswith('http') ends = text.endswith('.txt')

Date & Time

Format dates, calculate differences, parse timestamps, handle timezones.

Current DateJavaScript
const now = new Date(); const timestamp = Date.now(); const iso = now.toISOString();
Format DatePython
from datetime import datetime now = datetime.now() formatted = now.strftime('%Y-%m-%d %H:%M:%S')
Date FormattingPHP
$date = date('Y-m-d H:i:s'); $formatted = date('F j, Y', strtotime($date)); $timestamp = strtotime('+1 week');
Date DifferenceJavaScript
const diff = date2 - date1; const days = Math.floor(diff / (1000 * 60 * 60 * 24)); const hours = Math.floor(diff / (1000 * 60 * 60));
Parse DatePython
from datetime import datetime dt = datetime.strptime('2024-01-15', '%Y-%m-%d') dt = datetime.fromisoformat('2024-01-15T10:30:00')
Add TimePython
from datetime import timedelta future = now + timedelta(days=7) past = now - timedelta(hours=24)

API & HTTP

Make HTTP requests, fetch data, handle responses and errors.

Fetch GETJavaScript
const res = await fetch('/api/users'); const data = await res.json(); if (!res.ok) throw new Error(data.message);
Fetch POSTJavaScript
const res = await fetch('/api/users', { method: 'POST', headers: {'Content-Type': 'application/json'}, body: JSON.stringify({ name: 'John' }) });
RequestsPython
import requests r = requests.get(url, params={'key': 'value'}) r = requests.post(url, json={'name': 'John'}) data = r.json()
cURLPHP
$ch = curl_init($url); curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); $response = curl_exec($ch); curl_close($ch);
HTTP GETGo
resp, err := http.Get(url) if err != nil { return err } defer resp.Body.Close() body, _ := io.ReadAll(resp.Body)
Error HandlingJavaScript
try { const res = await fetch(url); if (!res.ok) throw new Error(`HTTP ${res.status}`); return await res.json(); } catch (e) { console.error(e); }

File Operations

Read, write, append, and manipulate files and directories.

Read FilePython
with open('file.txt', 'r') as f: content = f.read() # or line by line lines = f.readlines()
Write FilePython
with open('file.txt', 'w') as f: f.write('Hello World') # append mode with open('file.txt', 'a') as f: f.write('\nNew line')
Read/WriteNode.js
const fs = require('fs'); const data = fs.readFileSync('file.txt', 'utf8'); fs.writeFileSync('out.txt', content);
File OperationsPHP
$content = file_get_contents('file.txt'); file_put_contents('out.txt', $data); $lines = file('file.txt', FILE_IGNORE_NEW_LINES);
Check ExistsPython
import os exists = os.path.exists('file.txt') is_file = os.path.isfile('file.txt') is_dir = os.path.isdir('folder')
List DirectoryPython
import os files = os.listdir('.') # with glob pattern from glob import glob py_files = glob('*.py')

JSON & Data

Parse, stringify, and manipulate JSON data structures.

Parse & StringifyJavaScript
const obj = JSON.parse(jsonStr); const str = JSON.stringify(obj); // pretty print const pretty = JSON.stringify(obj, null, 2);
JSON HandlingPython
import json data = json.loads(json_str) json_str = json.dumps(data, indent=2) # with file with open('data.json') as f: data = json.load(f)
JSON Encode/DecodePHP
$arr = json_decode($json, true); $json = json_encode($arr, JSON_PRETTY_PRINT); // check for errors if (json_last_error() !== JSON_ERROR_NONE) {}
Safe AccessJavaScript
// optional chaining const city = user?.address?.city; // nullish coalescing const name = user?.name ?? 'Unknown';
Deep CloneJavaScript
const clone = JSON.parse(JSON.stringify(obj)); // modern way const clone = structuredClone(obj);
Merge ObjectsJavaScript
const merged = { ...obj1, ...obj2 }; const merged = Object.assign({}, obj1, obj2);

Regular Expressions

Pattern matching, search, replace, and validation with regex.

Email ValidationJavaScript
const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/; const isValid = emailRegex.test(email);
Find All MatchesPython
import re numbers = re.findall(r'\d+', text) emails = re.findall(r'[\w.]+@[\w.]+', text)
Replace PatternJavaScript
const clean = str.replace(/\s+/g, ' '); const noDigits = str.replace(/\d/g, ''); const masked = phone.replace(/(\d{3})\d{4}/, '$1****');
Regex ReplacePHP
$result = preg_replace('/\s+/', ' ', $str); $clean = preg_replace('/[^a-zA-Z0-9]/', '', $str);
URL ValidationJavaScript
const urlRegex = /^https?:\/\/[\w.-]+\.\w{2,}/; const isUrl = urlRegex.test(url);
Extract GroupsPython
match = re.search(r'(\d{4})-(\d{2})-(\d{2})', text) if match: year, month, day = match.groups()

Numbers & Math

Mathematical operations, random numbers, and number formatting.

Random NumberJavaScript
const rand = Math.random(); // 0-1 const int = Math.floor(Math.random() * 100); const inRange = Math.floor(Math.random() * (max - min + 1)) + min;
Round NumbersJavaScript
Math.round(3.5); // 4 Math.floor(3.9); // 3 Math.ceil(3.1); // 4 num.toFixed(2); // "3.14"
Number FormatJavaScript
const formatted = num.toLocaleString(); // "1,234,567.89" const currency = num.toLocaleString('en-US', { style: 'currency', currency: 'USD' });
Min/MaxJavaScript
const max = Math.max(...arr); const min = Math.min(...arr); const clamped = Math.min(Math.max(num, min), max);
Number FormatPHP
$formatted = number_format(1234.56, 2); // "1,234.56" $rounded = round(3.14159, 2); // 3.14
Parse NumbersJavaScript
const int = parseInt('42', 10); const float = parseFloat('3.14'); const num = Number('42'); // or +str

Explore More Snippets

Browse code snippets organized by programming language.

Browse by Language