Skip to content

Instantly share code, notes, and snippets.

View zhibirc's full-sized avatar
🟢
online

zhibirc

🟢
online
View GitHub Profile
@zhibirc
zhibirc / CircularBuffer-v1.js
Last active June 5, 2023 09:54
CircularBuffer class
/**
* Implement Circular/Ring Buffer basic behaviour.
*
* @version 1
*
* @example
* const buffer = new CircularBuffer(3);
*
* buffer.list(); // []
* buffer.push('URL 1');
@zhibirc
zhibirc / switchFocus.js
Created September 13, 2021 06:59
Easy switch focus between two buttons
const buttons = [...document.getElementsByClassName('button')];
let focusedButtonIndex = 0;
buttons[focusedButtonIndex].focus();
window.addEventListener('keydown', event => {
if ( buttons.some(button => button === event.target) ) {
if ( event.code === 'ArrowDown' || event.code === 'ArrowUp' ) {
buttons[focusedButtonIndex ^= 1].focus();
}
@zhibirc
zhibirc / generatePassword.js
Last active September 7, 2021 18:40
Basic password generator.
/**
* Basic password generator.
* Alphabet: digits, English letters in both cases, and special characters.
*
* @param {number[]} range - list of two numeric values "from" and "to" which are UTF code points
* @param {number} length - password length, small values aren't recommended for security reasons
*
* @return {Generator<string, void, *>}
*/
function* generatePassword ( range = [33, 126], length = 20 ) {
@zhibirc
zhibirc / recursion-examples.js
Last active March 19, 2021 12:46
Recursive one-liners (or a bit more) for popular tasks
/** @see {@link https://en.wikipedia.org/wiki/Digit_sum} */
const dsum = n => n < 10 ? n : n % 10 + dsum(n / 10 | 0);
/** @see {@link https://encyclopediaofmath.org/wiki/Factorial} */
const fact = n => n ? n * fact(n - 1) : 1;
/** @see {@link https://encyclopediaofmath.org/wiki/Greatest_common_divisor} */
const gcd = (a, b) => b ? gcd(b, a % b) : a;
/** @see {@link https://encyclopediaofmath.org/wiki/Power|Fast algorithm} */
@zhibirc
zhibirc / protector.js
Last active October 24, 2018 15:00
Protect API methods or arbitrary functions from introspection
/* Aim:
"function <function name>() {
[native code]
}"
*/
function protect ( fn ) {
fn.toString = fn.toLocaleString = fn.toSource = function () {
return 'function ' + fn.name + '() { [native code] }';
};
@zhibirc
zhibirc / gist:db0baa7ef3f4a7e564a19208ebae9c86
Last active July 7, 2017 07:59
Protection of the function code from inspection
// basic implementation
function protect ( fn ) {
fn.toString = fn.toLocaleString = fn.toSource = function () {
return 'function ' + fn.name + '() { [native code] }';
};
}
// but indirect call still available, so fix it
var protect = (function () {
// function can be reassign with different name, so use functions itself instead of string names