Find code snippets organized by common programming tasks and patterns.
Filter, map, reduce, sort, find, and manipulate arrays across languages.
const evens = nums.filter(n => n % 2 === 0);
const adults = users.filter(u => u.age >= 18);squares = [x**2 for x in nums]
names = [user['name'] for user in users]sort($arr); // ascending
usort($users, fn($a, $b) => $a['age'] - $b['age']);const sum = nums.reduce((a, b) => a + b, 0);
const grouped = items.reduce((acc, item) => {
(acc[item.type] ||= []).push(item);
return acc;
}, {});const user = users.find(u => u.id === 123);
const index = nums.findIndex(n => n > 10);const unique = [...new Set(arr)];
const uniqueById = [...new Map(
items.map(i => [i.id, i])
).values()];Parse, format, search, split, join, and transform strings.
const words = str.split(' ');
const csv = arr.join(',');
const slug = title.toLowerCase().split(' ').join('-');msg = f"Hello, {name}!"
formatted = "{:.2f}".format(3.14159)
padded = str(num).zfill(5) # "00042"const trimmed = str.trim();
const lower = str.toLowerCase();
const upper = str.toUpperCase();$new = str_replace('old', 'new', $str);
$clean = preg_replace('/\s+/', ' ', $str);const sub = str.substring(0, 10);
const last = str.slice(-5);
const excerpt = str.slice(0, 100) + '...';if 'hello' in text:
print('Found!')
starts = text.startswith('http')
ends = text.endswith('.txt')Format dates, calculate differences, parse timestamps, handle timezones.
const now = new Date();
const timestamp = Date.now();
const iso = now.toISOString();from datetime import datetime
now = datetime.now()
formatted = now.strftime('%Y-%m-%d %H:%M:%S')$date = date('Y-m-d H:i:s');
$formatted = date('F j, Y', strtotime($date));
$timestamp = strtotime('+1 week');const diff = date2 - date1;
const days = Math.floor(diff / (1000 * 60 * 60 * 24));
const hours = Math.floor(diff / (1000 * 60 * 60));from datetime import datetime
dt = datetime.strptime('2024-01-15', '%Y-%m-%d')
dt = datetime.fromisoformat('2024-01-15T10:30:00')from datetime import timedelta
future = now + timedelta(days=7)
past = now - timedelta(hours=24)Make HTTP requests, fetch data, handle responses and errors.
const res = await fetch('/api/users');
const data = await res.json();
if (!res.ok) throw new Error(data.message);const res = await fetch('/api/users', {
method: 'POST',
headers: {'Content-Type': 'application/json'},
body: JSON.stringify({ name: 'John' })
});import requests
r = requests.get(url, params={'key': 'value'})
r = requests.post(url, json={'name': 'John'})
data = r.json()$ch = curl_init($url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$response = curl_exec($ch);
curl_close($ch);resp, err := http.Get(url)
if err != nil { return err }
defer resp.Body.Close()
body, _ := io.ReadAll(resp.Body)try {
const res = await fetch(url);
if (!res.ok) throw new Error(`HTTP ${res.status}`);
return await res.json();
} catch (e) { console.error(e); }Read, write, append, and manipulate files and directories.
with open('file.txt', 'r') as f:
content = f.read()
# or line by line
lines = f.readlines()with open('file.txt', 'w') as f:
f.write('Hello World')
# append mode
with open('file.txt', 'a') as f:
f.write('\nNew line')const fs = require('fs');
const data = fs.readFileSync('file.txt', 'utf8');
fs.writeFileSync('out.txt', content);$content = file_get_contents('file.txt');
file_put_contents('out.txt', $data);
$lines = file('file.txt', FILE_IGNORE_NEW_LINES);import os
exists = os.path.exists('file.txt')
is_file = os.path.isfile('file.txt')
is_dir = os.path.isdir('folder')import os
files = os.listdir('.')
# with glob pattern
from glob import glob
py_files = glob('*.py')Parse, stringify, and manipulate JSON data structures.
const obj = JSON.parse(jsonStr);
const str = JSON.stringify(obj);
// pretty print
const pretty = JSON.stringify(obj, null, 2);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)$arr = json_decode($json, true);
$json = json_encode($arr, JSON_PRETTY_PRINT);
// check for errors
if (json_last_error() !== JSON_ERROR_NONE) {}// optional chaining
const city = user?.address?.city;
// nullish coalescing
const name = user?.name ?? 'Unknown';const clone = JSON.parse(JSON.stringify(obj));
// modern way
const clone = structuredClone(obj);const merged = { ...obj1, ...obj2 };
const merged = Object.assign({}, obj1, obj2);Pattern matching, search, replace, and validation with regex.
const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
const isValid = emailRegex.test(email);import re
numbers = re.findall(r'\d+', text)
emails = re.findall(r'[\w.]+@[\w.]+', text)const clean = str.replace(/\s+/g, ' ');
const noDigits = str.replace(/\d/g, '');
const masked = phone.replace(/(\d{3})\d{4}/, '$1****');$result = preg_replace('/\s+/', ' ', $str);
$clean = preg_replace('/[^a-zA-Z0-9]/', '', $str);const urlRegex = /^https?:\/\/[\w.-]+\.\w{2,}/;
const isUrl = urlRegex.test(url);match = re.search(r'(\d{4})-(\d{2})-(\d{2})', text)
if match:
year, month, day = match.groups()Mathematical operations, random numbers, and number formatting.
const rand = Math.random(); // 0-1
const int = Math.floor(Math.random() * 100);
const inRange = Math.floor(Math.random() * (max - min + 1)) + min;Math.round(3.5); // 4
Math.floor(3.9); // 3
Math.ceil(3.1); // 4
num.toFixed(2); // "3.14"const formatted = num.toLocaleString();
// "1,234,567.89"
const currency = num.toLocaleString('en-US', {
style: 'currency', currency: 'USD'
});const max = Math.max(...arr);
const min = Math.min(...arr);
const clamped = Math.min(Math.max(num, min), max);$formatted = number_format(1234.56, 2);
// "1,234.56"
$rounded = round(3.14159, 2); // 3.14const int = parseInt('42', 10);
const float = parseFloat('3.14');
const num = Number('42'); // or +str