π Mundarija#
- ES8+ Asosiy Yangiliklari
- For Loop ning Ilg'or Usullari
- Senior Darajadagi Funksiyalar
- Async/Await va Promise Musterilari
- Performance Optimizatsiya
- Real Loyiha Misollari
π₯ ES8+ Asosiy Yangiliklari#
1. Object.entries() va Object.values()#
javascript
// Eski usul (ES5/ES6)
const user = { name: 'John', age: 30, city: 'Tashkent' };
for (let key in user) {
if (user.hasOwnProperty(key)) {
console.log(key, user[key]);
}
}
// ES8 ilg'or usuli
Object.entries(user).forEach(([key, value]) => {
console.log(`${key}: ${value}`);
});
// Object.values() - faqat qiymatlar
const values = Object.values(user); // ['John', 30, 'Tashkent']
// Real misol: Ma'lumotlarni transformatsiya qilish
const transformData = (obj) => {
return Object.entries(obj).reduce((acc, [key, value]) => {
acc[key.toUpperCase()] = typeof value === 'string'
? value.toUpperCase()
: value;
return acc;
}, {});
};
2. String.padStart() va String.padEnd()#
javascript
// Raqamlarni formatlash
const formatId = (id, length = 8) => {
return String(id).padStart(length, '0');
};
console.log(formatId(42)); // "00000042"
console.log(formatId(1234)); // "00001234"
// Jadval yaratish
const createTable = (data) => {
const headers = ['Name', 'Age', 'City'];
const rows = data.map(item =>
headers.map(header =>
String(item[header.toLowerCase()]).padEnd(15)
).join(' | ')
);
return [headers.join(' | '), ...rows].join('\n');
};
3. Object.getOwnPropertyDescriptors()#
javascript
// Murakkab obyekt konfiguratsiyasi
const createImmutableObject = (obj) => {
const descriptors = Object.getOwnPropertyDescriptors(obj);
Object.keys(descriptors).forEach(key => {
descriptors[key].writable = false;
descriptors[key].configurable = false;
});
return Object.create(null, descriptors);
};
// Deep clone with descriptors
const deepCloneWithDescriptors = (obj) => {
const clone = Array.isArray(obj) ? [] : {};
const descriptors = Object.getOwnPropertyDescriptors(obj);
for (let [key, descriptor] of Object.entries(descriptors)) {
if (descriptor.value && typeof descriptor.value === 'object') {
descriptor.value = deepCloneWithDescriptors(descriptor.value);
}
Object.defineProperty(clone, key, descriptor);
}
return clone;
};
4. Async/Await (ES8) va Undan Keyingi#
javascript
// Senior darajadagi async/await patternlari
class AsyncDataProcessor {
constructor(config) {
this.config = config;
this.cache = new Map();
this.retryCount = 3;
}
// Retry mexanizmi
async retryOperation(fn, retries = this.retryCount) {
try {
return await fn();
} catch (error) {
if (retries === 0) throw error;
console.log(`Retrying... (${retries} attempts left)`);
await this.sleep(1000 * (this.retryCount - retries + 1));
return this.retryOperation(fn, retries - 1);
}
}
// Parallel va ketma-ket ishlov berish
async processBatch(items, processor, concurrency = 5) {
const results = [];
const batches = this.chunkArray(items, concurrency);
for (const batch of batches) {
const batchResults = await Promise.all(
batch.map(item => this.retryOperation(() => processor(item)))
);
results.push(...batchResults);
}
return results;
}
// Kesh bilan ishlash
async getDataWithCache(key, fetcher, ttl = 300000) {
const cached = this.cache.get(key);
if (cached && Date.now() - cached.timestamp < ttl) {
return cached.data;
}
const data = await this.retryOperation(fetcher);
this.cache.set(key, { data, timestamp: Date.now() });
return data;
}
// Utility funksiyalar
sleep(ms) {
return new Promise(resolve => setTimeout(resolve, ms));
}
chunkArray(arr, size) {
return Array.from(
{ length: Math.ceil(arr.length / size) },
(_, i) => arr.slice(i * size, i * size + size)
);
}
}
// Real foydalanish
const processor = new AsyncDataProcessor({
timeout: 5000,
maxRetries: 3
});
// API dan ma'lumot olish
const fetchUserData = async (userId) => {
return processor.getDataWithCache(
`user_${userId}`,
async () => {
const response = await fetch(`/api/users/${userId}`);
if (!response.ok) throw new Error('Network error');
return response.json();
},
60000 // 1 daqiqa kesh
);
};
π For Loop ning Ilg'or Usullari#
1. For...of bilan Iteratorlar#
javascript
// Iterator yaratish
class DataStream {
constructor(data) {
this.data = data;
this.index = 0;
}
*[Symbol.iterator]() {
for (let i = 0; i < this.data.length; i++) {
yield this.processItem(this.data[i]);
}
}
processItem(item) {
return {
original: item,
processed: item * 2,
timestamp: Date.now()
};
}
}
// Async iterator
class AsyncDataStream {
constructor(urls) {
this.urls = urls;
}
async *[Symbol.asyncIterator]() {
for (const url of this.urls) {
const response = await fetch(url);
const data = await response.json();
yield data;
}
}
}
// Foydalanish
const stream = new DataStream([1, 2, 3, 4, 5]);
for (const item of stream) {
console.log(item);
}
// Async iterator
const asyncStream = new AsyncDataStream([
'/api/data1',
'/api/data2',
'/api/data3'
]);
for await (const data of asyncStream) {
console.log('Received:', data);
}
2. Map, Filter, Reduce - For Loop o'rniga#
javascript
// Murakkab transformatsiyalar
const complexTransformation = (data) => {
return data
.map(item => ({
...item,
total: item.price * item.quantity,
discount: item.price * item.quantity * 0.1
}))
.filter(item => item.total > 100)
.reduce((acc, item) => {
acc.totalRevenue += item.total;
acc.totalDiscount += item.discount;
acc.items.push({
id: item.id,
name: item.name,
finalPrice: item.total - item.discount
});
return acc;
}, {
totalRevenue: 0,
totalDiscount: 0,
items: []
});
};
// Pipeline pattern
const createPipeline = (...fns) => (input) =>
fns.reduce((acc, fn) => fn(acc), input);
// For loop bilan pipeline
const pipeline = createPipeline(
data => data.filter(item => item.active),
data => data.map(item => ({ ...item, processed: true })),
data => data.sort((a, b) => a.priority - b.priority),
data => data.reduce((acc, item) => {
acc[item.category] = acc[item.category] || [];
acc[item.category].push(item);
return acc;
}, {})
);
3. Generatorlar bilan For Loop#
javascript
// Cheksiz ketma-ketliklar
function* fibonacciGenerator() {
let prev = 0, curr = 1;
while (true) {
yield curr;
[prev, curr] = [curr, prev + curr];
}
}
// Take n ta element
function* take(iterator, n) {
let count = 0;
for (const value of iterator) {
if (count++ >= n) break;
yield value;
}
}
// Filter generator
function* filter(iterator, predicate) {
for (const value of iterator) {
if (predicate(value)) {
yield value;
}
}
}
// Map generator
function* map(iterator, transform) {
for (const value of iterator) {
yield transform(value);
}
}
// Real misol: Katta datasetni qayta ishlash
function* processLargeDataset(dataset) {
let batch = [];
for (const item of dataset) {
batch.push(item);
if (batch.length === 1000) {
yield batch;
batch = [];
}
}
if (batch.length > 0) yield batch;
}
// Streaming ma'lumotlarni qayta ishlash
const streamProcessor = (dataStream) => {
const generator = processLargeDataset(dataStream);
for (const batch of generator) {
// Har bir batch ni parallel qayta ishlash
const results = batch.map(item => heavyOperation(item));
yield results;
}
};
π― Senior Darajadagi Funksiyalar#
1. Currying va Partial Application#
javascript
// Currying
const curry = (fn) => {
const curried = (...args) => {
if (args.length >= fn.length) {
return fn(...args);
}
return (...more) => curried(...args, ...more);
};
return curried;
};
// Real misol: API so'rovlari
const apiRequest = curry((method, url, data, headers) => {
return fetch(url, {
method,
headers: { 'Content-Type': 'application/json', ...headers },
body: data ? JSON.stringify(data) : undefined
});
});
// Preconfigured funksiyalar
const getRequest = apiRequest('GET');
const postRequest = apiRequest('POST');
const getUserData = getRequest('/api/users');
const createUser = postRequest('/api/users');
// Composition
const compose = (...fns) => (x) =>
fns.reduceRight((acc, fn) => fn(acc), x);
const pipe = (...fns) => (x) =>
fns.reduce((acc, fn) => fn(acc), x);
// Real composition misoli
const processUserData = pipe(
validateUser,
enrichUserData,
formatUserResponse,
cacheUserData
);
2. Memoization va Kesh#
javascript
class AdvancedMemoization {
constructor(options = {}) {
this.cache = new Map();
this.ttl = options.ttl || 300000; // 5 daqiqa
this.maxSize = options.maxSize || 1000;
}
memoize(fn, keyGenerator = null) {
return (...args) => {
const key = keyGenerator
? keyGenerator(...args)
: JSON.stringify(args);
const cached = this.cache.get(key);
if (cached && Date.now() - cached.timestamp < this.ttl) {
return cached.value;
}
const result = fn(...args);
this.cache.set(key, {
value: result,
timestamp: Date.now()
});
// Keshni tozalash
if (this.cache.size > this.maxSize) {
const oldest = Array.from(this.cache.entries())
.sort((a, b) => a[1].timestamp - b[1].timestamp)[0];
this.cache.delete(oldest[0]);
}
return result;
};
}
// WeakMap bilan memoization
static weakMemoize(fn) {
const cache = new WeakMap();
return (obj) => {
if (!cache.has(obj)) {
cache.set(obj, fn(obj));
}
return cache.get(obj);
};
}
}
// Fibonacci optimizatsiyasi
const fib = (n) => {
if (n <= 1) return n;
return fib(n - 1) + fib(n - 2);
};
const memoizedFib = new AdvancedMemoization().memoize(fib);
3. Decorator Pattern#
javascript
// Funksiya dekoratorlari
const decorators = {
// Vaqtni o'lchash
measureTime(fn) {
return function(...args) {
const start = performance.now();
const result = fn.apply(this, args);
const end = performance.now();
console.log(`${fn.name} took ${end - start}ms`);
return result;
};
},
// Logging
log(fn) {
return function(...args) {
console.log(`Calling ${fn.name} with`, args);
const result = fn.apply(this, args);
console.log(`${fn.name} returned`, result);
return result;
};
},
// Validatsiya
validate(schema) {
return function(fn) {
return function(...args) {
const [data] = args;
const errors = [];
for (const [key, rule] of Object.entries(schema)) {
if (rule.required && !data[key]) {
errors.push(`${key} is required`);
}
if (rule.type && typeof data[key] !== rule.type) {
errors.push(`${key} must be ${rule.type}`);
}
}
if (errors.length > 0) {
throw new Error(`Validation failed: ${errors.join(', ')}`);
}
return fn.apply(this, args);
};
};
},
// Retry
retry(attempts = 3, delay = 1000) {
return function(fn) {
return async function(...args) {
let lastError;
for (let i = 0; i < attempts; i++) {
try {
return await fn.apply(this, args);
} catch (error) {
lastError = error;
if (i < attempts - 1) {
await new Promise(r => setTimeout(r, delay * (i + 1)));
}
}
}
throw lastError;
};
};
},
// Cache
cache(ttl = 300000) {
const memoizer = new AdvancedMemoization({ ttl });
return (fn) => memoizer.memoize(fn);
}
};
// Dekoratorlarni qo'llash
class UserService {
@decorators.measureTime
@decorators.log
@decorators.validate({ name: { required: true, type: 'string' } })
createUser(data) {
return { id: Date.now(), ...data };
}
@decorators.retry(3, 2000)
@decorators.cache(60000)
async getUser(id) {
const response = await fetch(`/api/users/${id}`);
return response.json();
}
}
β‘ Performance Optimizatsiya#
1. Stream va Chunk Processing#
javascript
class StreamProcessor {
constructor(options = {}) {
this.chunkSize = options.chunkSize || 1000;
this.parallel = options.parallel || 5;
}
// Katta datasetni qayta ishlash
async processLargeDataset(data, processor) {
const chunks = this.createChunks(data);
const results = [];
for (let i = 0; i < chunks.length; i += this.parallel) {
const batch = chunks.slice(i, i + this.parallel);
const batchResults = await Promise.all(
batch.map(chunk => this.processChunk(chunk, processor))
);
results.push(...batchResults);
}
return results;
}
createChunks(data) {
const chunks = [];
for (let i = 0; i < data.length; i += this.chunkSize) {
chunks.push(data.slice(i, i + this.chunkSize));
}
return chunks;
}
async processChunk(chunk, processor) {
// Web Workers yoki parallel ishlov
return chunk.map(processor);
}
// Streaming response
async *streamResponse(url) {
const response = await fetch(url);
const reader = response.body.getReader();
const decoder = new TextDecoder();
while (true) {
const { done, value } = await reader.read();
if (done) break;
const chunk = decoder.decode(value);
yield this.parseChunk(chunk);
}
}
parseChunk(chunk) {
// Chunk ni JSON yoki boshqa formatga o'tkazish
try {
return JSON.parse(chunk);
} catch {
return chunk;
}
}
}
2. Lazy Evaluation#
javascript
class Lazy {
constructor(fn) {
this.fn = fn;
this.value = null;
this.computed = false;
}
get() {
if (!this.computed) {
this.value = this.fn();
this.computed = true;
}
return this.value;
}
// Lazy property
static lazy(proto, key, descriptor) {
const fn = descriptor.initializer();
return {
configurable: true,
enumerable: true,
get() {
const value = fn.call(this);
Object.defineProperty(this, key, {
value,
configurable: false,
enumerable: true
});
return value;
}
};
}
}
// Real misol
class DataLoader {
@Lazy.lazy
get expensiveData() {
console.log('Computing expensive data...');
return this.loadData();
}
@Lazy.lazy
get config() {
return this.loadConfig();
}
loadData() {
// Og'ir hisoblash
return Array.from({ length: 1000000 }, (_, i) => i);
}
loadConfig() {
return {
api: 'https://api.example.com',
timeout: 5000,
retries: 3
};
}
}
π Real Loyiha Misollari#
1. Microservice Architecture#
javascript
// Service registry
class ServiceRegistry {
constructor() {
this.services = new Map();
this.discovery = new Map();
}
register(serviceName, version, instance) {
const key = `${serviceName}:${version}`;
if (!this.services.has(key)) {
this.services.set(key, []);
}
this.services.get(key).push({
instance,
heartbeat: Date.now(),
healthy: true
});
}
async discover(serviceName, version = 'latest') {
const services = Array.from(this.services.entries())
.filter(([key]) => key.startsWith(serviceName))
.sort((a, b) => {
const vA = a[0].split(':')[1];
const vB = b[0].split(':')[1];
return vB.localeCompare(vA);
});
if (version === 'latest') {
return services[0]?.[1] || [];
}
const key = `${serviceName}:${version}`;
return this.services.get(key) || [];
}
healthCheck(serviceName, version) {
const key = `${serviceName}:${version}`;
const instances = this.services.get(key);
if (!instances) return;
instances.forEach(async (service) => {
try {
const health = await service.instance.health();
service.healthy = health.status === 'healthy';
service.heartbeat = Date.now();
} catch {
service.healthy = false;
}
});
}
}
// Message queue
class MessageQueue {
constructor(options = {}) {
this.queue = [];
this.processors = new Map();
this.maxSize = options.maxSize || 1000;
this.retryDelay = options.retryDelay || 5000;
}
async publish(topic, message) {
const msg = {
id: Date.now() + '-' + Math.random().toString(36),
topic,
payload: message,
timestamp: Date.now(),
attempts: 0
};
this.queue.push(msg);
if (this.queue.length > this.maxSize) {
this.queue.shift(); // Old ma'lumotlarni o'chiramiz
}
await this.process(msg);
}
async process(message) {
const processor = this.processors.get(message.topic);
if (!processor) return;
try {
await processor(message.payload);
} catch (error) {
message.attempts++;
if (message.attempts < 3) {
setTimeout(() => this.process(message), this.retryDelay);
} else {
console.error('Message failed:', message.id, error);
// Dead letter queue ga yuborish
await this.publish('dead-letter', message);
}
}
}
subscribe(topic, handler) {
this.processors.set(topic, handler);
}
}
2. Data Pipeline#
javascript
class DataPipeline {
constructor(config = {}) {
this.stages = [];
this.errorHandlers = [];
this.batchSize = config.batchSize || 100;
this.parallel = config.parallel || 4;
}
stage(name, processor) {
this.stages.push({ name, processor });
return this;
}
onError(handler) {
this.errorHandlers.push(handler);
return this;
}
async execute(data) {
let result = data;
for (const stage of this.stages) {
try {
if (Array.isArray(result)) {
// Batch processing
const batches = this.chunkArray(result, this.batchSize);
const promises = batches.map(batch =>
this.processBatch(batch, stage)
);
const batchResults = await Promise.all(promises);
result = batchResults.flat();
} else {
result = await stage.processor(result);
}
} catch (error) {
for (const handler of this.errorHandlers) {
await handler(error, stage.name, result);
}
throw error;
}
}
return result;
}
async processBatch(batch, stage) {
if (this.parallel > 1 && Array.isArray(batch)) {
const chunks = this.chunkArray(batch, Math.ceil(batch.length / this.parallel));
const results = await Promise.all(
chunks.map(chunk => stage.processor(chunk))
);
return results.flat();
}
return stage.processor(batch);
}
chunkArray(arr, size) {
const chunks = [];
for (let i = 0; i < arr.length; i += size) {
chunks.push(arr.slice(i, i + size));
}
return chunks;
}
}
// Real pipeline misoli
const pipeline = new DataPipeline({ batchSize: 50, parallel: 3 });
pipeline
.stage('validate', (data) => {
return data.filter(item => item.id && item.name);
})
.stage('enrich', async (data) => {
const enriched = await Promise.all(data.map(async (item) => {
const extra = await fetchExtraData(item.id);
return { ...item, ...extra };
}));
return enriched;
})
.stage('transform', (data) => {
return data.map(item => ({
id: item.id,
name: item.name.toUpperCase(),
fullName: `${item.firstName} ${item.lastName}`,
total: item.price * item.quantity
}));
})
.stage('aggregate', (data) => {
return data.reduce((acc, item) => {
acc.total += item.total;
acc.count++;
acc.items.push(item);
return acc;
}, { total: 0, count: 0, items: [] });
})
.onError((error, stage, data) => {
console.error(`Error at stage ${stage}:`, error);
// Error haqida log yozish
logError(error, stage, data);
});
// Foydalanish
const result = await pipeline.execute(rawData);
π― Xulosa#
JavaScript da senior darajadagi dasturlar yozish uchun:
- ES8+ imkoniyatlarini to'liq o'zlashtiring
- Async/Await va Promise larni mukammal biling
- For loop larni transformatsiya, pipeline va generatorlar bilan almashtiring
- Functional programming usullarini qo'llang
- Performance optimizatsiya ga e'tibor bering
- Clean code va design patterns dan foydalaning
- Error handling va logging ni to'g'ri tashkil eting
π Qo'shimcha Tavsiyalar#
- Har doim TypeScript dan foydalaning (type safety uchun)
- ESLint va Prettier ni ishlating
- Jest yoki Mocha bilan test yozing
- Webpack yoki Vite bilan build processni optimallashtiring
- Performance monitoring (Lighthouse, Web Vitals) dan foydalaning
π Ushbu postni do'stlaringiz bilan ulashing va JavaScript mahoratingizni oshiring!
#JavaScript #ES8 #WebDevelopment #SeniorDeveloper #Coding #Programming

No comments yet.