Skip to main content

Untitled

0 likes • Apr 14, 2023 • 8 views
JavaScript
Loading...

More JavaScript Posts

arithmetic progression

0 likes • Nov 19, 2022 • 0 views
JavaScript
const arithmeticProgression = (n, lim) =>
Array.from({ length: Math.ceil(lim / n) }, (_, i) => (i + 1) * n );
arithmeticProgression(5, 25); // [5, 10, 15, 20, 25]

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

Monotonic Array

0 likes • Nov 19, 2022 • 2 views
JavaScript
// Time Complexity : O(N)
// Space Complexity : O(1)
var isMonotonic = function(nums) {
let isMono = null;
for(let i = 1; i < nums.length; i++) {
if(isMono === null) {
if(nums[i - 1] < nums[i]) isMono = 0;
else if(nums[i - 1] > nums[i]) isMono = 1;
continue;
}
if(nums[i - 1] < nums[i] && isMono !== 0) {
return false;
}
else if(nums[i - 1] > nums[i] && isMono !== 1) {
return false;
}
}
return true;
};
let nums1 = [1,2,2,3]
let nums2 = [6,5,4,4]
let nums3 = [1,3,2]
console.log(isMonotonic(nums1));
console.log(isMonotonic(nums2));
console.log(isMonotonic(nums3));

Express Login Endpoint

CHS
0 likes • Mar 11, 2021 • 4 views
JavaScript
router.post("/", async (req, res) => {
const { email, password } = req.body;
try {
if (!email) return res.status(400).json({ msg: "An email is required" });
if (!password)
return res.status(400).json({ msg: "A password is required" });
const user = await User.findOne({ email }).select("_id password");
if (!user) return res.status(400).json({ msg: "Invalid credentials" });
const match = await bcrypt.compare(password, user.password);
if (!match) return res.status(400).json({ msg: "Invalid credentials" });
const accessToken = genAccessToken({ id: user._id });
const refreshToken = genRefreshToken({ id: user._id });
res.cookie("token", refreshToken, {
expires: new Date(Date.now() + 604800),
httpOnly: true,
});
res.json({ accessToken });
} catch (err) {
console.log(err.message);
res.status(500).json({ msg: "Error logging in user" });
}
});

native data structures

0 likes • Nov 19, 2022 • 0 views
JavaScript
const nums = [1, 2, 3];
const strs = Array.from('est');
nums.push(6);
nums.push(4, 9);
strs.unshift('t');
nums.length; // 6
nums[nums.length - 1]; // 9
strs[0]; // 't'
strs[2]; // 's'
nums.slice(1, 3); // [2, 3]
nums.map(n => n * 2); // [2, 4, 6, 12, 8, 18]
nums.filter(n => n % 2 === 0); // [2, 6, 4]
nums.reduce((a, n) => a + n, 0); // 25
strs.reverse(); // ['t', 's', 'e', 't']
strs.join(''); // 'test'
const nums = new Set([1, 2, 3]);
nums.add(4);
nums.add(1);
nums.add(5);
nums.add(4);
nums.size; // 5
nums.has(4); // true
nums.delete(4);
nums.has(4); // false
[...nums]; // [1, 2, 3, 5]
nums.clear();
nums.size; // 0
const items = new Map([
[1, { name: 'John' }],
[2, { name: 'Mary' }]
]);
items.set(4, { name: 'Alan' });
items.set(2, { name: 'Jeff' });
items.size; // 3
items.has(4); // true
items.get(2); // { name: 'Jeff' }
items.delete(2);
items.size; // 2
[...items.keys()]; // [1, 4]
[...items.values()]; // [{ name: 'John' }, { name: 'Alan' }]
items.clear();
items.size; // 0

levenshtein distance

0 likes • Nov 19, 2022 • 1 view
JavaScript
const levenshteinDistance = (s, t) => {
if (!s.length) return t.length;
if (!t.length) return s.length;
const arr = [];
for (let i = 0; i <= t.length; i++) {
arr[i] = [i];
for (let j = 1; j <= s.length; j++) {
arr[i][j] =
i === 0
? j
: Math.min(
arr[i - 1][j] + 1,
arr[i][j - 1] + 1,
arr[i - 1][j - 1] + (s[j - 1] === t[i - 1] ? 0 : 1)
);
}
}
return arr[t.length][s.length];
};
levenshteinDistance('duck', 'dark'); // 2