Skip to content

Instantly share code, notes, and snippets.

@mohnatus
mohnatus / while-match.js
Created March 16, 2019 15:49
find re match in string
const str = "Строчка с 3 числами в ней... 42 и 88.";
const numRe = /\b(\d+)\b/g;
let match;
while (match = numRe.exec(str)) {
console.log("Нашёл ", match[1], " на ", match.index);
}
// Нашёл 3 на 10
// Нашёл 42 на 29
@mohnatus
mohnatus / multiline-split.js
Created March 16, 2019 15:53
split multiline string on lines
let str = "multiline\nstring";
let lines = str.split(/\r?\n/);
@mohnatus
mohnatus / from-to-iterate.js
Created March 17, 2019 07:02
перебор значений от from до to в любую сторону
function iterate(from, to, cb) {
let diff = to > from ? 1 : -1;
for (let i = from * diff; i <= to * diff; i++) {
cb(i / diff);
}
}
@mohnatus
mohnatus / array-shuffle.js
Created March 21, 2019 16:20
shuffle array (Fisher-Yates algorithm)
Array.prototype.shuffle = function() {
let arr = [...this];
let m = this.length;
while(m) {
const i = Math.floor(Math.random() * m--);
[arr[m], arr[i]] = [arr[i], arr[m]];
}
return arr;
}
@mohnatus
mohnatus / is-element-inside.js
Created March 25, 2019 04:29
check if element is inside another element
function isInside(node, target) {
for (; node != null; node = node.parentNode)
if (node == target) return true;
}
@mohnatus
mohnatus / scroll-progress.js
Last active March 30, 2019 17:13
document scroll progress
var bar = document.querySelector(".progress div");
addEventListener("scroll", function() {
var max = document.body.scrollHeight - innerHeight;
var percent = (pageYOffset / max) * 100;
bar.style.width = percent + "%";
});
@mohnatus
mohnatus / git-config
Created March 30, 2019 18:40
git initial configure
git config --global user.name "John Doe"
git config --global user.email johndoe@example.com
let xhr = new XMLHttpRequest();
xhr.open('GET', '/my/url', true);
xhr.send();
xhr.onreadystatechange = function() {
if (this.readyState != 4) return;
if (this.status != 200) {
console.log( 'ошибка: ' + (this.status ? this.statusText : 'запрос не удался') );
return;
}
let xhr = new XMLHttpRequest();
let body = JSON.stringify({});
xhr.open('POST', '/my/url', true);
xhr.setRequestHeader('Content-type', 'application/json; charset=utf-8');
xhr.send(body);
xhr.onreadystatechange = function() {
if (this.readyState != 4) return;
if (this.status != 200) {
console.log( 'ошибка: ' + (this.status ? this.statusText : 'запрос не удался') );
return;
@mohnatus
mohnatus / random.js
Created April 12, 2019 10:36
get random integer
// Возвращает случайное целое число между min (включительно) и max (не включая max)
// Использование метода Math.round() даст вам неравномерное распределение!
function getRandomInt(min, max) {
return Math.floor(Math.random() * (max - min)) + min;
}