0% found this document useful (0 votes)
13 views5 pages

Assessment 3

The document contains examples of code snippets demonstrating different JavaScript concepts like sorting algorithms, object comparison, React components, MongoDB aggregation queries and more.

Uploaded by

yumikajuco
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)
13 views5 pages

Assessment 3

The document contains examples of code snippets demonstrating different JavaScript concepts like sorting algorithms, object comparison, React components, MongoDB aggregation queries and more.

Uploaded by

yumikajuco
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
You are on page 1/ 5

//answer No.

1//

function quickSort(arr) {
if (arr.length < 2) {
return arr;
}
const pivot = arr[Math.floor(Math.random() * arr.length)];

let left = [];


let right = [];
let equal = [];

for (let val of arr) {


if (val < pivot) {
left.push(val);
} else if (val > pivot) {
right.push(val);
} else {
equal.push(val);
}
}
return [
...quickSort(left),
...equal,
...quickSort(right)
];
}

//answer No.2//

function insertionSort(inputArr) {
let n = inputArr.length;
for (let i = 1; i < n; i++) {
// Choosing the first element in our unsorted subarray
let current = inputArr[i];
// The last element of our sorted subarray
let j = i-1;
while ((j > -1) && (current < inputArr[j])) {
inputArr[j+1] = inputArr[j];
j--;
}
inputArr[j+1] = current;
}
return inputArr;
}

//amswer No.3//

function merge(left, right) {


let arr = []
while (left.length && right.length) {
// Pick the smaller among the smallest element of left and right sub arrays

if (left[0] < right[0]) {


arr.push(left.shift())
} else {
arr.push(right.shift())
}
}
return [ ...arr, ...left, ...right ]
}

//amswer No.4//
var has = {
name: 'dragon',
surname: 'caterpillar',
skills: {
football: true,
basketball: true,
volleyball: true
}
}

var pas = {
name: 'deer',
surname: 'caterpillar',
skills: {
football: true,
basketball: false,
volleyball: false
}
}

function compare(Obj1, Obj2) {


var values1 = Object.values(Obj1);
var values2 = Object.values(Obj2);
var equivalent = [];

var keys = Object.keys(Obj1);


keys.forEach(k => {
if (Obj1.hasOwnProperty(k) && Obj2.hasOwnProperty(k)) {
if (typeof Obj1[k] === 'object') {
let recursiveAnswer = compare(Obj1[k], Obj2[k]);
equivalent.push(...recursiveAnswer);
} else if (Obj1[k] === Obj2[k]) {
equivalent.push(Obj1[k]);
}
}
});

return equivalent;
}

let equiv = compare(has, pas);


console.log(equiv);

//amswer No.5//
var startTime = performance.now();

var endTime = performance.now();


console.log("Time taken: " + (endTime - startTime) + " milliseconds");

//amswer No.6//
class Cylinder {
constructor(height, radius) {
this.height = height;
this.radius = radius;
}

get volume() {
return (Math.PI * this.radius * this.radius * this.height).toFixed(4);
}
}

const cylinder = new Cylinder(7, 4);


console.log("Volume of cylinder:", cylinder.volume);

//answer No.7//
class Animal {
constructor(name) {
this.name = name;
}

speak() {
console.log(`${this.name} makes a noise.`);
}
}

class Cat extends Animal {


speak() {
console.log(`${this.name} meow.`);
}
}

const Cat = new Cat("Rufus");


Cat.speak();

//answer No.8//
import React from "react";

//initialize parent class//


class MyComponent extends React.Component {
constructor(props) {
super(props);
this.state = {
count: 0,
};
}

//display a title passed in as a prop//


render() {
return (
<div>
<h1>{this.props.title}</h1>
<p>Count: {this.state.count}</p>
//count when clicked//
<button onClick={() => this.setState({ count: this.state.count + 1 })}>
Increment
</button>
</div>
);
}
}

export default MyComponent;


//answer No.9//
import React, { useState } from 'react';

function Example() {
// Declare a new state variable, which we'll call "count"
const [count, setCount] = useState(0);

return (
<div>
<p>You clicked {count} times</p>
<button onClick={() => setCount(count + 1)}>
Click me
</button>
</div>
);
}

//answer No.10//
//Stateless component//
import React from 'react';

function Greeting(props) {
return <h1>Hello, {props.name}!</h1>;
}

//statefull component//
import React, { Component } from 'react';

class Counter extends Component {


constructor(props) {
super(props);
this.state = { count: 0 };
}

render() {
return (
<div>
<p>You clicked {this.state.count} times</p>
<button onClick={() => this.setState({ count: this.state.count + 1 })}>
Click me
</button>
</div>
);
}
}

//answer No.11//
db.posts.aggregate([
{
$group: {
_id: { $dateToString: { format: "%m-%d-%Y", date: "$createdAt" } },
avgLikes: { $avg: "$likes" }
}
}
]);

//answer No.12//
db.sms.aggregate([
{
$group: {
_id: null,
totalSMS: { $sum: { $ceil: { $divide: [ "$size", 132 ] } } }
}
}
]);

//answer No.13//
db.collection.update(
{ _id: ObjectId("5f7c6d4a7f8b9d0e2f3e9a1c"), "items.name": "Apple" },
{ $inc: { "items.$.count": 1 } }
);

//answer No.14//
{
"_id": "cust1",
"name": "Kim Doo",
"email": "[email protected]",
"orders": [
{
"_id": "order101",
"item": "Item A",
"quantity": 3,
"price": 15.99
},
{
"_id": "order102",
"item": "Item B",
"quantity": 1,
"price": 8.50
}
]
}

//answer No.15//
//Here is an example JSON document that includes an index on the timestamp field://
{
"_id": "document1",
"timestamp": "2023-05-25T13:00:00Z",
"field1": "value1",
"field2": "value2",
...
}

// Index JSON
{
"timestamp": -1
}
// Index type
"non-capped"

//with this index in place, you can use the following query to retrieve the last
100 documents://
db.collection.find().sort({timestamp: -1}).limit(100)

You might also like