Skip to content

Instantly share code, notes, and snippets.

View r13v's full-sized avatar
🙈

Rustam Giliaziev r13v

🙈
  • Spain
  • 07:50 (UTC +02:00)
  • LinkedIn in/r13v
View GitHub Profile
import {useEffect} from 'react';
type EventKey = string;
type EventHandler<T = any> = (payload: T) => void;
type EventMap = Record<EventKey, EventHandler>;
type Bus<E> = Record<keyof E, E[keyof E][]>;
interface EventBus<T extends EventMap> {
on<Key extends keyof T>(key: Key, handler: T[Key]): () => void;
off<Key extends keyof T>(key: Key, handler: T[Key]): void;
@SanariSan
SanariSan / bookmarklet.js
Created March 24, 2023 17:48 — forked from andyg2/bookmarklet.js
Bookmark-let to summarize a web page using GPT-3 - written by GPT-3
javascript: (function () {
var text = document.body.innerText;
var spl = text.split(" ");
if (spl.length > 3000) {
text = spl.slice(0, 3000).join(" ");
}
fetch('https://api.openai.com/v1/completions', {
method: 'POST',
headers: {
@semeleven
semeleven / common.js
Last active November 19, 2024 08:36
Хелперы для плохометров
const fs = require("fs");
const path = require("path");
const util = require("util");
const { exec } = require("child_process");
const yargs = require("yargs/yargs");
const { hideBin } = require("yargs/helpers");
const execAsync = util.promisify(exec);
function commonYargs() {
const argv = yargs(hideBin(process.argv))
@ryanlintott
ryanlintott / LayoutThatFits.swift
Last active December 8, 2023 15:14
An alternative to ViewThatFits. Updated version can be found here: https://github.com/ryanlintott/LayoutThatFits
//
// LayoutThatFits.swift
// WWDC22Experiments
//
// Created by Ryan Lintott on 2022-06-08.
//
import SwiftUI
struct LayoutThatFits: Layout {
@byte-sourcerer
byte-sourcerer / MacEditorTextView.swift
Created October 31, 2021 10:46
An NSTextView wrapped by SwiftUI with TextKit 2
/**
* MacEditorTextView
* Copyright (c) Thiago Holanda 2020-2021
* https://twitter.com/tholanda
*
* MIT license
* Modified by https://github.com/cjwcommuny for TextKit 2
*/
import Combine

Краткая характеристика:

  1. У него много сторов и сторы могут зависеть друг от друга, а не один большой стор и селекторы. То есть он ближе к Эфектору, чем в Редаксу/MobX. Всё ради tree shaking.
  2. Он ближе к стору прямых измений. В публичном API нет экшенов. Но всё-таки value = 1 на манер MobX запрещены — значения можно менять только через спец. методы. И в синхронизации состояния с сервером экшены есть (просто скрыты из публичного API).

Плюсы:

  1. Может работать без Логакса, чисто как стейт-менеджер.
  2. API специально создан, чтобы хранить в сторах бизнес-логику, чем разгружать компоненты и упрощать переносимость приложения между фреймворками.
  3. От 157 байт (!) в вашем JS-бандле.
  4. Расчитан на агрессивный tree shaking, чтобы в JS-бандле был только код того состояния, которые используются в текущих страницах.
  5. Очень ленивый — сторы на которых никто не подписан выгружаются из памяти, а их бизнес-логика останавливается.
@nodkz
nodkz / 1-server-generate-sign-url.js
Last active December 10, 2022 18:25
Upload image to S3 with resizing using lambda functions via hooks
/* @flow */
/* eslint-disable no-param-reassign */
import express, { type $Request, type $Response } from 'express';
import uniqid from 'uniqid';
import aws from 'aws-sdk';
export type SignResult = {
publicUrl: string,
signedUrl: string,
// Swift's untyped errors are a goddam PiTA. Here's the pattern I use to try to work around this.
// The goal is basically to try to guarantee that every throwing function in the app throws an
// ApplicationError instead of some unknown error type. We can't actually enforce this statically
// But by following this convention we can simplify error handling
enum ApplicationError: Error, CustomStringConvertible {
// These are application-specific errors that may need special treatment
case specificError1
case specificError2(SomeType)
@rohozhnikoff
rohozhnikoff / 1-usage.js
Last active February 20, 2019 08:16
довешиваем аналог classNames к итоговым стилям React Native Stylesheet + пробрасываем глобальную тему
import { Styler } from '../style/react-native-styler';
/*
если заменить StyleSheet.create({}) на Styler.create({})
то все будет работать аналогично, включая перфоманс оптимизации
к итоговому обьекту добавляется метод .$(), работающий аналогично вебовскому classNames
плюс, в Styler.create можно загнать функцию, аргументом в которые отправляется глобальная тема и утилиты
*/
@andymatuschak
andymatuschak / States-v3.md
Last active August 16, 2025 08:46
A composable pattern for pure state machines with effects (draft v3)

A composable pattern for pure state machines with effects

State machines are everywhere in interactive systems, but they're rarely defined clearly and explicitly. Given some big blob of code including implicit state machines, which transitions are possible and under what conditions? What effects take place on what transitions?

There are existing design patterns for state machines, but all the patterns I've seen complect side effects with the structure of the state machine itself. Instances of these patterns are difficult to test without mocking, and they end up with more dependencies. Worse, the classic patterns compose poorly: hierarchical state machines are typically not straightforward extensions. The functional programming world has solutions, but they don't transpose neatly enough to be broadly usable in mainstream languages.

Here I present a composable pattern for pure state machiness with effects,