Skip to main content

React Short Circuit Evaluation

Feb 3, 2021CHS
Loading...

More JavaScript Posts

Extracting components

Nov 19, 2022CodeCatch

0 likes • 2 views

function formatDate(date) {
return date.toLocaleDateString();
}
function Comment(props) {
return (
<div className="Comment">
<div className="UserInfo">
<img
className="Avatar"
src={props.author.avatarUrl}
alt={props.author.name}
/>
<div className="UserInfo-name">
{props.author.name}
</div>
</div>
<div className="Comment-text">{props.text}</div>
<div className="Comment-date">
{formatDate(props.date)}
</div>
</div>
);
}
const comment = {
date: new Date(),
text: 'I hope you enjoy learning React!',
author: {
name: 'Hello Kitty',
avatarUrl: 'https://placekitten.com/g/64/64',
},
};
ReactDOM.render(
<Comment
date={comment.date}
text={comment.text}
author={comment.author}
/>,
document.getElementById('root')
);

copy to clipboard

Nov 19, 2022CodeCatch

0 likes • 0 views

const copyToClipboard = str => {
const el = document.createElement('textarea');
el.value = str;
el.setAttribute('readonly', '');
el.style.position = 'absolute';
el.style.left = '-9999px';
document.body.appendChild(el);
const selected =
document.getSelection().rangeCount > 0
? document.getSelection().getRangeAt(0)
: false;
el.select();
document.execCommand('copy');
document.body.removeChild(el);
if (selected) {
document.getSelection().removeAllRanges();
document.getSelection().addRange(selected);
}
};
copyToClipboard('Lorem ipsum'); // 'Lorem ipsum' copied to clipboard.

Destructuring Assignment

Nov 19, 2022CodeCatch

0 likes • 0 views

//JavaScript program to swap two variables
//take input from the users
let 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}`);

Subsets of an array

Nov 19, 2022CodeCatch

0 likes • 2 views

const getSubsets = arr => arr.reduce((prev, curr) => prev.concat(prev.map(k => k.concat(curr))), [[]]);
// Examples
getSubsets([1, 2]); // [[], [1], [2], [1, 2]]
getSubsets([1, 2, 3]); // [[], [1], [2], [1, 2], [3], [1, 3], [2, 3], [1, 2, 3]]

greatest common denominator

Nov 19, 2022CodeCatch

0 likes • 0 views

const gcd = (...arr) => {
const _gcd = (x, y) => (!y ? x : gcd(y, x % y));
return [...arr].reduce((a, b) => _gcd(a, b));
};
gcd(8, 36); // 4
gcd(...[12, 8, 32]); // 4
function printHeap(heap, index, level) {
if (index >= heap.length) {
return;
}
console.log(" ".repeat(level) + heap[index]);
printHeap(heap, 2 * index + 1, level + 1);
printHeap(heap, 2 * index + 2, level + 1);
}
//You can call this function by passing in the heap array and the index of the root node, which is typically 0, and level = 0.
let heap = [3, 8, 7, 15, 17, 30, 35, 2, 4, 5, 9];
printHeap(heap,0,0)