20-bo'lim: Amaliy masalalar (parsing, formatting)¶
π Kundalik ishda uchraydigan utilita funksiyalar. Yana bir bor β tilning tayyor vositalari ko'pincha qo'lda yozishdan yaxshiroq va xavfsizroq.
209. Minglik ajratuvchi bilan formatlash¶
β± O(d) β d: raqamlar soni.
Har tilda tayyor vosita: JS toLocaleString, PHP number_format, Python f-string :,.
JS
const formatNumber = n => n.toLocaleString("en-US");
// qo'lda: String(n).replace(/\B(?=(\d{3})+(?!\d))/g, ",")
210. Slugify (matn β URL slug)¶
β± O(n)
Kichik harf β maxsus belgilarni olib tashlash β bo'shliq/tirelarni bitta tirega β chetdagilarni kesish. (Lotin bo'lmagan harflar uchun transliteratsiya kerak.)
JS
const slugify = text =>
text.toLowerCase().trim()
.replace(/[^a-z0-9\s-]/g, "")
.replace(/[\s-]+/g, "-")
.replace(/^-+|-+$/g, "");
function slugify($text): string {
$text = strtolower(trim($text));
$text = preg_replace('/[^a-z0-9\s-]/', '', $text);
$text = preg_replace('/[\s-]+/', '-', $text);
return trim($text, '-');
}
import re
def slugify(text):
text = text.lower().strip()
text = re.sub(r"[^a-z0-9\s-]", "", text)
text = re.sub(r"[\s-]+", "-", text)
return text.strip("-")
211. Query string'ni parse qilish¶
β± O(n)
Tayyor vositalar β JS URLSearchParams, PHP parse_str, Python parse_qs (u har kalitga ro'yxat beradi, shuning uchun [0]).
JS
PHP Pythonfrom urllib.parse import parse_qs
def parse_query(qs):
return {k: v[0] for k, v in parse_qs(qs).items()}
212. Baytlarni o'qishli formatga (human-readable)¶
β± O(1)
1024 asosli logarifm orqali mos birlikni tanlaymiz (1536 β "1.5 KB").
JS
const formatBytes = bytes => {
if (bytes === 0) return "0 B";
const units = ["B", "KB", "MB", "GB", "TB"];
const i = Math.floor(Math.log(bytes) / Math.log(1024));
return (bytes / 1024 ** i).toFixed(1) + " " + units[i];
};
function formatBytes($bytes): string {
if ($bytes === 0) return "0 B";
$units = ["B", "KB", "MB", "GB", "TB"];
$i = (int) floor(log($bytes) / log(1024));
return round($bytes / (1024 ** $i), 1) . " " . $units[$i];
}
import math
def format_bytes(num_bytes):
if num_bytes == 0:
return "0 B"
units = ["B", "KB", "MB", "GB", "TB"]
i = int(math.floor(math.log(num_bytes, 1024)))
return f"{num_bytes / 1024 ** i:.1f} {units[i]}"
213. Integer β Roman raqam¶
β± O(1) (cheklangan jadval)
Kattadan kichikka β har qiymatni imkon qadar ayirib, mos belgini qo'shamiz (greedy). 1994 β "MCMXCIV".
JS
const toRoman = num => {
const map = [
[1000, "M"], [900, "CM"], [500, "D"], [400, "CD"],
[100, "C"], [90, "XC"], [50, "L"], [40, "XL"],
[10, "X"], [9, "IX"], [5, "V"], [4, "IV"], [1, "I"],
];
let result = "";
for (const [value, symbol] of map) {
while (num >= value) { result += symbol; num -= value; }
}
return result;
};
function toRoman($num): string {
$map = [
1000 => "M", 900 => "CM", 500 => "D", 400 => "CD",
100 => "C", 90 => "XC", 50 => "L", 40 => "XL",
10 => "X", 9 => "IX", 5 => "V", 4 => "IV", 1 => "I",
];
$result = "";
foreach ($map as $value => $symbol) {
while ($num >= $value) { $result .= $symbol; $num -= $value; }
}
return $result;
}
def to_roman(num):
mapping = [
(1000, "M"), (900, "CM"), (500, "D"), (400, "CD"),
(100, "C"), (90, "XC"), (50, "L"), (40, "XL"),
(10, "X"), (9, "IX"), (5, "V"), (4, "IV"), (1, "I"),
]
result = []
for value, symbol in mapping:
while num >= value:
result.append(symbol)
num -= value
return "".join(result)
214. Title case (har so'z bosh harfi katta)¶
β± O(n)
Tayyor vositalar β PHP ucwords, Python str.title(); JS'da regex bilan har so'z boshini katta qilamiz.
JS
PHP Python215. Matnni qisqartirish (truncate + "β¦")¶
β± O(n)
PHP'da mb_ funksiyalari UTF-8 (ko'p baytli) matn uchun zarur β oddiy substr o'zbekcha harflarni buzishi mumkin.
JS
PHPfunction truncate($s, $max): string {
return mb_strlen($s) <= $max ? $s : rtrim(mb_substr($s, 0, $max)) . "β¦";
}
216. Tasodifiy parol generatsiya¶
β± O(n)
β οΈ Xavfsizlik: PHP random_int va Python secrets kriptografik xavfsiz; JS Math.random esa emas β jiddiy holatlarda crypto.getRandomValues ishlating.
JS
const randomPassword = (length = 12) => {
const chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789!@#$%";
let result = "";
for (let i = 0; i < length; i++) {
result += chars[Math.floor(Math.random() * chars.length)];
}
return result;
};
function randomPassword(int $length = 12): string {
$chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789!@#$%";
$result = "";
$max = strlen($chars) - 1;
for ($i = 0; $i < $length; $i++) {
$result .= $chars[random_int(0, $max)];
}
return $result;
}
import secrets
def random_password(length=12):
chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789!@#$%"
return "".join(secrets.choice(chars) for _ in range(length))