Search This Blog

2023/09/28

Node.js:Buffer Interview Questions

 What is a Node.js Buffer?


A Node.js Buffer is a built-in object in Node.js used to
represent binary data directly in memory. It is a raw memory
allocation outside the JavaScript heap that allows Node.js to
handle binary data efficiently, which is crucial for tasks like
working with files, network streams, and other data sources
where binary data is involved.

How can you create a Buffer in Node.js?

You can create a Buffer in Node.js using one of the following methods:

Buffer.from(data): Creates a Buffer from an array, array-like object, or string.
Buffer.alloc(size): Allocates a new, zero-filled Buffer of the specified size.
Buffer.allocUnsafe(size): Allocates a new Buffer of the specified size, but it
may contain uninitialized memory.
Buffer.allocUnsafeSlow(size): Similar to Buffer.allocUnsafe(size), but slower.

How do you read data from a Buffer?

You can read data from a Buffer using methods like readUInt8,
readUInt16LE, readUInt16BE, readUInt32LE, readUInt32BE,
and similar methods for different data types. For example:

const buffer = Buffer.from([0x01, 0x02, 0x03, 0x04]);
const value = buffer.readUInt16LE(0); // Read a 16-bit integer in little-endian format from offset 0

How do you write data to a Buffer?

You can write data to a Buffer using methods like writeUInt8,
writeUInt16LE, writeUInt16BE, writeUInt32LE, writeUInt32BE,
and similar methods for different data types. For example:

const buffer = Buffer.alloc(4);
buffer.writeUInt16LE(0x0102, 0); // Write a 16-bit integer in little-endian format to offset 0


What are the differences between Buffer.from and Buffer.alloc?

Buffer.from creates a new Buffer and initializes it with the provided data (e.g., an array or string).
Buffer.alloc creates a new Buffer and initializes it with zeros.
Buffer.from is used when you want to create a Buffer from existing data,
whereas Buffer.alloc is used when you want to create an empty Buffer with a specific size.

How can you convert a Buffer to a string in Node.js?

Answer: You can convert a Buffer to a string in Node.js using the toString method. For example:

const buffer = Buffer.from('Hello, World!');
const str = buffer.toString('utf8'); // Convert the Buffer to a UTF-8 encoded string


What is the purpose of Buffer.allocUnsafe and Buffer.allocUnsafeSlow?

Answer:

Buffer.allocUnsafe allocates a new Buffer of the specified size but does not initialize its contents.
It is faster than Buffer.alloc because it doesn't fill the buffer with zeros,
but you should be careful when using it as the buffer may contain random data.

Buffer.allocUnsafeSlow is similar to Buffer.allocUnsafe, but it may be slower
and should be used only in cases where Buffer.allocUnsafe is not available.

How can you check the length of a Buffer?

Answer: You can check the length of a Buffer using the length property or the byteLength method:

const buffer = Buffer.from('Hello');
const length1 = buffer.length; // 5
const length2 = buffer.byteLength; // 5

Node.js:Buffers in node.js

 create buffer from string


var buf = Buffer.from('abc');
console.log(buf.toString());


create empty buffer of length 15

var buf = Buffer.alloc(15);
console.log(buf);

return size of buffer

var buf = Buffer.from('abc');
console.log(buf.length);


join three buffer object to one

var buf1 = Buffer.from('a');
var buf2 = Buffer.from('b');
var buf3 = Buffer.from('c');
var arr = [buf1, buf2, buf3];

var buf = Buffer.concat(arr);
console.log(buf.toString());


A Buffer cannot be resized.

Max Buffer size :

var buffer = require('buffer')
console.log(buffer.constants.MAX_LENGTH)

it is less on 32 bit machine & more on 64 bit machines.

Checking wheather object is buffer

var buf1 = Buffer.from('a');
var buf2 = "sa"
console.log(Buffer.isBuffer(buf1));
console.log(Buffer.isBuffer(buf2));


Return the number of bytes in the string "abc":

var len3 = Buffer.byteLength('abc');
console.log(len3);


Check the length of a buffer object:

var buf = Buffer.alloc(15);
var len1 = Buffer.byteLength(buf);
var len2 = buf.length;
console.log(len1);
console.log(len2);


return index from where the searched value is starting. It returns -1 if the value is not present in the buffer.

const buffer = Buffer.from('GeeksforGeeks: A computer science portal');
const output = buffer.indexOf('computer');
console.log(output);

output:
17


