Data Analytics
27K subscribers
1.17K photos
24 videos
26 files
979 links
Dive into the world of Data Analytics – uncover insights, explore trends, and master data-driven decision making.
Download Telegram
Data Analytics
# πŸ“š JavaScript Tutorial - Part 7/10: Object-Oriented JavaScript & Prototypes #JavaScript #OOP #Prototypes #Classes #DesignPatterns Welcome to Part 7 of our JavaScript series! This comprehensive lesson will take you deep into JavaScript's object-oriented…
# πŸ“š JavaScript Tutorial - Part 8/10: Functional Programming in JavaScript
#JavaScript #FunctionalProgramming #FP #PureFunctions #HigherOrderFunctions

Welcome to Part 8 of our JavaScript series! Today we'll explore functional programming (FP) concepts that will transform how you write JavaScript, making your code more predictable, reusable, and maintainable.

---

## πŸ”Ή Core Principles of Functional Programming
### 1. Pure Functions
// Pure function (same input β†’ same output, no side effects)
function add(a, b) {
return a + b;
}

// Impure function (side effect + depends on external state)
let taxRate = 0.1;
function calculateTax(amount) {
return amount * taxRate; // Depends on external variable
}


### 2. Immutability
// Bad (mutates original array)
const addToCart = (cart, item) => {
cart.push(item); // Mutation!
return cart;
};

// Good (returns new array)
const addToCartFP = (cart, item) => [...cart, item];


### 3. Function Composition
const compose = (...fns) => x => fns.reduceRight((v, f) => f(v), x);

const toUpperCase = str => str.toUpperCase();
const exclaim = str => `${str}!`;
const shout = compose(exclaim, toUpperCase);

shout('hello'); // "HELLO!"


---

## πŸ”Ή First-Class Functions
### 1. Functions as Arguments
const numbers = [1, 2, 3];

// Passing function as argument
numbers.map(num => num * 2); // [2, 4, 6]


### 2. Returning Functions
const createMultiplier = factor => num => num * factor;
const double = createMultiplier(2);
double(5); // 10


### 3. Storing Functions
const mathOps = {
add: (a, b) => a + b,
subtract: (a, b) => a - b
};
mathOps.add(3, 5); // 8


---

## πŸ”Ή Higher-Order Functions
### 1. Array Methods
const products = [
{ id: 1, name: 'Laptop', price: 999, inStock: true },
{ id: 2, name: 'Mouse', price: 25, inStock: false }
];

// Transform data
const productNames = products.map(p => p.name);

// Filter data
const availableProducts = products.filter(p => p.inStock);

// Reduce to single value
const totalPrice = products.reduce((sum, p) => sum + p.price, 0);


### 2. Custom HOF Example
function withLogging(fn) {
return (...args) => {
console.log(`Calling with args: ${args}`);
const result = fn(...args);
console.log(`Result: ${result}`);
return result;
};
}

const loggedAdd = withLogging(add);
loggedAdd(3, 5);


---

## πŸ”Ή Closures
Functions that remember their lexical scope.

### 1. Basic Closure
function createCounter() {
let count = 0;
return () => ++count;
}

const counter = createCounter();
counter(); // 1
counter(); // 2


### 2. Practical Use Case
function createApiClient(baseUrl) {
return {
get(endpoint) {
return fetch(`${baseUrl}${endpoint}`).then(res => res.json());
},
post(endpoint, data) {
return fetch(`${baseUrl}${endpoint}`, {
method: 'POST',
body: JSON.stringify(data)
});
}
};
}

const jsonPlaceholder = createApiClient('https://jsonplaceholder.typicode.com');
jsonPlaceholder.get('/posts/1').then(console.log);


---

## πŸ”Ή Currying
Transforming a multi-argument function into a sequence of single-argument functions.

// Regular function
const add = (a, b, c) => a + b + c;

// Curried version
const curriedAdd = a => b => c => a + b + c;
curriedAdd(1)(2)(3); // 6

