Skip to main content

Generate a random HEX color

Nov 18, 2022AustinLeath
Loading...

More JavaScript Posts

Invert Binary Tree

Oct 15, 2022CodeCatch

2 likes • 6 views

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

array shuffle

Nov 19, 2022CodeCatch

0 likes • 0 views

const shuffle = ([...arr]) => {
let m = arr.length;
while (m) {
const i = Math.floor(Math.random() * m--);
[arr[m], arr[i]] = [arr[i], arr[m]];
}
return arr;
};
const foo = [1, 2, 3];
shuffle(foo); // [2, 3, 1], foo = [1, 2, 3]

Monotonic Array

Nov 19, 2022CodeCatch

0 likes • 2 views

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

quick sort

Nov 19, 2022CodeCatch

0 likes • 0 views

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)];
};
quickSort([1, 6, 1, 5, 3, 2, 1, 4]); // [1, 1, 1, 2, 3, 4, 5, 6]

copyString.js

Nov 8, 2023LeifMessinger

0 likes • 5 views

function copyString(text){
async function navigatorClipboardCopy(text){
if(document.location.protocol != "https:"){
return false;
}
return new Promise((resolve, reject)=>{
navigator.clipboard.writeText(text).then(()=>{resolve(true);}, ()=>{resolve(false);});
});
}
function domCopy(text){
if(!(document.execCommand)){
console.warn("They finally deprecated document.execCommand!");
}
const input = document.createElement('textarea');
input.value = text;
document.body.appendChild(input);
input.select();
const success = document.execCommand('copy');
document.body.removeChild(input);
return success;
}
function promptCopy(){
prompt("Copy failed. Might have ... somewhere. Check console.", text);
console.log(text);
}
function done(){
alert("Copied to clipboard");
}
navigatorClipboardCopy(text).catch(()=>{return false;}).then((success)=>{
if(success){
done();
}else{
if(domCopy(text)){
done();
}else{
promptCopy();
}
}
});
}

Reverse a string in Java

Nov 20, 2022Helper

0 likes • 1 view

new StringBuilder(hi).reverse().toString()