Skip to main content

next cpu

Nov 18, 2022AustinLeath
Loading...

More JavaScript Posts

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)

Get union of arrays

Nov 19, 2022CodeCatch

0 likes • 0 views

const union = (...arr) => [...new Set(arr.flat())];
// Example
union([1, 2], [2, 3], [3]); // [1, 2, 3]

Convert data to yyyy mm dd format

Nov 19, 2022CodeCatch

0 likes • 1 view

// `date` is a `Date` object
const formatYmd = date => date.toISOString().slice(0, 10);
// Example
formatYmd(new Date()); // 2020-05-06

containsDuplicate

Nov 19, 2022CodeCatch

0 likes • 0 views

let nums = [1,2,3,1]
var containsDuplicate = function(nums) {
let obj = {};
for(let i =0; i< nums.length; i++){
if(obj[nums[i]]){
obj[nums[i]] += 1;
return true;
}else{
obj[nums[i]] = 1;
}
}
return false;
};
console.log(containsDuplicate(nums));

Timer

Feb 5, 2021LeifMessinger

0 likes • 2 views

class Timer{
start(){
this.startTime = Date.now();
}
stop(){
const dt = Date.now() - this.startTime;
console.log(dt);
return dt;
}
getExecTime(fun, asynchronous){
return asynchronous ? this.getAsyncExecTime(fun) : this.getSyncExecTime(fun);
}
getSyncExecTime(fun){
this.start();
fun();
return this.stop();
}
async getAsyncExecTime(fun){
this.start();
await fun();
return this.stop();
}
static average(fun, numTimes, asynchronous = false){
const times = [];
const promises = [];
let timer = new Timer();
if(asynchronous){
for(let i = 0; i < numTimes; i++){
timer.getAsyncExecTime(fun);
}
}else{
for(let i = 0; i < numTimes; i++){
timer.getSyncExecTime(fun);
}
}
return (times => times.reduce(((sum, acc) => sume + acc), 0) / times.length);
}
static async timeAsync(fun, numTimes){
if(numTimes <= 1) return new Timer().getAsyncExecTime(fun);
const promises = [];
let timer = new Timer(true);
for(let i = 0; i < numTimes; i++){
promises.push(fun().catch((e)=>{}));
}
try{
await Promise.all(promises).catch((e)=>{});
}catch(e){
//do absolutely nothing
}
return timer.stop();
}
constructor(start = false){
if(start) this.start();
}
}

React - Lifting State

Jan 25, 2023CHS

1 like • 4 views

export const Main = () => {
const [title, setTitle] = useState('');
return (
<ChildComponent
title={title}
onChange={e => setTitle(e.target.value)}
/>
);
};
export const ChildComponent = ({ title, onChange }) => {
return (
<Box component="form" onSubmit={() => {}} noValidate mt={5}>
<TextField
fullWidth
id="title"
label="Title"
name="title"
autoComplete="title"
autoFocus
color="primary"
variant="filled"
InputLabelProps={{ shrink: true }}
value={title}
onChange={onChange}
/>
</Box>
);
};