const get_element_list = id => {
return axios({
url: `${url_hook}/lists.element.get.json`,
method: 'post',
data: {
IBLOCK_TYPE_ID: 'lists',
IBLOCK_ID: 17,
filter: {
PROPERTY_70: 1,
PROPERTY_74: id,
},
},
}).then(response => {
const result = response.data.result[0];
console.log(result, response.status, response.data); // посмотрите, что тут
});
};
localStorage
. id
. На случай, если их перемешают иначе, или добавится новая — полагаться только на порядковый номер в коллекции, i
, не годится: сейчас на 3-м месте одна кнопка, завтра окажется другая, а мы для неё запомнили включённое состояние.id
. Кнопка может быть добавлена или не-добавлена в избранное. Булево значение: true
или false
. Запоминать будем набор пар ключ-значение. Ключ id
, значение true/false. Что-то типа { "abc123": true, "xyz789": false, }
const mostLeastAndTheRest = names => {
const dict = names.reduce((acc, name) => ((acc[name] ??= 0), acc[name]++, acc), {});
// { "Женя": 3, "Иван": 1, "Виктор": 4, "Константин": 1 }
const values = Object.values(dict);
const max = Math.max(...values);
const min = Math.min(...values);
const entries = Object.entries(dict);
const winners = entries.filter(([_, value]) => value === max).map(([key, _]) => key);
const losers = entries.filter(([_, value]) => value === min).map(([key, _]) => key);
const rest = Object.keys(dict).filter(name => !winners.includes(name) && !losers.includes(name));
return { winners, losers, rest };
};
mostLeastAndTheRest(['Женя', 'Женя', 'Иван', 'Женя', 'Виктор', 'Виктор', 'Константин', 'Виктор', 'Виктор']);
/*
{
"winners": [ "Виктор" ],
"losers": [ "Иван", "Константин" ],
"rest": [ "Женя" ]
}
*/
xss = [(1, 'a'), (2, 'b'), (3, 'c')]
flat = [x for xs in xss for x in xs]
print(flat) # [1, 'a', 2, 'b', 3, 'c']
via // массив 1..99
const range = Array(99)
.fill()
.map((_, i) => i + 1); // массив 1..99
// 6 неповторяющихся выигрышных
const win = Array(6)
.fill()
.map(() => range.splice(Math.floor(Math.random() * range.length), 1).pop())
.sort((a, b) => a - b);
// [ 1, 55, 69, 76, 91, 92 ]
Для выбора выпавших чисел игрока этот же range
уже использовать нельзя – в нём не хватает 6 чисел. children
, в нём найдите indexOf
кликнутого элемента.SRC="/var/tmp/nu-pogodi.mp4"
ffmpeg \
-i "$SRC" \
-vf "hflip" \
-c:v libx264 \
-c:a copy \
"$SRC-flip.mp4"
Медленная и тяжёлая часть работы тут — пережатие видео в h264. Его не избежать, к сожалению.axios.get()
возвращает Promise. Его метод .then()
выполнится не сразу, а когда-то потом, когда будет получен результат запроса. Представьте, что интернет очччеенньь мееедленнныыыйй.console.log()
в последней строке – сразу же за созданием объекта. Но на тот момент веб-запрос ещё не выполнился.class Address {
address = null;
data = [];
data() {
return this.data;
}
constructor(address) {
this.address = address;
}
fetchInformation() {
return axios.get(`${API_BASE}/getAddressInformation`, {
params: {
address: this.address
}
}).then(({ data }) => this.data = data);
}
}
async function initialize() {
const address = new Address(TEST_WALLET);
await address.fetchInformation();
console.log(address);
}
initialize();
const el = document.createElement('div');
el.constructor.name // "HTMLDivElement"
class Habr {
constructor(q) {
this.q = q;
}
}
const h = new Habr('есть конструктор?');
h.constructor.name // "Habr"
7155 7155 7155 7155 7155 7155 7155 7155
6881 6881 6881 6881 6881 6881 6881 6881
6881 6881 6881 6881 6881 6881 6881 6881
7429 7566 7429 7429 7566 7429 7429 7429
8114 7018 8114 7840 6881 7840 7840 8114
7703 7703 7840 7018 6881 7018 7155 7703
7155 7840 7566 7566 7292 7566 8114 7155
7018 7703 7977 7566 7155 7566 7155 7018
const value = '20047155x20046881x20046881x20047429x20048114x20047703x20047155x20047018x20056745x20047155x20046881x20046881x20047566x20047018x20047703x20047840x20047703x20056745x20047155x20046881x20046881x20047429x20048114x20047840x20047566x20047977x20056745x20047155x20046881x20046881x20047429x20047840x20047018x20047566x20047566x20056745x20047155x20046881x20046881x20047566x20046881x20046881x20047292x20047155x20056745x20047155x20046881x20046881x20047429x20047840x20047018x20047566x20047566x20056745x20047155x20046881x20046881x20047429x20047840x20047155x20048114x20047155x20056745x20047155x20046881x20046881x20047429x20048114x20047703x20047155x20047018';
value.split('x').map(s => +s.replace(/^2004/, ''))
.reduce((acc, c, i) => {
if ((i + 1) % 9 !== 0) {
(acc[i % 9] ??= []).push(c);
}
return acc;
}, [])
.map(ar => ar.join(' '))
.join('\n')
7155, 6881, 7429, 8114, 7703,
7018, 7566, 7840, 7977, 7292
[...value.split('x').map(s => +s.replace(/^2004/, ''))
.reduce((acc, c, i) => {
if ((i + 1) % 9 !== 0) {
acc.add(c);
}
return acc;
}, new Set())].join(', ')
function makeAbbr(words) {
let result = '';
for (let i = 0; i < words.length; i++) {
const char = words[i];
if (char !== ' ' && (i === 0 || words[i - 1] === ' ')) {
result += char;
}
}
return result;
}
символ — не пробел, И, к тому же, самый первый в тексте, ИЛИ перед ним был пробел.const makeAbbr = words =>
words
.trim() // убрать пробелы по краям строки
.split(/\s+/) // разбить по пробелу(ам) в массив
.map(w => w[0].toUpperCase()) // от каждого взять первые буквы
.join(''); // склеить в строку
makeAbbr(' мир труд май') // "МТМ"
innerHTML
на каждой итерации — плохо (медленно). Лучше один раз собрать весь HTML в строку, и один раз заменить innerHTML
.const html = new Array(12)
.fill()
.map((_, i) => {
const parallax = `./src/img/parallax/${i & 1 ? 2 : 1}.jpg`;
const hero = './src/img/home/hero.jpg';
const title = `Code №${i + 1}`;
const codepen = `Codepen-${i + 1}`;
return `
<div class="portfolio__codepen">
<div class="portfolio__codepen-background"></div>
<img class="portfolio__codepen-image" src="${parallax}">
<div class="portfolio__codepen-down">
<img src="${hero}" class="codepen-down__hero">
<div class="codepen-down__text">
<h4>${title}</h4>
<h5>${codepen}</h5>
</div>
<a href="#codepen" class="codepen-down__link">Source</a>
</div>
</div>
`;
})
.join('\n');
item.innerHTML = html;
const A = class { constructor() { this.name = 'I am A';} };
const B = class { constructor() { this.name = 'I am Bee';} };
const allClasses = { A, B };
const className = 'A';
const instance = new allClasses[className]();
console.log(instance.name); // I am A