textpayload = message.user.bonusNew ? `"{\"button\": \"дуэль\"}"` : "{\"button\": \"бонус_новичка\"}`"
`
const bonusButton = { button: message.user.bonusNew ? 'дуэль' : 'бонус_новичка' };
textpayload = JSON.stringify(bonusButton);
let variants = [
{ condition: (tries === 0), alert: 'У вас закончились попытки' },
{ condition: (value == number), alert: 'Поздравляю, вы угадали', returnValue: true },
{ decreaseTries: true }
];
for(let i = 0; i < variants.length; ++i) {
let v = variants[i];
if(typeof v.condition === 'undefined' || v.condition) {
if(v.alert) {
alert(v.alert);
}
if(v.decreaseTries) {
tries--;
triesSpan.textContent = declOfNum(tries, ['попытка', 'попытки', 'попыток']);
triesTitle.textContent = `У вас осталось ${tries} ${triesSpan.textContent}`;
}
return v.returnValue || false;
}
}
const merge = (target, ...sources) =>
sources.reduce((acc, n) => (
Object.entries(n).forEach(([ k, v ]) =>
acc[k] = v instanceof Object
? merge(acc[k] instanceof Object ? acc[k] : {}, v)
: v
),
acc
), target);
const result = merge({}, ...arrayObj);
// эта функция - Генератор. Он создаёт итерируемые штуки
function* makeRangeIterator(start = 0, end = 100, step = 1) {
let iterationCount = 0;
for (let i = start; i < end; i += step) {
iterationCount++;
yield i;
}
return iterationCount;
}
// вот сделаем итератор от 1 и до 10 (исключая конец)
var r1_10 = makeRangeIterator(1, 10);
// в цикле получим из итератора значения
for (i of r1_10) {
console.log(i); // выведет от 1 до 9
}
function shuffle(arr) {
for (let i = arr.length; i > 1; ) {
const j = Math.random() * (i--) | 0;
[ arr[i], arr[j] ] = [ arr[j], arr[i] ];
}
return arr;
}
computed: {
shuffledAnswers() {
return shuffle(Object.entries(this.questions[this.idx].answers));
},
...
<div v-for="[ key, answer ] in shuffledAnswers">
...
document.querySelector('form').addEventListener('input', e => {
document.querySelector('button').disabled = ![
[ 'input', el => el.value ],
[ 'select', el => el.selectedIndex ],
].every(([ selector, validator ]) => {
return [...e.currentTarget.querySelectorAll(selector)].every(validator);
});
});
const hidden = (str, count = 4) => '*'.repeat(count) + str.slice(-4);
const hidden = (str, count = 4) => str.replace(/.*?(?=.{0,4}$)/, Array(count + 1).join('*'));
data: () => ({
filterColumns: [
[ 'name', 'имя', 'string' ],
[ 'count', 'количество', 'number' ],
[ 'distance', 'расстояние', 'number' ],
],
operations: [
[ 'equal', 'равно' ],
[ 'contains', 'содержит' ],
[ 'greater', 'больше' ],
[ 'less', 'меньше' ],
],
...
data: () => ({
types: {
string: {
equal: (a, b) => a.toLowerCase() === b,
contains: (a, b) => a.toLowerCase().includes(b),
greater: (a, b) => a.toLowerCase() > b,
less: (a, b) => a.toLowerCase() < b,
},
number: {
equal: (a, b) => a === +b,
contains: (a, b) => `${a}`.includes(b),
greater: (a, b) => a > +b,
less: (a, b) => a < +b,
},
},
...
<select v-model="column">
<option v-for="n in filterColumns" :value="n[0]">{{ n[1] }}</option>
</select>
<select v-model="operation">
<option v-for="n in operations" :value="n[0]">{{ n[1] }}</option>
</select>
computed: {
filteredItems() {
const { items, column } = this;
const type = this.filterColumns.find(n => n[0] === column)?.[2];
const filterFn = this.types[type]?.[this.operation];
const filterVal = this.filterVal.toLowerCase();
return filterFn && filterVal
? items.filter(n => filterFn(n[column], filterVal))
: items;
},
...
const xxx = str => Array
.from(str, (n, i) => n.toUpperCase() + n.toLowerCase().repeat(i))
.join('-');
const xxx = str => str
.toUpperCase()
.split('')
.reduce((acc, n, i) => `${acc}${i ? '-' : ''}${n}${Array(-~i).join(n.toLowerCase())}`, '');
const xxx = str => str
.toUpperCase()
.replace(/(?<=.)./g, (m, i) => '-'.concat(m, ...Array(i).fill(m.toLowerCase())));
const [ todos, setTodos ] = useState(() => {
let todos = null;
try {
todos = JSON.parse(localStorage.getItem('todos'));
} catch (e) {};
return Array.isArray(todos) ? todos : [];
});
setTodos([ ...todos, { id: Date.now(), complete: false, title: value, }, ]); localStorage.setItem("todos", JSON.stringify(todos));
useEffect(() => {
localStorage.setItem('todos', JSON.stringify(todos));
}, [ todos ]);
<button data-order="-1">От большего к меньшему</button>
<button data-order="+1">От меньшего к большему</button>
const wrapper = document.querySelector('.catalog-items');
const buttons = document.querySelectorAll('[data-order]');
buttons.forEach(n => n.addEventListener('click', onClick));
function onClick({ target: t }) {
const order = +t.dataset.order;
sortChildren(wrapper, el => parseInt(el.innerText) * order);
buttons.forEach(n => n.classList.toggle('active', n === t));
}
function sortChildren(parent, value) {
parent.append(...Array
.from(parent.children, n => [ n, value(n) ])
.sort((a, b) => a[1] - b[1])
.map(n => n[0])
);
}
Uncaught SyntaxError: Unexpected token < in JSON at position 0Читаем. Переводим.