Skip to main content

Clone an array

0 likes • Nov 19, 2022 • 0 views
JavaScript
Loading...

More JavaScript Posts

return array head

0 likes • Nov 19, 2022 • 0 views
JavaScript
const head = arr => (arr && arr.length ? arr[0] : undefined);
head([1, 2, 3]); // 1
head([]); // undefined
head(null); // undefined
head(undefined); // undefined

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);

Function promisification

0 likes • Nov 19, 2022 • 0 views
JavaScript
// promisify(f, true) to get array of results
function promisify(f, manyArgs = false) {
return function (...args) {
return new Promise((resolve, reject) => {
function callback(err, ...results) { // our custom callback for f
if (err) {
reject(err);
} else {
// resolve with all callback results if manyArgs is specified
resolve(manyArgs ? results : results[0]);
}
}
args.push(callback);
f.call(this, ...args);
});
};
}
// usage:
f = promisify(f, true);
f(...).then(arrayOfResults => ..., err => ...);

bucket sort

0 likes • Nov 19, 2022 • 0 views
JavaScript
const bucketSort = (arr, size = 5) => {
const min = Math.min(...arr);
const max = Math.max(...arr);
const buckets = Array.from(
{ length: Math.floor((max - min) / size) + 1 },
() => []
);
arr.forEach(val => {
buckets[Math.floor((val - min) / size)].push(val);
});
return buckets.reduce((acc, b) => [...acc, ...b.sort((a, b) => a - b)], []);
};
bucketSort([6, 3, 4, 1]); // [1, 3, 4, 6]

greatest common denominator

0 likes • Nov 19, 2022 • 0 views
JavaScript
const gcd = (...arr) => {
const _gcd = (x, y) => (!y ? x : gcd(y, x % y));
return [...arr].reduce((a, b) => _gcd(a, b));
};
gcd(8, 36); // 4
gcd(...[12, 8, 32]); // 4

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]