// Practical example
const createUser = username => email => password => ({
username,
email,
password
});

const registerUser = createUser('js_dev');
const withEmail = registerUser('[email protected]');
const finalUser = withEmail('secure123');


---

## πŸ”Ή Recursion
### 1. Basic Recursion
function factorial(n) {
return n <= 1 ? 1 : n * factorial(n - 1);
}


### 2. Tail Call Optimization
function factorial(n, acc = 1) {
return n <= 1 ? acc : factorial(n - 1, n * acc);
}


### 3. Recursive Array Processing
function deepMap(arr, fn) {
return arr.map(item =>
Array.isArray(item) ? deepMap(item, fn) : fn(item)
);
}

deepMap([1, [2, [3]]], x => x * 2); // [2, [4, [6]]]


---
❀1
Data Analytics
# πŸ“š JavaScript Tutorial - Part 7/10: Object-Oriented JavaScript & Prototypes #JavaScript #OOP #Prototypes #Classes #DesignPatterns Welcome to Part 7 of our JavaScript series! This comprehensive lesson will take you deep into JavaScript's object-oriented…
## πŸ”Ή Practical Example: Redux-like Store
function createStore(reducer, initialState) {
let state = initialState;
const listeners = [];

const getState = () => state;

const dispatch = (action) => {
state = reducer(state, action);
listeners.forEach(listener => listener());
};

const subscribe = (listener) => {
listeners.push(listener);
return () => {
const index = listeners.indexOf(listener);
listeners.splice(index, 1);
};
};

return { getState, dispatch, subscribe };
}

// Reducer (pure function)
function counterReducer(state = 0, action) {
switch(action.type) {
case 'INCREMENT': return state + 1;
case 'DECREMENT': return state - 1;
default: return state;
}
}

// Usage
const store = createStore(counterReducer);
store.subscribe(() => console.log(store.getState()));
store.dispatch({ type: 'INCREMENT' }); // Logs: 1


---

## πŸ”Ή Best Practices
1. Strive for purity when possible
2. Limit side effects to controlled areas
3. Use immutable data with libraries like Immer
4. Compose small functions into larger ones
5. Document function signatures clearly

---

### πŸ“Œ What's Next?
In Part 9, we'll cover:
➑️ Error Handling Strategies
➑️ Debugging Techniques
➑️ Performance Optimization
➑️ Memory Management

#JavaScript #FunctionalProgramming #CleanCode πŸš€

Practice Exercise:
1. Convert an imperative function to pure FP style
2. Implement a pipe() function (left-to-right composition)
3. Create a memoization higher-order function
Data Analytics
# πŸ“š JavaScript Tutorial - Part 8/10: Functional Programming in JavaScript #JavaScript #FunctionalProgramming #FP #PureFunctions #HigherOrderFunctions Welcome to Part 8 of our JavaScript series! Today we'll explore functional programming (FP) concepts that…
# πŸ“š JavaScript Tutorial - Part 9/10: Error Handling & Debugging
#JavaScript #Debugging #ErrorHandling #Performance #BestPractices

Welcome to Part 9 of our JavaScript series! Today we'll master professional error handling, debugging techniques, and performance optimization strategies used by senior developers.

---

## πŸ”Ή Comprehensive Error Handling
### 1. Error Types in JavaScript
try {
// Potential error code
} catch (error) {
if (error instanceof TypeError) {
console.log("Type error occurred");
} else if (error instanceof ReferenceError) {
console.log("Undefined variable");
} else if (error instanceof RangeError) {
console.log("Value out of range");
} else {
console.log("Unknown error:", error.message);
}
}


### 2. Custom Error Classes
class ApiError extends Error {
constructor(url, status, message) {
super(`API call to ${url} failed with ${status}: ${message}`);
this.name = "ApiError";
this.status = status;
this.url = url;
}
}

// Usage
throw new ApiError("/users", 500, "Internal Server Error");


