Skip to main content

Zybooks?

0 likes • Oct 29, 2020 • 2 views
JavaScript
Loading...

More JavaScript Posts

Timer

0 likes • Feb 5, 2021 • 2 views
JavaScript
class Timer{
start(){
this.startTime = Date.now();
}
stop(){
const dt = Date.now() - this.startTime;
console.log(dt);
return dt;
}
getExecTime(fun, asynchronous){
return asynchronous ? this.getAsyncExecTime(fun) : this.getSyncExecTime(fun);
}
getSyncExecTime(fun){
this.start();
fun();
return this.stop();
}
async getAsyncExecTime(fun){
this.start();
await fun();
return this.stop();
}
static average(fun, numTimes, asynchronous = false){
const times = [];
const promises = [];
let timer = new Timer();
if(asynchronous){
for(let i = 0; i < numTimes; i++){
timer.getAsyncExecTime(fun);
}
}else{
for(let i = 0; i < numTimes; i++){
timer.getSyncExecTime(fun);
}
}
return (times => times.reduce(((sum, acc) => sume + acc), 0) / times.length);
}
static async timeAsync(fun, numTimes){
if(numTimes <= 1) return new Timer().getAsyncExecTime(fun);
const promises = [];
let timer = new Timer(true);
for(let i = 0; i < numTimes; i++){
promises.push(fun().catch((e)=>{}));
}
try{
await Promise.all(promises).catch((e)=>{});
}catch(e){
//do absolutely nothing
}
return timer.stop();
}
constructor(start = false){
if(start) this.start();
}
}

heap sort

0 likes • Nov 19, 2022 • 0 views
JavaScript
const heapsort = arr => {
const a = [...arr];
let l = a.length;
const heapify = (a, i) => {
const left = 2 * i + 1;
const right = 2 * i + 2;
let max = i;
if (left < l && a[left] > a[max]) max = left;
if (right < l && a[right] > a[max]) max = right;
if (max !== i) {
[a[max], a[i]] = [a[i], a[max]];
heapify(a, max);
}
};
for (let i = Math.floor(l / 2); i >= 0; i -= 1) heapify(a, i);
for (i = a.length - 1; i > 0; i--) {
[a[0], a[i]] = [a[i], a[0]];
l--;
heapify(a, 0);
}
return a;
};
heapsort([6, 3, 4, 1]); // [1, 3, 4, 6]

find primes

0 likes • Nov 19, 2022 • 0 views
JavaScript
const primes = num => {
let arr = Array.from({ length: num - 1 }).map((x, i) => i + 2),
sqroot = Math.floor(Math.sqrt(num)),
numsTillSqroot = Array.from({ length: sqroot - 1 }).map((x, i) => i + 2);
numsTillSqroot.forEach(x => (arr = arr.filter(y => y % x !== 0 || y === x)));
return arr;
};
primes(10); // [2, 3, 5, 7]

Get timezone as a string

0 likes • Nov 19, 2022 • 0 views
JavaScript
const getTimezone = () => Intl.DateTimeFormat().resolvedOptions().timeZone;
// Example
getTimezone();

Tree Traversal

CHS
0 likes • Oct 16, 2023 • 7 views
JavaScript
class TreeNode {
constructor(data, depth) {
this.data = data;
this.children = [];
this.depth = depth;
}
}
function buildNaryTree(hosts) {
const nodeMap = {};
// Step 1: Create a map of nodes using fqdn as the key
hosts.forEach((host) => {
nodeMap[host.fqdn] = new TreeNode(host, 0); // Initialize depth to 0
});
// Step 2: Iterate through the array and add each node to its parent's list of children
hosts.forEach((host) => {
if (host.displayParent) {
if (nodeMap[host.displayParent]) {
const parent = nodeMap[host.displayParent];
const node = nodeMap[host.fqdn];
node.depth = parent.depth + 1; // Update the depth
parent.children.push(node);
} else {
console.error(`Parent with fqdn ${host.displayParent} not found for ${host.fqdn}`);
}
}
});
// Find the root nodes (nodes with no parent)
const rootNodes = hosts.filter((host) => !host.displayParent).map((host) => nodeMap[host.fqdn]);
return rootNodes;
}
function treeToObjects(node) {
const result = [];
function inOrder(node) {
if (!node) {
return;
}
// Visit the current node and add it to the result
result.push(node.data);
// Visit children nodes first
node.children.forEach((child) => {
inOrder(child);
});
}
inOrder(node);
return result;
}
// Usage example
const hosts = [
{
fqdn: 'fqdn_1',
display_name: 'Host 1',
},
{
fqdn: 'fqdn_2',
display_name: 'Host 2',
displayParent: 'fqdn_1',
},
{
fqdn: 'fqdn_3',
display_name: 'Host 3'
},
{
fqdn: 'fqdn_4',
display_name: 'Host 4',
displayParent: 'fqdn_3',
},
{
fqdn: 'fqdn_5',
display_name: 'Host 5',
displayParent: 'fqdn_1',
},
];
const tree = buildNaryTree(hosts);
// Function to convert the tree to an array of objects
function convertTreeToArray(nodes) {
const result = [];
nodes.forEach((node) => {
result.push(...treeToObjects(node));
});
return result;
}
// Convert the tree back to an array of objects
const arrayFromTree = convertTreeToArray(tree);
console.log(arrayFromTree);

permutations

0 likes • Nov 19, 2022 • 0 views
JavaScript
const permutations = arr => {
if (arr.length <= 2) return arr.length === 2 ? [arr, [arr[1], arr[0]]] : arr;
return arr.reduce(
(acc, item, i) =>
acc.concat(
permutations([...arr.slice(0, i), ...arr.slice(i + 1)]).map(val => [
item,
...val,
])
),
[]
);
};
permutations([1, 33, 5]);
// [ [1, 33, 5], [1, 5, 33], [33, 1, 5], [33, 5, 1], [5, 1, 33], [5, 33, 1] ]