Loading...
More JavaScript Posts
const euclideanDistance = (a, b) =>Math.hypot(...Object.keys(a).map(k => b[k] - a[k]));euclideanDistance([1, 1], [2, 3]); // ~2.2361euclideanDistance([1, 1, 1], [2, 3, 2]); // ~2.4495
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}`)})
const longestPalindrome = (s) => {if(s.length === 1) return sconst odd = longestOddPalindrome(s)const even = longestEvenPalindrome(s)if(odd.length >= even.length) return oddif(even.length > odd.length) return even};const longestOddPalindrome = (s) => {let longest = 0let longestSubStr = ""for(let i = 1; i < s.length; i++) {let currentLongest = 1let currentLongestSubStr = ""let left = i - 1let right = i + 1while(left >= 0 && right < s.length) {const leftLetter = s[left]const rightLetter = s[right]left--right++if(leftLetter === rightLetter) {currentLongest += 2currentLongestSubStr = s.slice(left+1, right)} else break}if(currentLongest > longest) {if(currentLongestSubStr) longestSubStr = currentLongestSubStrelse longestSubStr = s[i]longest = currentLongest}}return longestSubStr}const longestEvenPalindrome = (s) => {let longest = 0let longestSubStr = ""for(let i = 0; i < s.length - 1; i++) {if(s[i] !== s[i+1]) continue;let currentLongest = 2let currentLongestSubStr = ""let left = i - 1let right = i + 2while(left >= 0 && right < s.length) {const leftLetter = s[left]const rightLetter = s[right]left--right++if(leftLetter === rightLetter) {currentLongest += 2currentLongestSubStr = s.slice(left+1, right)} else break}if(currentLongest > longest) {if(currentLongestSubStr) longestSubStr = currentLongestSubStrelse longestSubStr = s[i] + s[i+1]longest = currentLongest}}return longestSubStr}console.log(longestPalindrome("babad"))
const quickSort = arr => {const a = [...arr];if (a.length < 2) return a;const pivotIndex = Math.floor(arr.length / 2);const pivot = a[pivotIndex];const [lo, hi] = a.reduce((acc, val, i) => {if (val < pivot || (val === pivot && i != pivotIndex)) {acc[0].push(val);} else if (val > pivot) {acc[1].push(val);}return acc;},[[], []]);return [...quickSort(lo), pivot, ...quickSort(hi)];};console.log(quickSort([1, 6, 1, 5, 3, 2, 1, 4])) // [1, 1, 1, 2, 3, 4, 5, 6]
// Get the text that the user has selectedconst getSelectedText = () => window.getSelection().toString();getSelectedText();
new StringBuilder(hi).reverse().toString()