### 3. Error Boundary Pattern (React-like)
function ErrorBoundary({ children }) {
const [error, setError] = useState(null);

try {
return children;
} catch (err) {
setError(err);
return <FallbackUI error={error} />;
}
}

// Wrap components
<ErrorBoundary>
<UnstableComponent />
</ErrorBoundary>


---

## πŸ”Ή Advanced Debugging Techniques
### 1. Console Methods Beyond `log()`
console.table([{id: 1, name: 'Ali'}, {id: 2, name: 'Sarah'}]);

console.group("User Details");
console.log("Name: Ali");
console.log("Age: 25");
console.groupEnd();

console.time("API Call");
await fetchData();
console.timeEnd("API Call"); // Logs execution time


### 2. Debugger Statement & Breakpoints
function complexCalculation() {
debugger; // Pauses execution here
// Step through with F10/F11
const result = /* ... */;
return result;
}


### 3. Source Maps in Production
// webpack.config.js
module.exports = {
devtool: 'source-map', // Generates .map files
// ...
};


---

## πŸ”Ή Performance Optimization
### 1. Benchmarking Tools
// Using performance.now()
const start = performance.now();
expensiveOperation();
const end = performance.now();
console.log(`Operation took ${end - start}ms`);


### 2. Memory Leak Detection
Common leak patterns:
// 1. Accidental globals
function leak() {
leakedVar = 'This is global!'; // Missing var/let/const
}

// 2. Forgotten timers
const intervalId = setInterval(() => {}, 1000);
// Remember to clearInterval(intervalId)

// 3. Detached DOM references
const elements = [];
function storeElement() {
const el = document.createElement('div');
elements.push(el); // Keeps reference after removal
}


### 3. Optimization Techniques
// 1. Debounce rapid events
function debounce(fn, delay) {
let timeout;
return (...args) => {
clearTimeout(timeout);
timeout = setTimeout(() => fn(...args), delay);
};
}

// 2. Web Workers for CPU-intensive tasks
const worker = new Worker('task.js');
worker.postMessage(data);
worker.onmessage = (e) => console.log(e.data);

// 3. Virtualize long lists (react-window, etc.)


---

## πŸ”Ή Memory Management
### 1. Garbage Collection Basics
// Circular reference (modern engines handle this)
let obj1 = {};
let obj2 = { ref: obj1 };
obj1.ref = obj2;

// Manual cleanup
let heavyResource = loadResource();
function cleanup() {
heavyResource = null; // Eligible for GC
}


### 2. WeakMap & WeakSet
const weakMap = new WeakMap();
let domNode = document.getElementById('node');
weakMap.set(domNode, { clicks: 0 });

// When domNode is removed, entry is automatically GC'd


---

## πŸ”Ή Network Optimization
### 1. Bundle Analysis
npm install -g source-map-explorer
source-map-explorer bundle.js


### 2. Code Splitting
// Dynamic imports
const module = await import('./heavyModule.js');

// React.lazy
const HeavyComponent = React.lazy(() => import('./HeavyComponent'));
Data Analytics
# πŸ“š JavaScript Tutorial - Part 8/10: Functional Programming in JavaScript #JavaScript #FunctionalProgramming #FP #PureFunctions #HigherOrderFunctions Welcome to Part 8 of our JavaScript series! Today we'll explore functional programming (FP) concepts that…
### 3. Caching Strategies
// Service Worker caching
self.addEventListener('fetch', (event) => {
event.respondWith(
caches.match(event.request)
.then(response => response || fetch(event.request))
);
});


---

## πŸ”Ή Security Best Practices
### 1. Input Sanitization
function sanitizeInput(input) {
return input.replace(/</g, '&lt;').replace(/>/g, '&gt;');
}


### 2. Content Security Policy (CSP)
<meta http-equiv="Content-Security-Policy" 
content="default-src 'self'; script-src 'self' 'unsafe-inline'">


