Skip to content

Commit

Permalink
add: js samples
Browse files Browse the repository at this point in the history
  • Loading branch information
thutasann committed Feb 9, 2025
1 parent fbe2b55 commit b531a45
Show file tree
Hide file tree
Showing 9 changed files with 321 additions and 4 deletions.
4 changes: 2 additions & 2 deletions data_structures/README.md
Original file line number Diff line number Diff line change
@@ -1,3 +1,3 @@
# Java Data Structures and Algorithms
# Java Data Structures and Algorithms & Javascript Questions

- [key-patterns](./docs/keys-patterns.md)
- [key-patterns](./docs/keys-patterns.md)
63 changes: 63 additions & 0 deletions data_structures/docs/javascript-common-questions.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,63 @@
# Advanced JavaScript Questions

## 1. Closures & Scope

- What are **closures** in JavaScript? Provide an example.
- How does **variable hoisting** work in JavaScript?
- What’s the difference between **var, let, and const** in terms of scope?
- Explain the **Temporal Dead Zone (TDZ)**.

## 2. Asynchronous JavaScript (Promises, Async/Await, Event Loop)

- How does the **event loop** work in JavaScript?
- What is the difference between **microtasks** and **macrotasks**?
- Explain the difference between **Promise.all, Promise.allSettled, Promise.race, and Promise.any**.
- How does **async/await** work internally?

## 3. Prototypes & Inheritance

- What is **prototypal inheritance**?
- What is the difference between `__proto__` and `prototype`?
- How does `Object.create()` work?

## 4. Memory Management & Performance

- How does JavaScript handle **garbage collection**?
- What are **memory leaks** in JavaScript, and how do you prevent them?
- What’s the difference between **deep copy and shallow copy**?

## 5. Functional Programming

- What is **currying**, and how does it work?
- What is the difference between `.map()`, `.filter()`, and `.reduce()`?
- What are **pure functions**, and why are they important?

## 6. JavaScript Engines & Compilation

- How does the **V8 engine** work?
- What is **JIT compilation** in JavaScript?
- Explain **hidden classes** in V8 and how they affect performance.

## 7. Event Delegation & DOM Manipulation

- What is **event delegation**, and how does it improve performance?
- What is the difference between `e.stopPropagation()` and `e.preventDefault()`?
- How does **debouncing** and **throttling** work?

## 8. Advanced Object Concepts

- What’s the difference between **Object.freeze(), Object.seal(), and Object.preventExtensions()**?
- How do you create an **immutable object** in JavaScript?
- What are **symbols**, and when should you use them?

## 9. Modules & Design Patterns

- What’s the difference between **CommonJS and ES6 Modules**?
- Explain the **Revealing Module Pattern**.
- How do you implement the **Singleton Pattern** in JavaScript?

## 10. Meta-Programming (Proxy, Reflect, etc.)

- What is the **Proxy** object in JavaScript, and how do you use it?
- What is the purpose of the **Reflect API**?
- How does `defineProperty()` work?
18 changes: 18 additions & 0 deletions data_structures/js_questions/closure_scopes/basic_closure.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
/**
* A Closure is a function that remembers the variables
* from its lexical scope even when executed outside that scope.
* - The `count` variabled is enclosed in the inner function.
* - Even after createCounter has finished executing, the returned function retians access to count
*/
function createCounter(): () => number {
let counter = 0;

return function () {
return counter++;
};
}

