0% found this document useful (0 votes)
4 views7 pages

Code Examples for JavaScript Functions

The document contains various JavaScript code snippets demonstrating different programming concepts, including counting duplicates in an array, swapping strings without a third variable, summing an array without loops, and extracting unique values. It also includes React component examples, promise handling, object manipulation, and comparisons. Each section illustrates specific coding techniques and their expected outputs.

Uploaded by

rajatsingh209
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
4 views7 pages

Code Examples for JavaScript Functions

The document contains various JavaScript code snippets demonstrating different programming concepts, including counting duplicates in an array, swapping strings without a third variable, summing an array without loops, and extracting unique values. It also includes React component examples, promise handling, object manipulation, and comparisons. Each section illustrates specific coding techniques and their expected outputs.

Uploaded by

rajatsingh209
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd

// Write a code to find the count of duplicate in array

// output : {1: 2, 2: 2, 3:1, 4:1 }

const arr = [1, 1, 2, 2, 3, 4];

function occurance(arr) {
const result = [Link]((acc, curr) => {
acc[curr] = (acc[curr] || 0) + 1;
return acc;
}, {});
return result;
}

[Link](occurance(arr));
-----------------------------------------------------------------------

// swap two string without using third variable

let a = "ram";
let b = "shaym";

let alen = [Link];

[Link]("before swap");
[Link](a, b);

a = a + b;
b = [Link]("").slice(0, alen).join("");
a = [Link]("").slice(alen).join("");

[Link]("After swap");
[Link](a, b);

-----------------------------------------------------------------------

// sum of array without using loop and builtin methods

const arr = [1, 2, 3, 4, 5, 6, 7, 8];

function summation(arr, index = 0) {


let sum = 0;

if (arr[index] === arr[-1]) return 0;

return (sum = arr[index] + summation(arr, index + 1));


}

[Link](summation(arr));

-----------------------------------------------------------------------

// write the unique value from array without using inbuilt methods

const arr = [1, 1, 2, 4, 5, 5];

const arr1 = [2, 2, 2, 24, 3, 4, 5, 2, 3, 5, 5];

function uniqueValue(arr) {
let new_arr = [];
for (let i = 0; i < [Link]; i++) {
if (new_arr.includes(arr[i])) {
continue;
}
new_arr.push(arr[i]);
}
return new_arr;
}

[Link](uniqueValue(arr));
[Link](uniqueValue(arr1));

-----------------------------------------------------------------------

React - Question output based

import { useState, useEffect } from "react";

function A() {
[Link]("A");
return <B />;
}
function B() {
[Link]("B");
return <C />;
}
function C() {
[Link]("C");
return null;
}
function D() {
[Link]("D");
return null;
}

export default function app() {


const [count, setCount] = useState(0);

useEffect(() => {
setCount((count) => count + 1);
}, []);
[Link]("Start");
return (
<div>
<A state={count} />
<D />
</div>
);
}

Output:
Start
A
B
C
D

-----------------------------------------------------------------------
React - Machine Coding interview Parsing through [Link] and display component

import "./[Link]";
import { useEffect } from "react";
import data from "./[Link]";

export default function App() {


const new_data = [];
new_data.push([Link].custom_blocks["1"]);
new_data.push([Link].custom_blocks["2"]);
[Link](new_data);
return (
<div className="App">
{new_data.map((item, index) => (
<Platform item={item} key={index} />
))}
</div>
);
}

function Platform({ item }) {


[Link](item);
return (
<div
style={{
display: "flex",
flexDirection:
item.card_image_template[0].field_ci_image_alignment === "left"
? "row"
: "row-reverse",
}}
>
<div>
<img
src={item.card_image_template[0]?.field_ci_image?.rel_url}
alt="Image"
height="340px"
width="530px"
/>
</div>
<div>
<p>{item.card_image_template[0].field_card_image.data[0].sub_title}</p>
<p>{item.card_image_template[0].field_card_image.data[0].title}</p>
<p>
{item.card_image_template[0].field_card_image.data[0].description}
</p>
</div>
</div>
);
}

-----------------------------------------------------------------------

Output based question

const arr1 = [];


const arr2 = [];

[Link](arr1 == arr2); // false


