g
. Хотите найти всё - используйте preg_match_all. const types = [ 'text', 'password', 'number' ];
const [ type, setType ] = useState('text');
<input type={type} />
const onTypeChange = e => setType(e.target.value);
{types.map(n => (
<input
type="button"
value={n}
className={n === type ? 'active' : ''}
onClick={onTypeChange}
/>
))}
{types.map(n => (
<label>
<input
type="radio"
value={n}
checked={n === type}
onChange={onTypeChange}
/>
{n}
</label>
))}
<select value={type} onChange={onTypeChange}>
{types.map(n => <option>{n}</option>)}
</select>
<button onClick={() => setType(types[(types.indexOf(type) + 1) % types.length])}>
next type
</button>
const sorted = (arr, path) => arr
.map(function(n) {
return [ n, this.reduce((p, c) => p?.[c], n) ];
}, path.split('.'))
.sort((a, b) => a[1] - b[1])
.map(n => n[0]);
const sorted = (arr, key) => arr
.map(n => [ n, key(n) ])
.sort((a, b) => a[1] - b[1])
.map(n => n[0]);
const sortedByCommentsCount = sorted(arr, n => n.comments.count);
const sortedByLengthDesc = sorted(arr, n => -n.length);
document.querySelector('form').addEventListener('submit', function(e) {
e.preventDefault();
const data = Object.fromEntries(new FormData(this));
console.log(JSON.stringify(data, null, 2));
});
const pickers = $('селектор элементов, на которых инициализируются экземпляры календаря')
.datepicker({
onSelect(formattedDate, date, picker) {
pickers.forEach(n => n !== picker && (
n.currentDate = picker.currentDate,
n.selectedDates = [ date ],
n.update()
));
},
})
.get()
.map(n => $(n).data('datepicker'));
const options = {
onSelect({ date, datepicker }) {
pickers.forEach(n => n !== datepicker && n.update({
viewDate: datepicker.viewDate,
selectedDates: [ date ],
}, {
silent: true,
}));
},
};
const pickers = Array.from(
document.querySelectorAll('селектор элементов с календарями'),
n => new AirDatepicker(n, options)
);
<select id="country"></select>
<select id="city"></select>
const setOptions = (el, data) =>
el.innerHTML = data
.map(n => `<option>${n}</option>`)
.join('');
const countries = [
{ name: 'Германия', cities: [ 'Берлин', 'Бонн', 'Мюнхен' ] },
{ name: 'Франция', cities: [ 'Париж', 'Лион', 'Марсель' ] },
{ name: 'Италия', cities: [ 'Рим', 'Неаполь', 'Милан' ] },
];
const country = document.querySelector('#country');
const city = document.querySelector('#city');
setOptions(country, countries.map(n => n.name));
country.addEventListener('change', function() {
setOptions(city, countries.find(n => n.name === this.value).cities);
});
country.dispatchEvent(new Event('change'));
const sortedInventory = Object
.values(inventory)
.sort((a, b) => a.price - b.price)
.map(n => `${n.title} - ${n.amount}`)
.join('\n');
const add = (str, val) =>
str.replace(/\d+$/, m => `${+m + val}`.padStart(m.length, 0));
add('string0001', 1) // 'string0002'
add('string1010', 99) // 'string1109'
add('string2345', 6789) // 'string9134'
string99 + 1
должно быть равно string00
, а не string100
), то после вызова padStart
добавьте .slice(-m.length)
. <p class="typeit">hello, world!!</p>
<p class="typeit">fuck the world</p>
<p class="typeit">fuck everything</p>
const typeit = Array.from(
document.querySelectorAll('.typeit'),
(n, i) => new TypeIt(n, {
cursor: false,
afterComplete: () => typeit[i + 1]?.go(),
})
);
typeit[0].go();
const uniqueWithCount = (arr, idKey, countKey) =>
Object.values(arr.reduce((acc, n) => (
(acc[n[idKey]] ??= { ...n, [countKey]: 0 })[countKey]++,
acc
), {}));
const result = uniqueWithCount(arr, 'name', 'qty');
const addToCart = product =>
setCart(cart => cart.some(n => n.id === product.id)
? cart.map(n => n.id === product.id ? { ...n, qty: n.qty + 1 } : n)
: [ ...cart, { ...product, qty: 1 } ]
);
const firstNonRepeatingLetter = str =>
[...str].find((n, i, a) => a.indexOf(n) === a.lastIndexOf(n)) || '';
const firstNonRepeatingLetter = str =>
str.charAt(Array
.from(str.toLowerCase())
.findIndex((n, i, a) => a.indexOf(n) === a.lastIndexOf(n))
);
separator = 'lot'
item = 'obj'
count = [ n.count(item) for n in s.split(separator)[1:] ]
print(' '.join(f'[{separator} {n} {item}]' for n in count))
function calc(val = 0) {
const self = {
add: v => (val += v, self),
sub: v => (val -= v, self),
mul: v => (val *= v, self),
div: v => (val /= v, self),
pow: v => (val **= v, self),
toString: () => val,
};
return self;
}
calc().add(5).mul(5) + 1 // 26
+calc(100).div(10).sub(2) // 8
`${calc(2).pow(10)}` // "1024"