const counter = createCounter();
console.log('counter()', counter());
console.log('counter()', counter());
console.log('counter()', counter());
Original file line number Diff line number Diff line change
@@ -0,0 +1,40 @@
/**
* ## Block Scope vs Function Scope
* - Function Scope: When a variable is declared inside a function, it is only accessible within that function and cannot be used outside that function.\
* - Block Scope: A variable when declared inside the if or switch conditions or inside for or while loops, are accessible within that particular condition or loop. To be consise the variables declared inside the curly braces are called as within block scope.
* - var ==> function scope that is if a variable is declared using var keyword it will be accessible throughout the function.
* - let & const ==> block scope that is they are accessible within that particular block.
*/
function hello() {
if (true) {
var a = 'Javascript';
let b = 'C++';
const c = 'Python';
console.log(a);
console.log(b);
console.log(c);
}
console.log('Outside if statement');
console.log(a);
// console.log(b); ReferenceError: b is not defined
// console.log(c); ReferenceError: c is not defined
}
hello();

function functionScopeTest() {
if (true) {
var functionScoped = "I'm inside a function";
}
console.log(functionScoped);
}
functionScopeTest();

function blockScopeTest() {
if (true) {
let blockScoped = "I'm inside a block";
const constScoped = "I'm also inside a block";
console.log(blockScoped); // ✅ Works
}
// console.log(blockScoped); ❌ Error: blockScoped is not defined
}
blockScopeTest();
26 changes: 26 additions & 0 deletions data_structures/js_questions/closure_scopes/closure_in_loop.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
/**
* Issue: Closure Capturing Loop Variable
* - `var` is function-scoped, so all callbacks share the same `i`
* - when `setTimeout` executes, `i` is already 4
*/
function delayedLog() {
for (var i = 0; i <= 3; i++) {
setTimeout(() => {
console.log(i);
}, i * 1000);
}
}
delayedLog();

/**
* Fix: use `let`
* - `let` is block-scoped, createing a new `i` for each loop iteration
*/
function delayedLogFixed() {
for (let i = 1; i <= 3; i++) {
setTimeout(() => {
console.log(i);
}, i * 1000);
}
}
delayedLogFixed();
7 changes: 7 additions & 0 deletions data_structures/js_questions/closure_scopes/global_scope.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
let globalVar = "I'm Gloal!";

function printGlobal() {
console.log('globalVar ==> ', globalVar);
}

printGlobal();
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
function createSecret(secret: string) {
return {
getSecret: () => secret,
};
}
const obj = createSecret('Hidden meessage');
console.log(obj.getSecret());
15 changes: 15 additions & 0 deletions data_structures/js_questions/fibonacci.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
const fiboMemo = new Map([
[0, 0],
[1, 1],
]);