[Link](arr1 === arr2); // false

const obj1 = { a: 1 };
const obj2 = { a: 1 };

[Link](obj1 == obj2); // false


[Link](obj1 === obj2); // false

[Link](obj1.a == obj2.a); // true


[Link](obj1.a === obj2.a); // true

-----------------------------------------------------------------------

const a = [1, 2, 3, 4, 1, 3, 4, 5, 15, 8, 22];


output: [22,15,8,5,4,3,2,1]

const result = [...new Set(a)].sort((b, c) => c-b);

[Link](result);

------------------------------------------

const func = (function(a){


delete a;
return a;
})(5);

[Link](func);

output: 5

-------------------------------------------

const a = "4553ABC55DEF";

Output -
F
**E
****D
******C
********B
**********A

let result = "";

// Loop through the string in reverse


for (let i = [Link] - 1, stars = 0; i >= 0; i--) {
if (/[A-Z]/.test(a[i])) { // Check if the character is an alphabet
result += "*".repeat(stars) + a[i] + "\n";
stars += 2; // Increment stars for the next line
}
}

[Link](result);

--------------------------------------------------------------

//dot which follows the follows the cursor with delay


const circle = [Link]('div');

[Link] = '40px'; // Set width


[Link] = '40px'; // Set height
[Link] = '1px solid black';
[Link] = '50%';
[Link] = 'absolute';

function getCoordinates(event) {
const { clientX, clientY } = event;
[Link] = `${clientX - 20}px`;
[Link] = `${clientY - 20}px`;
}

[Link](circle);

[Link]('mousemove', getCoordinates);

----------------------------------------------------------

const promise = new Promise(res => res(2));

promise
.then(v => {
[Link](v);
return v * 2;
})
.then(v => {
[Link](v);
return v * 2;
})
.finally(v => {
[Link](v);
return 0;
})
.then(v => {
[Link](v);
});

// Output: 2,4,undefined, 8

Key Points:
finally does not alter the value passed down the chain.
Even though finally returns 0, it does not affect the value for the next .then.
The value passed to finally is always undefined.
This is because finally does not take the resolved or rejected value of the
promise.

-----------------------------------------------------------------------------------
-

var a = {}
var b = {key: "b"}
var c = {key: "c"}

a[b] = 600;
b[c] = 700;
[Link](a[c]) //600
[Link](a[b]) // 600
[Link](b[b]) // 700
[Link](b[c]) // 700

----------------------------------------------------------------------------------

const obj = [
{ apple: 2, orange: 1, banana: 3, grape: 1 },
{ apple: 2, orange: 1, banana: 3 },
{ apple: 2, orange: 1, banana: 3, grape: 2 },
];

// Expected Result
// {apple: 6, orange: 3, banana:9, grape: 3}

// using reduce method

const result = [Link]((acc, curr) => {


[Link](curr).forEach((key) => {
acc[key] = (acc[key] || 0) + curr[key];
});
return acc;
}, {});

[Link](result);

----------------------------------------------------------
let obj = [
{ Sno: 1, score: 20 },
{ Sno: 2, score: 30 },
{ Sno: 1, score: 50 },
];

let newArr = [Link](


[Link]((acc, curr) => {
if (acc[[Link]]) {
acc[[Link]].score += [Link]; // Sum the scores if Sno exists
} else {
acc[[Link]] = { ...curr }; // Add new entry
}
return acc;
}, {})
);

[Link](newArr);
// Output: [{ Sno: 1, score: 70 }, { Sno: 2, score: 30 }]

--------------------------------------------------------------------------

const user1 = { name: "Alice", age: 25 };


const user2 = { name: "Alice", age: 25 };

[Link]([Link](user1)=== [Link](user2));
user1 === user2
---------------------------------------------------------
const test = [{ name: 'Alice' }, { name: 'Bob' }];
const test2 = test;
test2[0].name = 'Charlie';

[Link]("test =>", test[0].name);


[Link]("test2 =>", test2[0].name);

-----------------------------------------------------------------
let name = "Bruce"
const person = {
name: 'Alice',
greet: function () {
[Link]([Link]);
},
hello: () => {
[Link](name)
}
};
[Link]()
[Link]()

You might also like