Tarkibga o'tish

20-bo'lim: Amaliy masalalar (parsing, formatting)

↑ Mundarijaga qaytish

πŸ›  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, ",")
PHP
function formatNumber($n): string {
    return number_format($n);
}
Python
def format_number(n):
    return f"{n:,}"

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, "");
PHP
function slugify($text): string {
    $text = strtolower(trim($text));
    $text = preg_replace('/[^a-z0-9\s-]/', '', $text);
    $text = preg_replace('/[\s-]+/', '-', $text);
    return trim($text, '-');
}
Python
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

const parseQuery = qs => Object.fromEntries(new URLSearchParams(qs));
PHP
function parseQuery($qs): array {
    parse_str($qs, $result);
    return $result;
}
Python
from 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];
};
PHP
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];
}
Python
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;
};
PHP
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;
}
Python
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

const titleCase = s =>
  s.toLowerCase().replace(/\b\w/g, c => c.toUpperCase());
PHP
function titleCase($s): string {
    return ucwords(strtolower($s));
}
Python
def title_case(s):
    return s.title()

215. 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

const truncate = (s, max) =>
  s.length <= max ? s : s.slice(0, max).trimEnd() + "…";
PHP
function truncate($s, $max): string {
    return mb_strlen($s) <= $max ? $s : rtrim(mb_substr($s, 0, $max)) . "…";
}
Python
def truncate(s, max_len):
    return s if len(s) <= max_len else s[:max_len].rstrip() + "…"

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;
};
PHP
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;
}
Python
import secrets

def random_password(length=12):
    chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789!@#$%"
    return "".join(secrets.choice(chars) for _ in range(length))