Skip to content

Instantly share code, notes, and snippets.

class BidirectionalMap<T> {
private forwardMap: Map<T, T>;
private backwardMap: Map<T, T>;
constructor() {
this.forwardMap = new Map();
this.backwardMap = new Map();
}
set(key: T, value: T): void {
@kitcat-dev
kitcat-dev / leetcode-patterns.ts
Created January 25, 2024 23:31
Repetitive patterns I want to memorize
/**
* @param {any[]} array
* @param {any} x
* @param {any} y
*/
function swap(array, x, y) {
temp = array[x];
array[x] = array[y];
array[y] = temp;
}
export const useToggle = (defaultValue = false) => {
const [isEnabled, set] = useReducer(
(state, next) => (next == null ? !state : next),
defaultValue
);
const enable = () => set(true);
const disable = () => set(false);
const toggle = () => set();
type Stringified<T> = { [k in keyof T]: T[k] extends number ? string : T[k] };
const stringifyWithKeys = <T, K extends keyof T>(obj: T, ...keys: K[]): Stringified<T> => {
const stringifiedObject = obj as Stringified<T>;
for (const [key, value] of Object.entries(pick(stringifiedObject, ...keys))) {
if (value !== undefined && typeof value === 'number') {
stringifiedObject[key as K] = String(value) as T[K] extends number ? string : T[K];
}
}
Object.mapEntries = (obj, callbackFn) =>
Object.fromEntries(
Object.entries(obj).map(callbackFn)
)
// 1. Генерация случайного числа в заданном диапазоне
const randomNumberInRange = (min, max) => Math.floor(Math.random() * (max - min + 1)) + min;
randomNumberInRange(10, 20) // 14
// 2. Переключение логического значения
const toggle = value => !value
toggle(false) // true
// 3. Сортировка элементов массива в случайном порядке (осторожно! низкий уровень случайности)
const sortRandom = (arr) => arr.sort(() => Math.random() - 0.5)
@kitcat-dev
kitcat-dev / items.json
Last active July 10, 2020 19:06
MTMR preset
[
{
"type": "escape",
"width": 75,
"align": "left"
},
{
"type": "volumeDown",
"bordered": false,
setTimeout(function() {
debugger;
}, 3000);
@kitcat-dev
kitcat-dev / currying.js
Created August 28, 2019 08:22
Каррирование функции
const If = foo => arg => foo(arg);
const True = arg1 => arg2 => arg1;
const False = arg1 => arg2 => arg2;
If(True)('one')('two'); // one
If(False)('one')('two'); // two
@kitcat-dev
kitcat-dev / partialApply.js
Created August 28, 2019 07:56
Частичное применение функции
const partialApply = (fn, arg1) => (arg2, arg3) => fn(arg1, arg2, arg3);
const getAverageSalary = (profession, country) => {
if (profession === 'programmer') {
if (country === 'spain') return 2000;
if (country === 'russia') return 1200;
if (country === 'usa') return 8000;
}
}