const buffer = Buffer.from('geeks community');
const output = buffer.indexOf(101);
const output1 = buffer.indexOf('geeks community');
const output2 = buffer.indexOf('com',7);//start searching at position 7 starting from 0

console.log(output);
console.log(output1);
console.log(output2);

output:
0
1
-1

check if two buffers are equal

var buf1 = Buffer.from('Hi');
var buf2 = Buffer.from('Hi');
console.log(buf1.equals(buf2));

output:
true


subarray:

const buf = Buffer.from('GeeksforGeeks', 'ascii');
console.log("Original buffer is: " + buf);
cropped_buf = buf.subarray(5, 10);
console.log("Cropped buffer is: " + cropped_buf);
cropped_buf[0] = 70; // F
cropped_buf[1] = 79; // O
cropped_buf[2] = 82; // R
console.log("Cropped buffer after modification is: " + cropped_buf);
console.log("Original buffer after modification is: " + buf);

output:

Original buffer is: GeeksforGeeks
Cropped buffer is: forGe
Cropped buffer after modification is: FORGe
Original buffer after modification is: GeeksFORGeeks



another example with negative index

const buf = Buffer.from('GeeksforGeeks', 'ascii');
console.log("Original buffer is: " + buf);

cropped_buf = buf.subarray(-12, -1);
console.log("Cropped buffer is:" + cropped_buf);
cropped_buf = buf.subarray(-10, -5);
console.log("Cropped buffer is: " + cropped_buf);
cropped_buf = buf.subarray();
console.log("Cropped buffer is: " + cropped_buf);


output:
Original buffer is: GeeksforGeeks
Cropped buffer is:eeksforGeek
Cropped buffer is: ksfor
Cropped buffer is: GeeksforGeeks


include or not

const buffer = Buffer.from('Geek One');
console.log(buffer.includes('Geek'));

output:
true

another example
const buffer = Buffer.from('GeeksforGeeks: A computer science portal');
const output = buffer.includes('Geek', 15);
console.log(output);

output:
false


copy method:

let buffer2 = Buffer.from('for');
let buffer1 = Buffer.from('GeeksandGeeks');

buffer2.copy(buffer1, 5,0)
console.log(buffer1.toString());

output:
GeeksforGeeks


compare:
return 0,-1 or 1

const buffer1 = Buffer.from('Geek');
const buffer2 = Buffer.from('Geek');
const op = Buffer.compare(buffer1, buffer2);
console.log(op);

output:
0


sort buffer array:
const buffers = [
Buffer.from('A', 'utf8'),
Buffer.from('C', 'utf8'),
Buffer.from('B', 'utf8')
];

buffers.sort(Buffer.compare);


compare on buffer object

const buffer1 = Buffer.from('GeeksOne');
const buffer2 = Buffer.from('GeekTwo');
let op = buffer1.compare(buffer2, 4);
let op1 = buffer1.compare(buffer2, 0, 7, 5);
console.log(op);
console.log(op1);

output:
-1
1


another example:
const buffer1 = Buffer.from("Geeks");
const buffer2 = Buffer.from("GeeksFor");

let op1 = buffer1.compare(buffer2, 0, 5);
console.log(op1);

output:
0

2023/09/14

Mysql :Factorial Using Recursive


WiTH RECURSIVE factorial(n,fact) as (

select 0,1
UNION ALL
select n+1,(n+1)* fact from factorial where n < 5
)
select * from factorial

Mysql Remove Duplicate keep 1st or keep last

 create table MyEmployee(

id int auto_increment primary key,
name varchar(50),
city varchar(50),
deptId int,
salary float,
dateOfJoining datetime
)

truncate table MyEmployee;

insert into MyEmployee(name,city,deptId,salary,dateOfJoining)
values('sagar','malvan',1,5000,now());

insert into MyEmployee(name,city,deptId,salary,dateOfJoining)
values('sangram','mumbai',1,10000,now());

insert into MyEmployee(name,city,deptId,salary,dateOfJoining)
values('sachin','banglore',2,15000,now());

insert into MyEmployee(name,city,deptId,salary,dateOfJoining)
values('vivek','mumbai',3,8000,now());

insert into MyEmployee(name,city,deptId,salary,dateOfJoining)
values('vishal','pune',4,6000,now());

insert into MyEmployee(name,city,deptId,salary,dateOfJoining)
values('vijay','nagpur',1,9700,now());

insert into MyEmployee(name,city,deptId,salary,dateOfJoining)
values('sagar','kankavali',2,6000,now());

