Skip to content

Instantly share code, notes, and snippets.

@drzhbe
drzhbe / badSpliceInsideLoop.js
Last active April 17, 2023 10:17
Как удалить элемент массива при переборе элементов массива или что бывает, если использовать метод splice внутри цикла? Описание можно почитать в комментарии к гисту.
// Bad method, don't use it.
var a = [0,1,2,3,4]
for (var i = 0; i < a.length; i++) {
console.log(i, a[i]);
if (a[i] === 0) {
console.log(a);
a.splice(i, 1);
console.log(a);
}
}
// shim layer with setTimeout fallback
window.requestAnimFrame = (function(){
return window.requestAnimationFrame ||
window.webkitRequestAnimationFrame ||
window.mozRequestAnimationFrame ||
function( callback ){
window.setTimeout(callback, 1000 / 60);
};
})();
@drzhbe
drzhbe / prime.js
Last active December 22, 2015 13:59
primes
function prime() {
this.primes = [],
this.number = 1,
this.stop = false,
this.x = 600851475143,
this.checkPrime = function() {
var number = this.number,
i = 0,
l = this.primes.length;
@drzhbe
drzhbe / rn.sh
Last active August 29, 2015 14:02
# swap names of 2 files
if [ $# -eq 2 ]
then
mv $1 $1.backup
mv $2 $1
mv $1.backup $2
fi
# swap %file_name% with %file_name%.backup
if [ $# -eq 1 ] && [ -f $1.backup ] || [ -d $1.backup ];
@drzhbe
drzhbe / localStorageStack.js
Created July 17, 2014 11:45
How to interact with key-value storage (localStorage) like a stack
/**
* Добавить в стэк listName значение value.
* При в storage будет храниться ключ ${listName}_last со значением индекса последнего элемента в этом списке.
* Новое значение сериализованное в JSON добавится в storage с ключом ${listName}_last + 1.
*
* Пример:
* В списке listName=log есть 3 элемента, storage будет выглядеть так:
* {
* 'log_last': '2',
* 'log_0': '{...}',
@drzhbe
drzhbe / localStorageQueue.js
Created July 18, 2014 05:35
How to interact with key-value storage (localStorage) like a queue
/**
* Функции для работы со storage, как с очередью.
*/
/**
* Очистить старые записи.
* @param tailIndexValue
* @param nextIndexValue
*/
function free(tailIndexValue, nextIndexValue) {
@drzhbe
drzhbe / JSON2File.js
Last active August 29, 2015 14:13
После сохранения для pretty print можно в IDE сделать Code -> Reformat Code
var path = '';
function JSON2File(error, success, code) {
var writer = fs.createWriteStream(path + '.json');
var json = JSON.stringify(success.data);
writer.write(json);
}
@drzhbe
drzhbe / trnslt.js
Last active January 20, 2020 03:57
Click on english word to translate it into russian. Translation will be logged into console.
/**
* <a href='http://api.yandex.ru/dictionary/'>Реализовано с помощью сервиса «API «Яндекс.Словарь»</a>
*/
(function() {
const YANDEX_DICTIONARY_KEY = 'dict.1.1.20150130T172350Z.0895b15babe24c90.431f35fa9af476be1b6d14d80f3809ab693a5970';
const DICTIONARY_URL = `https://dictionary.yandex.net/api/v1/dicservice.json/lookup?key=${YANDEX_DICTIONARY_KEY}&lang=en-ru`
function translate(word) {
fetch(`${DICTIONARY_URL}&text=${word}`)
.then(res => res.json())
@drzhbe
drzhbe / prgrss.js
Last active December 19, 2017 05:00
Show reading progress on scroll
(function() {
var willHide = false;
var msgBox = document.createElement('div');
msgBox.style.position = 'fixed';
msgBox.style.top = '10px';
msgBox.style.right = '10px';
msgBox.style.display = 'none';
document.body.appendChild(msgBox);
@drzhbe
drzhbe / once.js
Last active August 29, 2015 14:18
`once` for QML
/*!
\brief Если `flag` праведный, то выполнить `callback`, иначе подписаться на событие `sig`
Варианты реализации `flag`:
1. передать имя свойства (+ в любой момент времени можно проверить актуальность флага)
2. передать функтор (+ в любой момент времени можно проверить актуальность флага)
3. передать значение свойства (- узнать значение флага можно только в текущий момент времени)
Здесь используется последний, где `flag` — это буль
\param type:bool flag
\param type:Signal sig
\param type:function callback