Q1. Write a function to flatten a nested array using a recursive approach.
The
function should take an array that may contain nested arrays of arbitrary depth as
input and return a single, flattened array containing all the elements.
Input: [1, [2, [3, [4]], 5], 6]
Output: [1, 2, 3, 4, 5, 6]
const flattenArray = (arr) => {
let result = [];
arr.forEach((item) => {
if (Array.isArray(item)) {
result = result.concat(flattenArray(item));
} else {
result.push(item);
}
});
return result;
};
// Example
const notFlatArr= [1, [2, [3, [4]], 5], 6];
console.log(flattenArray(notFlatArr));
2. Implement a function to find all subsets of an array
Ans .
function subSets (arr) {
const subArr = [[]];
for(let i =0; i<arr.length; i++) {
const currentIndex = arr[i]
const len = subArr.length;
for(let j =0; j<len; j++) {
const newArr = [...subArr[j] , currentIndex];
subArr.push(newArr);
}
}
return subArr;
}
//Example
const arr = [1 , 2 ,3];
const subSetsArray = subSets(arr);
console.log(subSetsArray);
Q3. Implement an algorithm for rate-limiter using a sliding window or token bucket
approach in javascript
Ans.
type RateLimiter = {
tryConsume: () => boolean;
};
function createRateLimiter(limit: number, interval: number): RateLimiter {
let tokens = limit;
let lastRefillTime = Date.now();
function refillTokens() {
const now = Date.now();
const elapsedTime = now - lastRefillTime;
const tokensToAdd = Math.floor((elapsedTime / interval) * limit);
if (tokensToAdd > 0) {
tokens = Math.min(limit, tokens + tokensToAdd);
lastRefillTime = now;
}
}
// Try to consume a token
function tryConsume(): boolean {
refillTokens();
if (tokens > 0) {
tokens--;
return true; // Request allowed
}
return false; // Request denied
}
return { tryConsume };
}
// Example
const limiter = createRateLimiter(5, 10000);
setInterval(() => {
console.log("Request allowed:", limiter.tryConsume());
}, 2000);
4. Create a component that fetches and displays data from a mock API (e.g.,
https://jsonplaceholder.typicode.com/todos/1).
Ans.
import { useState, useEffect } from "react";
import { Card, CardContent } from "@/components/ui/card";
import { Button } from "@/components/ui/button";
const FetchTodo = () => {
const [todo, setTodo] = useState(null);
const [loading, setLoading] = useState(true);
const [error, setError] = useState(null);
const fetchUrlofApi = "https://jsonplaceholder.typicode.com/todos/1"
const fetchData = async () => {
setLoading(true);
setError(null);
try {
const response = await fetch(`${fetchUrlofApi }`);
if (!response.ok) {
throw new Error("Failed to fetch data");
}
const data = await response.json();
setTodo(data);
} catch (err) {
setError(err.message);
} finally {
setLoading(false);
}
};
useEffect(() => {
fetchData();
}, []);
return (
<div className="flex flex-col items-center p-4">
<Card className="shadow-lg">
<CardContent className="p-4">
{loading && <p>Loading...</p>}
{error && <p className="text-red-500">Error: {error}</p>}
{todo && (
<div>
<h2 className="text-xl font-semibold">Todo #{todo.id}</h2>
<p className="text-gray-600">{todo.title}</p>
<p className={todo.completed ? "text-green-500" : "text-red-500"}>
{todo.completed ? "Completed" : "Not Completed"}
</p>
</div>
)}
<Button className="mt-4" onClick={fetchData}>Refresh</Button>
</CardContent>
</Card>
</div>
);
};
export default FetchTodo;