insert into MyEmployee(name,city,deptId,salary,dateOfJoining)
values('sangram','pune',3,10000,now());

insert into MyEmployee(name,city,deptId,salary,dateOfJoining)
values('sachin','hyderabad',2,15000,now());


select * from MyEmployee;

Find Duplicate:


with duplicate as (
SELECT *,
ROW_NUMBER() OVER(PARTITION BY name) AS row_num
FROM MyEmployee
)
select * from duplicate where row_num > 1



Delete Duplicate keep first one:
with duplicate as (
SELECT *,
ROW_NUMBER() OVER(PARTITION BY name) AS row_num
FROM MyEmployee
)
delete MyEmployee from MyEmployee inner join duplicate on MyEmployee.id = duplicate.id
where duplicate.row_num > 1


Delete Duplicate keep last one
delete MyEmployee from MyEmployee join
(
SELECT min(id) minval ,max(id) maxval ,name from MyEmployee group by name
)t
where MyEmployee.name = t.name and MyEmployee.id !=t.maxval

2023/09/13

MySQL/PostgreSQL - nth max salary

Setup:
create table employee
(
id serial,
name varchar(150),
salary float
);

insert into employee(name,salary) values ('sagar','100000'),
('sangram','50000'),
('sachin','56000'),
('swapnil','45000'),
('gaurav',54000),
('ganesh',39000);

insert into employee(name,salary) values ('gajanan',54000),
('kamal',39000);


Nth Max Salary
select * from employee where salary = (
select salary from employee order by salary desc limit 1 offset n-1
)
3rd Max salary:
select * from employee where salary = (
select salary from employee order by salary desc limit 1 offset 2
)
Nth Max Salary Using Inner Join:
select s.* from employee s
inner join (
select distinct salary from employee order by salary desc limit 1 offset n-1
) t on s.salary = t.salary

3rd Max salary:
select s.* from employee s
inner join (
select distinct salary from employee order by salary desc limit 1 offset 2
) t on s.salary = t.salary

Nth Max Salary generic:
select * from employee e1 where n-1=(select count(distinct salary) from employee e2 where e2.salary > e1.salary)

3rd Max Salary:
select * from employee e1 where 2=(select count(distinct salary) from employee e2 where e2.salary > e1.salary)

Nth Max salary using DENSE_RANK():
select
T1.name,
T1.salary
from (
SELECT
DENSE_RANK() OVER (ORDER BY SALARY DESC) AS rownumber,
Salary,
name
FROM
employee
)T1 where T1.rownumber = n

3rd Max salary:
select
T1.name,
T1.salary
from (
SELECT
DENSE_RANK() OVER (ORDER BY SALARY DESC) AS rownumber,
Salary,
name
FROM
employee
)T1 where T1.rownumber = 3



Nth Max salary using ROW_NUMBER():
SELECT * FROM
(
SELECT
ROW_NUMBER() OVER (ORDER BY SALARY DESC) AS rownumber,Salary
FROM (select distinct salary from employee)T1
) AS foo
inner join Employee E2 on E2.salary = foo.salary
WHERE
rownumber = n

3rd Max salary:
SELECT * FROM
(
SELECT
ROW_NUMBER() OVER (ORDER BY SALARY DESC) AS rownumber,Salary
FROM (select distinct salary from employee)T1
) AS foo
inner join employee E2 on E2.salary = foo.salary
WHERE
rownumber = 3

Javascript:Implicit type conversion example

A number stored as string get converted to number if added to itself implicitly.
A number get converted to string if it is concated to empty string implicitly.

Code:
//convert number to string
var x = 1;
x = "" + 1;
console.log(typeof x);
console.log(x);

//convert string to number
var y = "23.78";
y = +y;
console.log(typeof y);
console.log(y);


Output:
string
1
number
23.78

Generated Columns Mysql

 A generated column is similar to a normal column, but you cannot change its value

manually. This is because an expression
defines how to generate the value of a generated column based on the other values
that are read from the other columns of the same row.

CREATE TABLE users (
id INT AUTO_INCREMENT PRIMARY KEY,
email VARCHAR(100) NOT NULL,
first_name VARCHAR(60) NOT NULL,
last_name VARCHAR(60) NOT NULL,
full_name varchar(120) GENERATED ALWAYS AS (CONCAT(first_name, ' ', last_name))
);

it is virtaul by default.

you can define a generated column as VIRTUAL or STORED


