Skip to content

Instantly share code, notes, and snippets.

@pongo
pongo / pg-migrations-packages.md
Last active August 21, 2022 15:30
Пакеты для миграций PostgreSQL

Пакеты для миграций PostgreSQL

Main

Пакет Raw SQL cli cli-create only up migration table transaction
knex - + + + - + +
[node-pg-migrate][2] - + + + - + +
[postgrator][3] + + - - + -
[@slonik/migrator][4] + + + - + slonik do??
@pongo
pongo / nominal-classes.ts
Last active April 18, 2020 14:05
Typescript nominal classes: classes are already nominal if they contain any private members
class Greeter {
greeting: string;
private __brand = Symbol; // private __brand!: never;
constructor(message: string) {
this.greeting = message;
}
greet() {
return "Hello, " + this.greeting;
}
}
// 525,957 ops/s ±1.38%
const length = 500,
array = new Array(length);
for (let i = 0; i < length; i++) {
array[i] = i;
}
// 452,446 ops/s ±1.78%
@pongo
pongo / hrtime1.js
Last active April 8, 2020 11:04
node.js performance measure
// https://stackoverflow.com/a/14551263/136559
var start = process.hrtime();
var elapsed_time = function(note){
var precision = 3; // 3 decimal places
var elapsed = process.hrtime(start)[1] / 1000000; // divide by a million to get nano to milli
console.log(process.hrtime(start)[0] + " s, " + elapsed.toFixed(precision) + " ms - " + note); // print message + time
start = process.hrtime(); // reset the timer
}
@pongo
pongo / monomorphic typescript performance.md
Last active April 8, 2020 17:24
monomorphic code typescript javascript performance

  • значения по-умолчанию в аргументах функции (включая деструктуризацию объектов) работают быстрее, чем проверка === undefined внутри функции.
  • для мелких часто вызываемых функций нужно требовать указания всех аргументов. (если и не из-за полиформизма, то хотя бы чтобы не тратились ресурсы на проверку указан ли параметр)
  • для вложенных функций не совсем понятно — надо указывать все параметры или они нормально работают с переменными или параметрами замыкания. в одних тестах такие функции тормозят, в других — нет. но если указать,
@pongo
pongo / revalidate-caching-issues.md
Last active October 29, 2020 11:36
[vercel/next.js] RFC: Incremental Static Regeneration

Re: people with revalidate caching issues

I'm using getStaticProps with revalidate: 60 and was expecting to only get one data fetch per minute. I just checked our server logs and saw that the requests per minutes to that endpoint is bigger than 20.

The best solution is to not even hit your application. Let a CDN serve a response that's been cached, rather than your application. Trying to share disks/Redis's to sync up application caches is the wrong path - sure you could do it but it's a bunch of unnecessary complexity. Moving your caching solution in front of your application is a far better design.

Using Vercel should (caveat: this bug) take care of all of this for you. That's what Vercel want from Next.js - for you to use Vercel hosting, Vercel is a for-profit company after all. "It's all about that developer experience".

If you're running this on your own, I suggest not running multiple instances and trying to share disk caches. By all means, use multiple instances ("High Availability") but put

@pongo
pongo / Example.ts
Last active November 30, 2020 13:11
StacklessError and Result for typescript
function tryParse(str: string): Result<unknown> {
try {
return Result.ok(JSON.parse(str));
} catch (e) {
return Result.err((e as Error).message);
}
}
const parseResult = tryParse('{ "hello": "world" }');
if (parseResult.isErr) {

jest memory usage

Код

if (globalConfig.logHeapUsage) {
  if (global.gc) {
    global.gc();
  }
 result.memoryUsage = process.memoryUsage().heapUsed;

Гимнастика для глаз

Гимнастика для глаз может преследовать различные цели и может служить как для заботы о глазах, так и для улучшения самочувствия в целом.

Для релаксации

  • Закройте ладонями глаза, расслабьтесь, дышите ровно в течение 1-2 минут. Откройте глаза под ладонями. Если после этого вы видите в темноте блики, линии, световые пятна — оставайтесь с ладонями на глазах в течение 5-7 минут, пока фон не станет равномерно черным.
  • Несколько (5-8) раз подряд крепко зажмурьте глаза, расслабьте веки, медленно досчитайте до 5 и открывайте глаза.
  • Быстро моргните 8-10 раз, а затем опустите полузакрытые глаза вниз на несколько секунд. Проделайте упражнение 3-4 раза.