import { useRef, useEffect, useState } from 'react';
export default function App() {
const [count, setCount] = useState(0);
const countRef = useRef();
countRef.current = count;
useEffect(() => {
const clickEvent = () => {
console.log(`CountRef: ${countRef.current}`);
};
document.addEventListener('click', clickEvent);
return () => {
document.removeEventListener('click', clickEvent);
};
}, [countRef]);
return (
<div>
<button onClick={() => setCount((n) => n + 1)}>Count: {count}</button>
</div>
);
}
useEffect(() => {
countRef.current = count;
}, [countRef, count]);
const obj = {
a: 123,
b: {
v: 'qq'
},
c: {
x: {}
},
};
obj.c.d = obj.b; // перекрестная ссылка
obj.c.r = obj; // кольцевая ссылка
const norm = {
'#0': {
a: 123,
b: '#1',
c: {
x: {},
d: '#1',
r: '#0'
},
},
'#1': {
v: 'qq'
}
}
function getHeightRec(arr, height1, height2, max) {
if (arr.length === 0) {
return max;
}
let result;
const lastItem = arr.pop();
if (height1 === height2) {
result = Math.max(
getHeightRec(arr, height1, height2, height2),
getHeightRec(arr, height1 + lastItem, height2, height2)
);
} else {
result = Math.max(
getHeightRec(arr, height1, height2, max),
getHeightRec(arr, height1 + lastItem, height2, max),
getHeightRec(arr, height1, height2 + lastItem, max)
);
}
arr.push(lastItem);
return result;
}
function getHeight(arr) {
return getHeightRec(arr, 0, 0, 0);
}
function processDirection(arr, first, end, step) {
let top = -1;
for (let i = first; i !== end; i += step) {
const value = arr[i];
if (value <= top) {
arr[i] = -1;
} else {
top = value;
}
top--;
}
}
function updateArray(arr) {
processDirection(arr, 0, arr.length, 1);
processDirection(arr, arr.length - 1, -1, -1);
return arr;
}
// --------
updateArray([5, 1, 1, 0, 2, 1, 1, 0]); // [5, -1, -1, -1, 2, -1, 1, -1]