VIRTUAL Generated Columns:
MySQL does not store a generated column marked as VIRTUAL.
This means that MySQL evaluates its value on the fly when
required. This typically happens immediately after any
BEFORE query is triggered. In other terms, a virtual
generated column takes up no storage space. MySQL does not store a generated column marked as VIRTUAL.
This means that MySQL evaluates its value on the fly when
required. This typically happens immediately after any
BEFORE query is triggered. In other terms, a virtual
generated column takes up no storage space.

e.g.
CREATE TABLE usersvirtual (
id INT AUTO_INCREMENT PRIMARY KEY,
email VARCHAR(100) NOT NULL,
first_name VARCHAR(60) NOT NULL,
last_name VARCHAR(60) NOT NULL,
full_name varchar(120) GENERATED ALWAYS AS (CONCAT(first_name, ' ', last_name)) VIRTUAL
);

e.g.
CREATE TABLE usersvirtual (
id INT AUTO_INCREMENT PRIMARY KEY,
email VARCHAR(100) NOT NULL,
first_name VARCHAR(60) NOT NULL,
last_name VARCHAR(60) NOT NULL,
full_name varchar(120) GENERATED ALWAYS AS (CONCAT(first_name, ' ', last_name)) VIRTUAL
);

MySQL has to evaluate them when reading a table, making SELECT queries involving them slower.


Stored Generated Columns

MySQL stores any generated column marked as STORED.
This means that MySQL takes care of evaluating its
value and storing it on the disk every time you
insert or update a row. In other terms, a stored
column requires storage space as if it was a normal column.

e.g.
CREATE TABLE usersstored (
id INT AUTO_INCREMENT PRIMARY KEY,
email VARCHAR(100) NOT NULL,
first_name VARCHAR(60) NOT NULL,
last_name VARCHAR(60) NOT NULL,
full_name varchar(120) GENERATED ALWAYS AS (CONCAT(first_name, ' ', last_name)) STORED
);

INSERT or UPDATE comes with an overhead because MySQL has to generate them.

2023/09/11

Javascript Interview Question:Get all subsets of array

Problem Statement:
For given one dimesional array of numbers find all possible subsets
of that array.
e.g.
For Array [1,2,3]
Output should be
[
[],
[1],
[2],
[3],
[1,2],
[1,3],
[2,3],
[1,2,3]
]

Here array [1,2] & [2,1] are same as per set theory so should not be repeated.

Solution:
function getAllSubsets(arr) {
let subset = [[]];
function generateSubsets(indx, currentSubset) {
if (indx == arr.length) {
return;
}

for (let i = indx; i < arr.length; i++) {
currentSubset.push(arr[i]);
subset.push([...currentSubset]);
generateSubsets(i + 1, currentSubset);
currentSubset.pop();
}
}
generateSubsets(0, []);
return subset;
}

// Example usage:
const inputArray = [1, 2, 3];
const subsets = getAllSubsets(inputArray);

console.log(subsets);

Output:
[
[], [ 1 ],
[ 1, 2 ], [ 1, 2, 3 ],
[ 1, 3 ], [ 2 ],
[ 2, 3 ], [ 3 ]
]

Solution (Without Recursion):

function getAllSubsets(array) {
const subsets = [[]];

for (const el of array) {
const last = subsets.length - 1;
for (let i = 0; i <= last; i++) {
subsets.push([...subsets[i], el]);
}
}

return subsets;
}

let array = [1, 2, 3];
let result = getAllSubsets(array);
console.log(result);

Output:
[
[], [ 1 ],
[ 2 ], [ 1, 2 ],
[ 3 ], [ 1, 3 ],
[ 2, 3 ], [ 1, 2, 3 ]
]
Explanation:
Here is an example for [1, 2, 3]
1) Start with an empty subset: []

2) Create new subsets by adding "1" to each existing subset.
It will be:[] [1]

3) Create new subsets by adding "2" to each existing subset.
It will be:[], [1] [2], [1, 2]

4) Create new subsets by adding "3" to each existing subset.
It will be: [], [1], [2], [1, 2] [3], [1, 3], [2, 3], [1, 2, 3]

Javascript : Array Length

length is a property of arrays in JavaScript that returns or sets the
number of elements in a given array.

Code:
var names= ["sagar","sangram","sachin"]
console.log(names.length)

/*we can set array length it will increase array by appending undefined
element at end*/
names.length =6;
console.log(names)

