function getIndex(adr) {
// ...
return fetch(ajaxurl, {
method: 'POST',
body: formData
}).then(resp => resp.text())
.then(showResult)
// парашютики не забываем:
.catch(err => console.error(err));
}
function showResult(data) {
console.log(data);
}
getIndex('https://ya.ru/'); // вернёт промис, ну и фиг с ним
function getIndex(adr) {
// ...
return fetch(ajaxurl, {
method: 'POST',
body: formData
}).then(resp => resp.text())
.then(showResult)
.catch(err => console.error(err));
}
getIndex('https://ya.ru/')
.then(data => {
document.querySelector('#output').innerText = data;
})
.catch(err => console.error(err));
[2, -1, 2, 3, -9] = 6
(у вас получается 5)[-2, -1, 1, 2] = 3
(у вас выводит 2)function getMaxSubSum(arr) {
let max = 0;
const length = arr.length;
for (let frame = length; frame > 0; frame--) {
let sum = 0;
for (let i = 0; i < frame; i++) sum += arr[i];
max = Math.max(max, sum);
// move frame
for (let offset = 1; offset <= length - frame; offset++) {
sum -= arr[offset - 1];
sum += arr[offset + frame - 1];
max = Math.max(max, sum);
}
}
return max;
}
const tests = () => {
[
[[-1, 2, 3, -9], 5],
[[2, -1, 2, 3, -9], 6],
[[-1, 2, 3, -9, 11], 11],
[[-2, -1, 1, 2], 3],
[[100, -9, 2, -3, 5], 100],
[[1, 2, 3], 6],
[[-1, -2, -3], 0],
].forEach((el, i) => {
const result = getMaxSubSum(el[0]);
console.assert(result === el[1], "Test %d failed: [%s] %d != %d", i, el[0], result, el[1]);
})
}
tests();
++i
и i++
только в том, чему равно само это выражение:let i = 0;
alert(++i); // 1 – прибавили 1 и вернули результат
let j = 0;
alert(j++); // 0 – вернём значение до, и прибавим 1
// после уже всё одинаково
console.log(i, j); // 1, 1
const results = [];
const promises = [];
for (let i = 0; i < 10; i++) {
promises.push(
fetch('/user', {
method: 'POST',
headers: {'Content-Type': 'application/json'},
body: JSON.stringify({user: i}),
})
.then(response => response.json())
.then(data => results.push(data))
.catch(err => console.error(err))
);
}
Promise.all(promises)
.then(() => console.log("All 10 done!", results));
[func1, func2, func3]
// обернуть каждую в Promise:
.map((f) => () => new Promise((res, rej) => {
f();
setTimeout(res, 2000));
})
// и собрать цепочку из этих промисов:
.reduce((acc, c) => acc.then(c()), Promise.resolve());
- f();
- setTimeout(res, 2000));
+ f()
+ .then(() => setTimeout(res, 2000)));
async componentDidMount() {
const lastSongsResponse = await fetch("https://api.laut.fm/station/key/last_songs");
const lastSongs = await lastSongsResponse.json();
lastSongs.length = Math.min(7, lastSongs.length);
const promises = lastSongs.map((song) => new Promise((resolve, reject) => {
const params = {
method : 'album.getInfo',
artist : song.artist.name.replace(' & ', ', '),
album : song.album,
api_key : 'apikey',
format : 'json',
};
const url = "https://ws.audioscrobbler.com/2.0/?" + Object.keys(params).map((key) => `${key}=${params[key]}`).join('&');
const cover = await fetch(url)
.then((response) => response.json())
.then((songData) => songData.album.image[4]["#text"])
.catch(err => reject(err));
const date = new Date(song.started_at);
const songData = {
id1 : song.id,
id2 : song.id + 1,
artist : song.artist.name,
title : song.title,
cover : cover,
started_at : date.getHours() + ':' + date.getMinutes().toString().padStart(2, '0')
}
resolve(songData);
}));
const results = await Promise.all(promises);
this.setState({ results: results })
}
const deferred = () => {
Promise.prototype.resolve = () => {}; // чтобы не было ошибок )
return Promise.resolve("web");
}
// проверка
deferred()
.then(function(res) {
console.log(200, res);
return "lab";
})
.then(function(res) {
console.log(100, res);
})
.resolve("web");
// реализация
function deferred() {
function Box() {
this.queue = [];
}
Box.prototype.then = function(func) {
this.queue.push(func);
return this;
}
Box.prototype.resolve = function(first_arg) {
let arg = first_arg;
while (this.queue.length)
arg = this.queue.shift().call(this, arg);
}
return new Box;
}
var groups = "apiclub,55293029"; // сюда подставить ваши группы
var counts = API.groups.getById({
group_ids: groups,
fields: "members_count",
})@.members_count;
var total = 0;
while (counts.length > 0) total = total + counts.pop();
return total;
$code = <<<EOFVK
var groups = "apiclub,55293029";
var counts = API.groups.getById({
group_ids: groups,
fields: "members_count",
})@.members_count;
var total = 0;
while (counts.length > 0) total = total + counts.pop();
return total;
EOFVK;
// токен сообщества получить в Настройках своего сообщества, Работа с API
// нажать кнопку Создать ключ и выбрать любую галочку.
$token = '123123123';
$method = 'execute';
$params = [
'access_token' => $token,
'v' => '5.130',
];
$post_data = [
'code' => $code,
];
$url = sprintf(
'https://api.vk.com/method/%s?%s',
$method,
http_build_query($params)
);
$ch = curl_init();
curl_setopt_array($ch, [
CURLOPT_URL => $url,
CURLOPT_POST => true,
CURLOPT_POSTFIELDS => $post_data,
CURLOPT_RETURNTRANSFER => true,
CURLOPT_TIMEOUT => 10,
]);
$curl_result = curl_exec($ch);
$data = json_decode($curl_result);
$count = $data->response;
printf('<h2>Сейчас в группах %d участников</h2>', $count);
const appendByAttr = (title, subtitle) => jQuery(`a[title="${title}"] ~ .ammenu-submenu-container .ammenu-item.-child.-col-4 a[title="${subtitle}"] ~ ul li:last-child`)
.append($(`a[title="${title}"] ~ .ammenu-submenu-container .ammenu-item__extra`));
appendByAttr('Title 1', 'Subtitle 1');
appendByAttr('Title 2', 'Subtitle 2');
appendByAttr('Title 3', 'Subtitle 3');
Number(num_string)
/^[\*\/\+-]$/
"23к1с2".split(/[а-яй]+/) // [ "23", "1", "2" ]
"23к1с2".match(/([а-яй]+)/g) // [ "к", "с" ]
YaParse = (str) => {
const nums = str.split(/[а-яй]+/) // [ "23", "1", "2" ]
const parts = str.match(/([а-яй]+)/g) // [ "к", "с" ]
parts.unshift("дом");
return nums.reduce((acc, c, i) => (acc[parts[i]] = c, acc), {});
}
console.log(YaParse("23к1с2")); // { "дом": "23", "к": "1", "с": "2" }
false
"1a".codePointAt(0) // 49 - ascii и Unicode код символа "1"
"1a".codePointAt(1) // 97 - ascii и Unicode код символа латинской маленькой "a"
NaN
вообще беспорядок: 123 < "Z" // false
123 > "Z" // тоже false
sec
см. URL.searchParams:const params = (new URL(document.location)).searchParams;
const sec = Number(params.get('sec')) || 5; // или 5 по умолчанию
const future = new Date();
future.setTime(future.getTime() + 1000 * sec);
future
.const update = () => {
const diff = future.getTime() - Date.now(); // сколько осталось, в миллисекундах
const secondsLeft = Math.round(diff / 1000); // сколько осталось секунд
if (diff <= 0) {
// время прошло
} else {
// обновить в кнопке число оставшихся секунд
// и вызвать это обновление снова через чуть-чуть:
setTimeout(update, 200);
}
}
update();