### 3. Secure Authentication
// Never store tokens in localStorage
const auth = {
getToken() {
return window.sessionStorage.getItem('token');
},
setToken(token) {
window.sessionStorage.setItem('token', token);
}
};


---

## πŸ”Ή Practical Example: Robust API Wrapper
class ApiClient {
constructor(baseUrl) {
this.baseUrl = baseUrl;
this.cache = new Map();
}

async request(endpoint, options = {}) {
const cacheKey = JSON.stringify({ endpoint, options });

try {
// Cache-first strategy
if (this.cache.has(cacheKey)) {
return this.cache.get(cacheKey);
}

const response = await fetch(`${this.baseUrl}${endpoint}`, {
headers: { 'Content-Type': 'application/json' },
...options
});

if (!response.ok) {
throw new ApiError(
endpoint,
response.status,
await response.text()
);
}

const data = await response.json();
this.cache.set(cacheKey, data); // Cache response
return data;

} catch (error) {
if (error instanceof ApiError) {
console.error(`API Error: ${error.message}`);
} else {
console.error(`Network Error: ${error.message}`);
}
throw error;
}
}
}


---

## πŸ”Ή Best Practices Checklist
1. Error Handling
- [ ] Use specific error types
- [ ] Implement global error handlers
- [ ] Validate API responses

2. Debugging
- [ ] Utilize source maps
- [ ] Leverage browser dev tools
- [ ] Add strategic debugger statements

3. Performance
- [ ] Audit bundle size regularly
- [ ] Implement lazy loading
- [ ] Debounce rapid events

4. Security
- [ ] Sanitize user input
- [ ] Use secure token storage
- [ ] Implement CSP headers

---

### πŸ“Œ What's Next?
In Final Part 10, we'll cover:
➑️ Modern JavaScript (ES2023+)
➑️ TypeScript Fundamentals
➑️ Advanced Patterns
➑️ Where to Go From Here

#JavaScript #ProfessionalDevelopment #WebDev πŸš€

Practice Exercise:
1. Implement error boundaries in a React/Vue app
2. Profile a slow function using Chrome DevTools
3. Create a memory leak and detect it
Data Analytics
# πŸ“š JavaScript Tutorial - Part 9/10: Error Handling & Debugging #JavaScript #Debugging #ErrorHandling #Performance #BestPractices Welcome to Part 9 of our JavaScript series! Today we'll master professional error handling, debugging techniques, and performance…
# πŸ“š JavaScript Tutorial - Part 10/10: Modern JavaScript & Beyond
#JavaScript #ES2023 #TypeScript #AdvancedPatterns #WebDev

Welcome to the final part of our comprehensive JavaScript series! This ultimate lesson explores cutting-edge JavaScript features, TypeScript fundamentals, advanced patterns, and pathways for continued learning.

---

## πŸ”Ή Modern JavaScript Features (ES2023+)
### 1. Top-Level Await (ES2022)
// Module.js
const data = await fetch('https://api.example.com/data');
export { data };

// No need for async wrapper!


### 2. Array Find from Last (ES2023)
const numbers = [10, 20, 30, 20, 40];
numbers.findLast(n => n === 20); // 20 (last occurrence)
numbers.findLastIndex(n => n === 20); // 3


### 3. Hashbang Support (ES2023)
#!/usr/bin/env node
// Now executable directly via ./script.js
console.log('Hello from executable JS!');


### 4. WeakRef & FinalizationRegistry (ES2021)
const weakRef = new WeakRef(domElement);
const registry = new FinalizationRegistry(heldValue => {
console.log(`${heldValue} was garbage collected`);
});

registry.register(domElement, "DOM Element");


### 5. Error Cause (ES2022)
try {
await fetchData();
} catch (error) {
throw new Error('Processing failed', { cause: error });
}


---

## πŸ”Ή TypeScript Fundamentals
### 1. Basic Types
let username: string = "Ali";
let age: number = 25;
let isActive: boolean = true;
let scores: number[] = [90, 85, 95];
let user: { name: string; age?: number } = { name: "Ali" };