/*now array size got increased to 6 it added empty element to end to match
set size*/
console.log("Last:",names[5])

names[5] = "swapnil"
console.log("Last:",names[5])
console.log(names)

names.length =4;
console.log(names)

Output:
3
[ 'sagar', 'sangram', 'sachin', <3 empty items> ]
Last: undefined
Last: swapnil
[ 'sagar', 'sangram', 'sachin', <2 empty items>, 'swapnil' ]
[ 'sagar', 'sangram', 'sachin', <1 empty item> ]

Explanation:
when we can set array length it will increase array by appending undefined
element at end.When we set last element in increased array to string
"swapnil" by strar[5] = "swapnil" other element which got added due to
increase in length remain unchanged that is undefined or empty slot.When we
set array length to value less than its current array length array get
contracted in sence.When we set array length was 6 it become 6 element array
but when it is set to 4 ,5th & 6th element get removed.

Note:
names.length =-2; or names.length = 2.3 will give an error saying
'RangeError: Invalid array length'.

Javascript Interview Question:List palindrome words from word's array

List the words from array which are palindrome.

Code:
let words= ["Radar", "hello", "level", "world", "deified"]
let palindromeWords= [];

for (let word of words) {
//reverse a word
var reversedWord = word.split('').reverse().join('')

if (word.toUpperCase() == reversedWord.toUpperCase()) {
palindromeWords.push(word)
}
}

console.log(palindromeWords)

Output:
[ 'Radar', 'level', 'deified' ]

Typescript:NonNullable

 type stringornumber = string | number | null | undefined


type stringornumberNoNull = NonNullable<stringornumber>
//this type will not allow null or undefined
let num:stringornumberNoNull = 56;

//this can be string ,number ,undefined or null
let num2:stringornumber = undefined

Typescript: padStart & padEnd string function

Here we demonstrate masking all digits of credit card
number except last four using padStart().

secondly we will add '...' to 'Read More' at the end u
sing padEnd()

Code:
var cc ="1234567867897890"

var lastFour = cc.slice(-4)
var length = cc.length
console.log(length)
console.log(lastFour)

var masked = lastFour.padStart(length,"*")
console.log(masked)//**** **** **** 7890


var str ="Read More"
var newlength = str.length + 3
var newstr = str.padEnd(newlength,'.')
console.log(newstr)//Read More...


Output:
16
7890
************7890
Read More...

Typescript: Array.from

var str1 = Array.from("sangram")
console.log(str1)

var set = new Set()
set.add("sagar").add("sangram").add("sachin")
console.log(set)


var myarr1 = Array.from(set)
console.log(myarr1)

var double = Array.from([1, 2, 3], (x) => x + x)
console.log(double)

var indexArray = Array.from({ length: 5 }, (_current, index) => {
return index
})
//_current here underscore say we dont need this variable in function
console.log(indexArray)


Output:
[ 's', 'a', 'n', 'g', 'r', 'a', 'm' ] Set(3) { 'sagar', 'sangram', 'sachin' } [ 'sagar', 'sangram', 'sachin' ] [ 2, 4, 6 ] [ 0, 1, 2, 3, 4 ]

Javascript:Convert an array to object


There are multiple ways to convert an array to object.

Using Array.reduce() Method:

Code:
var str = ["a", "b", "c", "d"]
var res = str.reduce((acc, current,index) => {
return {...acc,[index]:current}
},{})
console.log(res)

Output
{ '0': 'a', '1': 'b', '2': 'c', '3': 'd' }



Other ways are more simple.

Way 1 using spread operator:

Code:
let names =["sagar","sangram","sachin"]
let objNameSpread = {...names}
console.log(objNameSpread)
Output:
{ '0': 'sagar', '1': 'sangram', '2': 'sachin' }



Way2 using Object.assign:

Code:
let objNameAssign =Object.assign({}, names);
console.log(objNameAssign)
Output:
{ '0': 'sagar', '1': 'sangram', '2': 'sachin' }

Javascript:Shortest Words in Array using Reduce

Find shortest words in array.

Code:
const words = [
"cat",
"dog",
"bird",
"elephant",
"lion",
"tiger",
"zebra",
"monkey",
"ox",
"b",
"a",
"giraffe",
"antelop",
];

function findShortestWords(words) {
let wordWithShortestLength = words.reduce((acc, current) => {
if (current.length < acc.length) {
return current;
} else {
return acc;
}
}, words[0]);

let wordsWithShortestLength = words.filter((m)=>{
return m.length == wordWithShortestLength.length
})
return wordsWithShortestLength
}

