Loading...
More JavaScript Posts
const express = require('express')const app = express()const port = 3000app.get('/', (req, res) => {res.send('Hello World!')})app.listen(port, () => {console.log(`Example app listening on port ${port}`)})
class TreeNode {constructor(key, value = key, parent = null) {this.key = key;this.value = value;this.parent = parent;this.children = [];}get isLeaf() {return this.children.length === 0;}get hasChildren() {return !this.isLeaf;}}class Tree {constructor(key, value = key) {this.root = new TreeNode(key, value);}*preOrderTraversal(node = this.root) {yield node;if (node.children.length) {for (let child of node.children) {yield* this.preOrderTraversal(child);}}}*postOrderTraversal(node = this.root) {if (node.children.length) {for (let child of node.children) {yield* this.postOrderTraversal(child);}}yield node;}insert(parentNodeKey, key, value = key) {for (let node of this.preOrderTraversal()) {if (node.key === parentNodeKey) {node.children.push(new TreeNode(key, value, node));return true;}}return false;}remove(key) {for (let node of this.preOrderTraversal()) {const filtered = node.children.filter(c => c.key !== key);if (filtered.length !== node.children.length) {node.children = filtered;return true;}}return false;}find(key) {for (let node of this.preOrderTraversal()) {if (node.key === key) return node;}return undefined;}}const tree = new Tree(1, 'AB');tree.insert(1, 11, 'AC');tree.insert(1, 12, 'BC');tree.insert(12, 121, 'BG');[...tree.preOrderTraversal()].map(x => x.value);// ['AB', 'AC', 'BC', 'BCG']tree.root.value; // 'AB'tree.root.hasChildren; // truetree.find(12).isLeaf; // falsetree.find(121).isLeaf; // truetree.find(121).parent.value; // 'BC'tree.remove(12);[...tree.postOrderTraversal()].map(x => x.value);// ['AC', 'AB']
const getTimezone = () => Intl.DateTimeFormat().resolvedOptions().timeZone;// ExamplegetTimezone();
alert("bruh")
const celsiusToFahrenheit = (celsius) => celsius * 9/5 + 32;const fahrenheitToCelsius = (fahrenheit) => (fahrenheit - 32) * 5/9;// ExamplescelsiusToFahrenheit(15); // 59celsiusToFahrenheit(0); // 32celsiusToFahrenheit(-20); // -4fahrenheitToCelsius(59); // 15fahrenheitToCelsius(32); // 0
const kNearestNeighbors = (data, labels, point, k = 3) => {const kNearest = data.map((el, i) => ({dist: Math.hypot(...Object.keys(el).map(key => point[key] - el[key])),label: labels[i]})).sort((a, b) => a.dist - b.dist).slice(0, k);return kNearest.reduce((acc, { label }, i) => {acc.classCounts[label] =Object.keys(acc.classCounts).indexOf(label) !== -1? acc.classCounts[label] + 1: 1;if (acc.classCounts[label] > acc.topClassCount) {acc.topClassCount = acc.classCounts[label];acc.topClass = label;}return acc;},{classCounts: {},topClass: kNearest[0].label,topClassCount: 0}).topClass;};const data = [[0, 0], [0, 1], [1, 3], [2, 0]];const labels = [0, 1, 1, 0];kNearestNeighbors(data, labels, [1, 2], 2); // 1kNearestNeighbors(data, labels, [1, 0], 2); // 0