Loading...
More JavaScript Posts
const binomialCoefficient = (n, k) => {if (Number.isNaN(n) || Number.isNaN(k)) return NaN;if (k < 0 || k > n) return 0;if (k === 0 || k === n) return 1;if (k === 1 || k === n - 1) return n;if (n - k < k) k = n - k;let res = n;for (let j = 2; j <= k; j++) res *= (n - j + 1) / j;return Math.round(res);};binomialCoefficient(8, 2); // 28
import React, { useState, useEffect } from 'react';import Link from 'next/link';export default function CookieBanner() {// Initialize with a default value (false if not previously set in localStorage)const [cookieConsent, setCookieConsent] = useState(() =>localStorage.getItem('cookieConsent') === 'true' ? true : false);useEffect(() => {const newCookieConsent = cookieConsent ? 'granted' : 'denied';window.gtag('consent', 'update', {analytics_storage: newCookieConsent});localStorage.setItem('cookieConsent', String(cookieConsent));}, [cookieConsent]);return !cookieConsent && (<div><div><p>We use cookies to enhance the user experience.{' '}<Link href='/privacy/'>View privacy policy</Link></p></div><div><button type="button" onClick={() => setCookieConsent(false)}>Decline</button><button type="button" onClick={() => setCookieConsent(true)}>Allow</button></div></div>)}
const formatDuration = ms => {if (ms < 0) ms = -ms;const time = {day: Math.floor(ms / 86400000),hour: Math.floor(ms / 3600000) % 24,minute: Math.floor(ms / 60000) % 60,second: Math.floor(ms / 1000) % 60,millisecond: Math.floor(ms) % 1000};return Object.entries(time).filter(val => val[1] !== 0).map(([key, val]) => `${val} ${key}${val !== 1 ? 's' : ''}`).join(', ');};formatDuration(1001); // '1 second, 1 millisecond'formatDuration(34325055574); // '397 days, 6 hours, 44 minutes, 15 seconds, 574 milliseconds'
const compactObject = val => {const data = Array.isArray(val) ? val.filter(Boolean) : val;return Object.keys(data).reduce((acc, key) => {const value = data[key];if (Boolean(value))acc[key] = typeof value === 'object' ? compactObject(value) : value;return acc;},Array.isArray(val) ? [] : {});};const obj = {a: null,b: false,c: true,d: 0,e: 1,f: '',g: 'a',h: [null, false, '', true, 1, 'a'],i: { j: 0, k: false, l: 'a' }};compactObject(obj);// { c: true, e: 1, g: 'a', h: [ true, 1, 'a' ], i: { l: 'a' } }
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 keyhosts.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 childrenhosts.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 depthparent.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 resultresult.push(node.data);// Visit children nodes firstnode.children.forEach((child) => {inOrder(child);});}inOrder(node);return result;}// Usage exampleconst 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 objectsfunction convertTreeToArray(nodes) {const result = [];nodes.forEach((node) => {result.push(...treeToObjects(node));});return result;}// Convert the tree back to an array of objectsconst arrayFromTree = convertTreeToArray(tree);console.log(arrayFromTree);
const luhnCheck = num => {let arr = (num + '').split('').reverse().map(x => parseInt(x));let lastDigit = arr.splice(0, 1)[0];let sum = arr.reduce((acc, val, i) => (i % 2 !== 0 ? acc + val : acc + ((val *= 2) > 9 ? val - 9 : val)),0);sum += lastDigit;return sum % 10 === 0;};luhnCheck('4485275742308327'); // trueluhnCheck(6011329933655299); // trueluhnCheck(123456789); // false