var shortest = findShortestWords(words);
console.log(shortest);


Output:
[ 'b', 'a' ]

2023/09/10

Javascript: Flatten Object to a single depth Object

const myNewobj = {
a: "bangladesh",
b: {
c: "pakistan",
d: {
e: "nepal",
f: {
g: "india",
},
},
},
};

function getValuesOfNextedObject(obj) {
let result = [];
for (let elt in obj) {
if (typeof obj[elt] == "object") {
result = result.concat(getValuesOfNextedObject(obj[elt]));
} else {
result.push([elt, obj[elt]]);
}
}
return result;
}

var res = getValuesOfNextedObject(myNewobj)
console.log(res)

var resultObject = {};
for (let elt of res) {
resultObject[elt[0]] = elt[1];
}
console.log(resultObject);

Output:
{ a: 'bangladesh', c: 'pakistan', e: 'nepal', g: 'india' }

Javascript Interview Question:Search keyword in Nexted JSON Object Using Value Array

Problem Statement:
Given JSON object multiple level of nexting find given value exist
in it as value of some key.
E.g. Suppose our multiple level nexted object is

const myobj = {
a: "bangladesh",
b: {
c: "pakistan",
d: {
e: "nepal",
f: {
g: "india",
},
},
},
};
If we pass india we should get true,if we pass goa we should get false.

Solution:
const multipleLevelNextedObject = {
a: "bangladesh",
b: {
c: "pakistan",
d: {
e: "nepal",
f: {
g: "india",
},
},
},
};

let valueToBeFound = "goa";//also try passing india instead of goa

function findValueExistInJsonObject(multipleLevelNextedObject
, valueToBeFound) {
/*this function will create an array of all values at leaf level*/
function getValuesOfNextedObject(obj) {
let result = [];
for (let elt in obj) {
if (typeof obj[elt] == "object") {
result = result.concat(getValuesOfNextedObject(obj[elt]));
} else {
result.push(obj[elt]);
}
}
return result;
}

let valueArray = getValuesOfNextedObject(multipleLevelNextedObject);

let isValueFoundInNextedObjectValues = valueArray.find((elt) => {
if (elt == valueToBeFound) {
return true;
}
});

return isValueFoundInNextedObjectValues;
}


console.log("Multiple Level Nexted Object:",
JSON.stringify(multipleLevelNextedObject))
let isValueFoundInNextedObjectValues
= findValueExistInJsonObject(multipleLevelNextedObject,valueToBeFound)

if (isValueFoundInNextedObjectValues) {
console.log(`Value '${valueToBeFound}'
found in nexted object values`);
} else {
console.log(`Value '${valueToBeFound}'
not found in nexted object values`);
}
Output:
Multiple Level Nexted Object:
{"a":"bangladesh","b":{"c":"pakistan","d":{"e":"nepal","f":{"g":"india"}}}}
Value 'goa' not found in nexted object values

Javascript:Flatten Array to single depth

Sample Input:
const numbers = [
1,
[3, [2, 8, [12, 9]]],
[5],
[12, [[5]]],
[100, [23, 45]]
]

Sample Output:
const numnbers = [
1, 3, 2, 8, 12,
9, 5, 12, 5, 100,
23, 45
]

Solution(1st Method):
const numbers = [
1,
[3, [2, 8, [12, 9]]],
[5],
[12, [[5]]],
[100, [23, 45]]
]

function flattenNextedArray(arr) {
let numbers = [];

for (let elt of arr) {
if (Array.isArray(elt)) {
numbers = numbers.concat(flattenNextedArray(elt))
} else {
numbers.push(elt)
}
}
return numbers
}


var flatten = flattenNextedArray(numbers)
console.log(flatten)

Solution(2nd Method):
const numbers = [
1,
[3, [2, 8, [12, 9]]],
[5],
[12, [[5]]],
[100, [23, 45]]
]

var flatten = numbers.flat(Infinity)
console.log(flatten)

Javascript:Reverse string by recursion

let fruit = "APPLE";

function reverseStringByRecursion(name) {
if (name.length == 0) {
return "";
} else {
let lastChar = name[name.length - 1];
let excludingLastChar = name.slice(0, name.length - 1);
return lastChar + reverse(excludingLastChar);
}
}

var reversedString = reverseStringByRecursion(fruit);
console.log(reversedString);


Output:
ELPPA