Loading...
More JavaScript Posts
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
const jwt = require("jsonwebtoken");const authToken = (req, res, next) => {const token = req.headers["x-auth-token"];try {req.user = jwt.verify(token, process.env.ACCESS_TOKEN_SECRET);next();} catch (err) {console.log(err.message);res.status(401).json({ msg: "Error authenticating token" });}};module.exports = authToken;
const dragAndDropDiv = editor.container;dragAndDropDiv.addEventListener('dragover', function(e) {e.stopPropagation();e.preventDefault();e.dataTransfer.dropEffect = 'copy';});dragAndDropDiv.addEventListener("drop",function(e){// Prevent default behavior (Prevent file from being opened)e.stopPropagation();e.preventDefault();const files = e.dataTransfer.items; // Array of all filesconsole.assert(files.length >= 1);if (files[0].kind === 'file') {var file = e.dataTransfer.items[0].getAsFile();const fileSize = file.size;const fileName = file.name;const fileMimeType = file.type;reader = new FileReader();reader.onloadend = function(){editor.setValue(reader.result);}reader.readAsText(file);}else{//Maybe handle if text is droppedconsole.log(files[0].kind);}});
var invertTree = function(root) {const reverseNode = node => {if (node == null) {return null}reverseNode(node.left);reverseNode(node.right);let holdLeft = node.left;node.left = node.right;node.right = holdLeft;return node;}return reverseNode(root);};
//JavaScript program to swap two variables//take input from the userslet a = prompt('Enter the first variable: ');let b = prompt('Enter the second variable: ');//using destructuring assignment[a, b] = [b, a];console.log(`The value of a after swapping: ${a}`);console.log(`The value of b after swapping: ${b}`);
const gcd = (...arr) => {const _gcd = (x, y) => (!y ? x : gcd(y, x % y));return [...arr].reduce((a, b) => _gcd(a, b));};gcd(8, 36); // 4gcd(...[12, 8, 32]); // 4