### 2. Interfaces & Types
interface User {
id: number;
name: string;
email: string;
}

type Admin = User & {
permissions: string[];
};

function createUser(user: User): Admin {
// ...
}


### 3. Generics
function identity<T>(arg: T): T {
return arg;
}

const result = identity<string>("Hello");


### 4. Type Inference & Utility Types
const user = {
name: "Ali",
age: 25
}; // Type inferred as { name: string; age: number }

type PartialUser = Partial<typeof user>;
type ReadonlyUser = Readonly<typeof user>;


---

## πŸ”Ή Advanced Patterns
### 1. Dependency Injection
class Database {
constructor(private connection: Connection) {}

query(sql: string) {
return this.connection.execute(sql);
}
}

const db = new Database(new MySQLConnection());


### 2. Proxy API
const validator = {
set(target, property, value) {
if (property === 'age' && typeof value !== 'number') {
throw new TypeError('Age must be a number');
}
target[property] = value;
return true;
}
};

const user = new Proxy({}, validator);
user.age = 25; // OK
user.age = "25"; // Throws error


### 3. Observable Pattern
class Observable<T> {
private subscribers: ((value: T) => void)[] = [];

subscribe(callback: (value: T) => void) {
this.subscribers.push(callback);
}

next(value: T) {
this.subscribers.forEach(cb => cb(value));
}
}

const clicks = new Observable<MouseEvent>();
clicks.subscribe(e => console.log(e.clientX));
document.addEventListener('click', e => clicks.next(e));


---

## πŸ”Ή Web Components
### 1. Custom Elements
class PopupAlert extends HTMLElement {
constructor() {
super();
this.attachShadow({ mode: 'open' });
this.shadowRoot.innerHTML = `
<style>
.alert { /* styles */ }
</style>
<div class="alert">
<slot></slot>
</div>
`;
}
}

customElements.define('popup-alert', PopupAlert);


### 2. Template Literals for HTML
function html(strings, ...values) {
let str = '';
strings.forEach((string, i) => {
str += string + (values[i] || '');
});
const template = document.createElement('template');
template.innerHTML = str;
return template.content;
}

const fragment = html`<div>Hello ${name}</div>`;


---

## πŸ”Ή Performance Patterns
### 1. Virtualization
function renderVirtualList(items, container, renderItem) {
const visibleItems = getVisibleItems(items, container);
container.replaceChildren(
...visibleItems.map(item => renderItem(item))
);
}
❀1
πŸ”₯ Trending Repository: awesome-front-end-system-design

πŸ“ Description: Curated front end system design resources for interviews and learning

πŸ”— Repository URL: https://github.com/greatfrontend/awesome-front-end-system-design

🌐 Website: https://greatfrontend.com/front-end-system-design-playbook

πŸ“– Readme: https://github.com/greatfrontend/awesome-front-end-system-design#readme

πŸ“Š Statistics:
🌟 Stars: 7.7K stars
πŸ‘€ Watchers: 37
🍴 Forks: 255 forks

πŸ’» Programming Languages: Not available

🏷️ Related Topics:
#react #javascript #front_end #system_design #system_design_interview #front_end_system_design


==================================
🧠 By: https://t.iss.one/DataScienceN
πŸ“Œ How to Build a Tic Tac Toe Game with Phaser.js

✍️ Manish Shivanandhan
🏷️ #JavaScript
❀1πŸ‘1
πŸ“Œ How to Build a Tic Tac Toe Game with Phaser.js

✍️ Manish Shivanandhan
🏷️ #JavaScript
πŸ“Œ Create 3D Web Experiences with JavaScript and Three.js

✍️ Beau Carnes
🏷️ #JavaScript
❀1πŸ”₯1
πŸ“Œ How to Build a Snake Game using Phaser.js

✍️ Manish Shivanandhan
🏷️ #JavaScript
❀2