arr.map((item) => ({ ...item, averagePrice: item.finance / item.physicalVolume }));
for (const entry of data) {
const row = table.insertRow(-1);
row.insertCell(-1).textContent = entry.alpha2Code;
row.insertCell(-1).innerHTML = `<img src="${entry.flag}" alt="" />`;
row.insertCell(-1).textContent = entry.name;
row.insertCell(-1).textContent = entry.capital ?? '-';
row.insertCell(-1).textContent = entry.population;
}
const count = 2;
export default await Promise.all(
Array.from({ length: count }, async (_, index) => (await import(`./data${index + 1}.js`)).default)
);
const getSubstringAfter = (string, char, iterations) => {
let pos = -1;
for (let i = 0; i < iterations; i++) {
pos = string.indexOf(char, pos + 1);
}
return string.slice(pos + 1);
};
getSubstringAfter(str, '-', 2);
str.split('-').slice(2).join('-');
str.replace(/([^-]+\-){2}/, '');
str.match(/(?:[^-]+\-){2}(.*)/)?.[1]
const createPersistCounter = (name) => {
let value = Number(localStorage.getItem(name) || '');
if (Number.isNaN(value)) {
value = 0;
}
const action = (fn) => () => {
fn();
localStorage.setItem(name, value);
};
const inc = action(() => (value += 1));
const dec = action(() => (value -= 1));
const reset = action(() => (value = 0));
return {
get value() {
return value;
},
inc,
dec,
reset
};
};
const counter = createPersistCounter('clicks');
counter.inc(); // localStorage['clicks'] == 1
counter.inc(); // localStorage['clicks'] == 2
- modal.classList.add('modal_show')
const modalContent = modal.querySelector('.modal__content')
if ( (modal.classList.contains('modal_show')) && (e.target != modalContent) ) {
modal.classList.remove('modal_show')
+ } else {
+ modal.classList.add('modal_show')
+ }
let p = new Promise((res, rej) => {
// Ждем 7сек; вызываем функцию res с аргументом 2
setTimeout(res, 7000, 2);
})
// Возвращаем новый промис; ждем 5сек; вызываем функцию res с аргументом 6 (2 + 4)
.then((data) => new Promise((res) => setTimeout(res, 5000, data + 4)))
.then((data) => console.log('data', data)); // 'data' 6
setTimeout(() => console.log(p), 10000); // Просто выведем промис
{MenuItems.map((item) => Object.entries(item).map(([headers, headersItems]) => (
<div className={s.wrapperSections}>
<img src={tile} alt={Object.entries(headersItems)[0][0]} />
<span>{headers}</span>
</div>
))}
array.map(([author, text]) => ({ author, text }))
array.reduce((acc, [author, text]) => [...acc, { author, text }], [])
array.reduce((acc, [author, text]) => (acc.push({ author, text }), acc), [])
array.reduce((acc, [author, text]) => {
acc.push({ author, text });
return acc;
}, [])
array.reduce((acc, pair) => {
acc.push({
author: pair[0],
text: pair[1]
});
return acc;
}, [])
for
если Вам это необходимо. useState<T | null>(null)
, т.к. в таком случае можно легко проверить значение в условном рендеринге. А если Вы объявите в вашем компоненте нечто вроде React.FC<{ data: T }>
, то Object
(точнее ничего, кроме T
честным путём) не сможете внутрь прокинуть.const formatter = new Intl.DateTimeFormat('en-US', {
timeZone: 'America/New_York',
weekday: 'long',
hour12: false,
hour: 'numeric',
minute: 'numeric'
});
const parts = formatter.formatToParts(new Date()).reduce((acc, entry) => ({
...acc,
[entry.type]: entry.value
}), {});
console.log(parts); // {weekday: 'Thursday', literal: ':', hour: '12', minute: '19'}
package.json
(npm init -y
). В приведённом Вами коде используются ES6-импорты (ESM-импорты), которые сразу не будут работать в Node.js, т.к. в нём используются CommonJS-импорты. Для решения данной проблемы у Вас есть два пути:"type": "module"
в package.json
:{
...
"type": "module",
...
}
- import * as crypto from 'crypto';
+ const crypto = require('crypto');
$ node .
cVoADkhcldK+mYC3Id5vhkxOr4NwVspTcgF56RiRG0CzcnOcBwcELKi1YnBNySmZugpjJNHuCU7ePjwVadqfAw==
interface IWrapper<T> {
component: T;
}
const Wrapper = <T extends React.ComponentType<any>>({
component: Component,
...props
}: React.PropsWithChildren<IWrapper<T> & React.ComponentProps<T>>) => <Component {...props} />;
transform-origin: 42.5px 152.5px;