function fibonacci(num: number): number {
if (num < 0) return 0;
if (fiboMemo.has(num)) return fiboMemo.get(num) || 0;
const result = fibonacci(num - 1) + fibonacci(num - 2);
fiboMemo.set(num, result);
return result;
}
console.log(fibonacci(10));
console.log(fibonacci(0));
console.log(fibonacci(1));
145 changes: 143 additions & 2 deletions data_structures/src/KeyPatterns/SlidingWindow/ts/SlidingWindow.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,147 @@
/**
* Sliding Window Problems, Solutions, Practices in typescript
*/
class SlidingWindow {
examples() {
main() {
this.maxSumOptimized();
this.longestSubStringWithoutRepeatingCharacter();
this.smallestSubArrayWithGivenSum();
this.longestSubstringWithKDistinct();
this.easyDynamicWindowSum();
this.dynamicWindowDistinct();
this.longestSubArrayWithSum();
}

longestSubArrayWithSum() {
console.log('\nLongest Subarray with Sum ==> ');
const arr = [3, 1, 2, 1, 1, 1, 1, 2];
const S = 5;
let windowStart = 0,
windowSum = 0,
maxLength = 0;

for (let windowEnd = 0; windowEnd < arr.length; windowEnd++) {
windowSum += arr[windowEnd];

while (windowSum >= S) {
windowSum -= arr[windowStart];
windowStart++;
}

maxLength = Math.max(maxLength, windowEnd - windowStart + 1);
}
console.log('maxLength ==>', maxLength);
}

dynamicWindowDistinct() {
console.log('\nDynamic Window Distinct ==> ');
const str = 'aabacbebebe';
const maxDistinct = 2;
let widnowStart = 0;
const charFrequencyMap = new Map<string, number>();

for (let windowEnd = 0; windowEnd < str.length; windowEnd++) {
const rightChar = str.charAt(windowEnd);
charFrequencyMap.set(rightChar, (charFrequencyMap.get(rightChar) || 0) + 1);

while (charFrequencyMap.size > maxDistinct) {
console.log(
`Current window with more than ${maxDistinct} distinct characters : ${str.substring(widnowStart, windowEnd)}`
);
const leftChar = str.charAt(widnowStart);
charFrequencyMap.set(leftChar, (charFrequencyMap.get(leftChar) || 0) - 1);
if (charFrequencyMap.get(leftChar) == 0) {
charFrequencyMap.delete(leftChar);
}
widnowStart++;
}
}
}

easyDynamicWindowSum() {
console.log('\n(Easy) Dynamic Window Sum ==> ');
const arr = [1, 2, 3, 4, 5];
const target = 8;
let windowStart = 0,
windowSum = 0;

for (let windowEnd = 0; windowEnd < arr.length; windowEnd++) {
windowSum += arr[windowEnd];

while (windowSum >= target) {
console.log(`Current WindowSum >= ${target} : ${windowSum}`);
windowSum -= arr[windowStart];
windowStart++;
}
}
}

longestSubstringWithKDistinct() {
console.log('\nLongest SubString with K Distinct Character ==> ');
const str = 'araaci';
const k = 2;
let windowStart = 0,
maxLength = 0;
const charFrequencyMap = new Map<string, number>();

for (let windowEnd = 0; windowEnd < str.length; windowEnd++) {
const rightChar = str.charAt(windowEnd);
charFrequencyMap.set(rightChar, (charFrequencyMap.get(rightChar) || 0) + 1);

while (charFrequencyMap.size > k) {
const leftChar = str.charAt(windowStart);
charFrequencyMap.set(leftChar, (charFrequencyMap.get(leftChar) || 0) - 1);
if (charFrequencyMap.get(leftChar) == 0) {
charFrequencyMap.delete(leftChar);
}
windowStart++;
}

maxLength = Math.max(maxLength, windowEnd - windowStart + 1);
}
console.log('maxLength ==> ', maxLength);
}

smallestSubArrayWithGivenSum() {
console.log('\nSmallest Subarray with given sum ==> ');
const arr = [2, 1, 5, 2, 3, 2];
const target = 7;
let windowStart = 0,
windowSum = 0,
minLength = Number.MAX_VALUE;

for (let windowEnd = 0; windowEnd < arr.length; windowEnd++) {
windowSum += arr[windowEnd];

while (windowSum >= target) {
minLength = Math.min(minLength, windowEnd - windowStart + 1);
windowSum -= arr[windowStart];
windowStart++;
}
}

const result = minLength === Number.MAX_VALUE ? 0 : minLength;
console.log('result', result);
}

longestSubStringWithoutRepeatingCharacter() {
console.log('\nLongest SubString without repeating Character ==> ');
const str = 'abcabcbb';
let windowStart = 0;
let maxLength = 0;
const charIndexMap = new Map<string, number>();

for (let windowEnd = 0; windowEnd < str.length; windowEnd++) {
const rightChar = str.charAt(windowEnd);

if (charIndexMap.has(rightChar)) {
windowStart = Math.max(windowStart, (charIndexMap.get(rightChar) || 0) + 1);
}

charIndexMap.set(rightChar, windowEnd);
maxLength = Math.max(maxLength, windowEnd - windowStart + 1);
}
console.log('maxLength', maxLength);
}

maxSumOptimized() {
Expand Down Expand Up @@ -29,4 +170,4 @@ class SlidingWindow {
}

const slidingWindow = new SlidingWindow();
slidingWindow.examples();
slidingWindow.main();

0 comments on commit b531a45

Please sign in to comment.