Everyday

My daily thoughts, learnings, and experiences.

All Posts

Using Zig for Advent of Code
This year, I decided to use Zig to solve Advent of Code. I started learning Zig sometime ago but took a break. It was not something easy from the beginning, so in the first few days, I had to use eit...
Zig
Test parameter passed into a function with Jest
OK, this one is super useful, I promise! As you may already know, we can use `toHaveBeenCalledWith` on a spied function to check if that function has been called with a set of arguments. For example, ...
TypeScript
Optional Chaining and Code Coverage
For the uninformed, **optional chaining** is a new JavaScript feature that allows you to access property values deep inside an object without checking that each reference in the chain is valid. For ex...
TypeScript
Mocking File and FileList in Jest
Sometimes we need to mock a `FileList`, for example, when we need to test file upload features. First, create a mock `File` object: ```typescript...
TypeScript
Testing localStorage in Jest
One approach to testing the `localStorage` function in Jest is to mock the `setItem`/`getItem` methods. To mock something with `localStorage`, we can do it via the `Storage.prototype`, for example: ``...
TypeScript
Migrating docker-compose application
Previously, I hosted [Plausible](https://plausible.io) on my Linux server. It's a Google Analytics alternative, that runs as a set of 4 Docker containers, managed with `docker-compose`. Which is cool....
Self-hosting
Recursive Descent Parser
A parser is a program that usually takes a stream of lexical tokens and transforms them into another data structure, usually in the form of a parse tree that satisfies the language's grammar rules. ##...
Parsing
Variable declaration in Virtual Stack Machine
In the [previous article](/everyday/04-21-2022-compilers-how-virtual-stack-machines-executed), we get an overview of how bytecode is executed in a stack machine. In this article, we continue to dive i...
Compilers
Virtual Stack Machines
Different programming languages have different approaches to executing their code. Some languages execute the code as they travel the *AST* (Tree Walk approach), and some languages compile the code in...
Compilers
Using the browser's CustomEvent
An event system is a mechanism for globally receiving and broadcasting messages, which can be used in a Web Application to allow different components that do not have any parent-child relation to comm...
TypeScript
Extract digits of a number from both ends
Let's say, we have a problem that requires us to print all the digits of a number from the left to right. A simple approach would be extracting the digits from the right to the left, storing them in a...
Algorithms
Detect chess piece movement with Bitboard
In [the previous article](/everyday/04-17-2022-data-structures-introduction-to-bitboard), we learned about Bitboard and how to use it in a simple board game. In this article, let's see how Bitboard ca...
Algorithms
Structures Bitboard Tic Tac Toe
[Bitboard](https://www.chessprogramming.org/Bitboards) is a widely-used technique in many computer chess programs for efficiently representing and extracting information on the chessboard. It seems to...
Data
Circle and Ray Intersection
Let $P$ be the intersection point, $A$ is the anchor point of the ray, $B$ is the endpoint of the ray (assuming the ray is length-limited) and $C$ is the circle's center point, with radius $r$. $$ \\b...
Math
Prime Factorization
In mathematics, the [fundamental theorem of arithmetic](https://en.wikipedia.org/wiki/Fundamental_theorem_of_arithmetic) states that: **"Any integer number larger than 1 can be written as a product of...
Math
Understanding keyof typeof
In the ["Use String as Enum Key"](/everyday/04-11-2022-typescript-use-string-as-enum-key) article, we use the **keyof typeof** keywords to create a union of an enum's keys. ```typescript enum Editor {...
TypeScript
Notes Monotonic Clock
In a computer system, there are 2 types of clocks: 1. **Wall Clock** (or **Real-Time Clock**): is the clock that is synchronized with NTP (Network Time Protocol), which is subjected to jump (moving f...
Reading
String as enum key
In TypeScript, you can define an enum and access its value with a _string-like value_, like this: ```typescript enum Editor {...
TypeScript
Tracking letter frequency
Sometimes, you will need to count the frequency of letters in a string and do something with that count. For example, with a simple algorithm to check if a string is a permutation of another one, we c...
Algorithms
Use Delve on M1 Mac
[Delve](https://github.com/go-delve/delve/tree/master/Documentation/installation) is a GDB-alike debugger for Golang, with better support for Go's data structures and Goroutine. To install Delve on M1...
Golang
Cyclic Sort
Cyclic Sort is an easy to implement and efficient algorithm. The only caveat is that it requires an input array to be a continuous range of values. It can be applied to the problems of finding *duplic...
Algorithms
Fast and slow pointers for Linked List
In a Linked List, traversal is restricted to forward only, you can't really go back to previous nodes once you go past them. When working on a problem that requires us to do some lookup in a Linked Li...
Algorithms
Code organization when using Nx
Nx is a tool to create and manage multiple-project workspaces. One of its most important features is the ability to track the changes in your projects in your workspace and only rebuild what is affect...
Monorepo
Some random notes about Classes
Some notes about some not-so-well-known things about TypeScript Classes. ## Parameter properties In TypeScript, you can define a class's properties in two ways: Define it as a class property in the no...
TypeScript
Notes Dry Run
OK, this one is embarrassing, I still remember the first time I was taught to dry run the code. It was many years ago when I started learning how to program. But I've never actually tried it properly....
Reading
Sliding Window
For the problems that require us to do something a stream of values, or a subsequence of an array, the typical approach is to use a sliding window. ![](_meta/sliding-window.png) A naive way to impleme...
Algorithms
Merge two sorted arrays with extra space
**The problem** Given two non-decreasing arrays `a` of length `m`, and `b` of length `n`. Merge the two arrays into array `a`. Since it’s an in-place merge, `a` has some extra spaces to fit the result...
Algorithms
Compilation Process
This article is inspired by the talk [How the TypeScript compiler compiles](https://www.youtube.com/watch?v=X8k_4tZ16qU), you should really check it out for a more in-depth understanding about the Typ...
TypeScript
The intrinsic keyword
In the [previous post](/everyday/03-30-2022-typescript-how-some-utility-types-are-implemented), we learned how some utility types are implemented. The fact that they're all done at the type level is v...
TypeScript
How some utility types are implemented
TypeScript provides several [utility types](https://www.typescriptlang.org/docs/handbook/utility-types.html) to help us manipulate types easier, like: `Partial<T>`, `Required<T>`, `Pick<T, Keys>`,... ...
TypeScript
A note about lib.dom.d.ts
In TypeScript, all the type definitions for the Web API are implemented in the [lib.dom.d.ts](https://github.com/microsoft/TypeScript/blob/main/lib/lib.dom.d.ts) file. One interesting thing is, this f...
TypeScript
Memorization with React.memo
[Memoization](https://en.wikipedia.org/wiki/Memoization) is the technique to let an expensive function return the cached value if all of its arguments remain unchanged. When a React component is wrapp...
React
Respect default font size
When working with text and CSS, we usually assume that the default font size of the browser is always a fixed number (for example, 16px), therefore, we don't think much when setting the base font size...
Typography
Hanging Punctuation
Hanging punctuation is the practice of pulling the punctuation marks into the margin of a text so that it does not disturb the _vertical [reading flow](https://betterwebtype.com/articles/2018/10/15/rh...
Typography
Counter Reset respects start attribute
In CSS, we can create a custom list numbering with `counter-reset`, `counter-increment` and `counter()` functions. For example: ```css...
CSS
Source Code Walkthrough InlayHints
So, I want to look into the TypeScript source code to understand how things work and maybe contribute to the project as well. This is a quite big project but I think the code organization is pretty go...
TypeScript
Active Listening
Active Listening is a process to **engage** and **empathize** with the speaker when talking about something. The most important part of active listening is to: - Try to understand the topic you're lis...
Skills
Component CSS Isolation
In Angular, component styles are isolated (a.k.a [View Encapsulation](https://angular.io/guide/view-encapsulation)). That means CSS styles of a component are only affect the component itself, **not it...
Angular
Skip some fields when serializing
Using serde, we can serialize a data structure into different formats, for example, JSON: ```rust #[derive(Serialize)]...
Rust
Notes Collector Fallacy
Collector's Fallacy is **the urge to collect something that you never use or need**, but the act of collecting gives you a good feeling (cognitive reward). For example: - Save every article on the int...
Reading
Notes Contributing to complex projects
As a developer, our main job is contributing to code projects, it can be a work project or an open-source project. With work projects, we might have access to more resources (other developers to learn...
Reading
Moving to IndexedDB
LocalStorage is a popular solution to persists data (locally) across sessions for web applications, but there are some limitations, for example: - It is limited to 10MB on most browsers. On Safari, it...
JavaScript
Notes How to Edit Your Own Writing
**Article:** https://www.nytimes.com/2020/04/07/smarter-living/how-to-edit-your-own-writing.html ## Why editing? Writing is like thinking. You will not know precisely what you are going to say before ...
Reading
Building large applications
Coming from React or other UI frameworks, when it comes to building large applications, you might have the habit of breaking it into smaller components. This mental model does not fit in Elm, in fact,...
Elm
Notes Diffuse vs Focused mode
The [Learning How to Learn](https://www.coursera.org/learn/learning-how-to-learn/home/welcome) course proposed an idea that there are two modes of thinking: **Focused** and **Diffuse**. You are either...
Reading
Cancel Request with Subscription
In RxJS, a [Subscription](https://rxjs.dev/guide/subscription) is an object that represents an execution of an [Observable](https://rxjs.dev/guide/observable). It has the most important method, the `u...
RxJS
Structured Data for Google
**Structured data** is a special data snippet you can insert into your page to help Google Search identify your content in a richer way (called **Rich Result**). It usually comes in the [JSON-LD forma...
SEO
Notes The Curse of Knowledge
**The curse of knowledge** is a cognitive bias of **assuming that others have the same background knowledge to understand what you are talking**. It is also known as the [False-Consensus Effect](https...
Reading
Notes Browser Rendering Painting Compositing
**Painting** and **Compositing** are the last two steps to generate a frame in the [browser's pixel pipeline](/everyday/03-06-2022-reading-notes-browser-s-rendering-process). **Painting** is the proce...
Reading
Notes Layout Thrashing
When a DOM node is written (change of style, attribute, or inner content), and the action triggers a layout change, the browser must do a layout recalculation (reflow). The browser usually waits for [...
Reading
Notes Two types of Knowledge
**Article:** https://fs.blog/feynman-learning-technique/ There are 2 types of knowledge: - Knowing the name of something...
Reading
Notes Browser Rendering Process
## The big picture Most devices refresh their screen 60 times a second. On each refresh, the graphics driver generates the pixel data from the frame provided by the application and sends it to the mon...
Reading
How React Diffing Algorithm Works
If you are busy, here is the **TL; DR**: **React Reconciliation** is the tree diffing algorithm that React used to update your application's DOM tree between renders. The [existing algorithms](https:/...
React
Notes Zeigarnik Effect
The Zeigarnik Effect means: **If you are working on a task and being interrupted, the task remains longer in your mind, making it easier to remember the task's details**. A more detailed explanation f...
Reading
CODEOWNERS file
On Github, you can create a `CODEOWNERS` file in the `.github/` or `docs/` folder to specify which person or team is responsible for the code in a repository. If a file or a folder has a code owner, t...
Git
Arrow Function in Classes
One of the most confusing things in JavaScript is the context object `this` inside a function. The value of `this` **depends on how the function is called, not how the function is defined**. Let's tak...
TypeScript
Notes Tetris Effect
**Article:** https://en.m.wikipedia.org/wiki/Tetris_effect *Tetris Effect* is an effect that happens **when you devote a large amount of time and mental effort to do something, it will shape the way y...
Reading
Type Annotation vs Type Assertion
By default, the TypeScript compiler tries its best to analyze the code and infer the type of your variables. ```typescript let a = 10; // typeof a == number...
TypeScript
Patterns The Elm Architecture
[The Elm Architecture](https://guide.elm-lang.org/architecture/) is not something necessary exclusive to the Elm language but should be viewed as a generic design pattern for architecting GUI applicat...
Design
Notes Suffering Oriented Programming
**Article:** http://nathanmarz.com/blog/suffering-oriented-programming.html OK, so I came across this very interesting article about product building. The author talks about a style of programming tha...
Reading
Lookup Types
Let's say you are tasked to build the next Amazon, and you gotta start small. So, you build a website that only sells books and audiobooks for now. The system would have the `BaseItem` type, defining ...
TypeScript
Enums at runtime
In TypeScript, an enum can be defined in various ways: a numeric enum, a string-based enum, or heterogeneous enum. By default, any enum member will have a numeric value: ```typescript...
TypeScript
Percentage Padding and Margin
When you specify a percentage value for the CSS padding or margin of an element, this percentage is **based on the width of the containing block**, not the width of the element itself. For example, in...
CSS
How Bitwarden encrypts your data
This note only covers the mechanism of Bitwarden's end-to-end encryption for a single user, between one or more clients. For more information about how they handle user authentication and password sha...
Security
Cryptography PBKDF2
PBKDF2 is a key derivation function, used in the process of deriving encryption keys. The main idea of PBKDF2 is repeatedly applying the input and the salt to a hash function like HMAC to produce a ke...
Security
Notes Rediscovering the Benefits of Drawing
**Article:** https://blogs.scientificamerican.com/symbiartic/rediscovering-the-forgotten-benefits-of-drawing/ In the old times, scientist are required to have drawing skill, because they have to recre...
Reading
Notes The Art of Close Reading
**Reference Link:** https://eric.ed.gov/?id=EJ718563 **Full text:** https://files.eric.ed.gov/fulltext/EJ718563.pdf In this article, the author make the point about what is the worst way to read (pass...
Reading
Beware the delete
Unlike C/C++, the [delete](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/delete) operator in JavaScript has nothing to do with memory deallocation. What it actually does ...
JavaScript
Structures Graph Represent
There are two ways to represent a graph data structure, each come with its own pros and cons. ## Using adjacency matrix An adjacency matrix is a square matrix, each element in the matrix indicate whet...
Data
The unknown Type
You can think of `unknown` as a type-safe version of `any`. They are both used to represent the type of value that is unknown beforehand (like a result of `JSON.parse`,...), but `unknown` required us ...
TypeScript
Record and Replay Macro
Macro is a complex type of repeation, it allow you to record and replay a sequence of actions. A macro can be created by: - Press `q<register-name>` to start record mode and store the macro to the `<r...
Vim
Implement Rust Result type
In Rust, there is a [Result<T, E>](https://doc.rust-lang.org/rust-by-example/std/result.html) type that could return either an `Ok(T)` value if the operation is succeeded, or an `Err(E)` value if the ...
TypeScript
Railroad Diagram
**Railroad Diagrams** (or **Syntax Diagrams**) are the graphical way to represent [context-free grammars](/everyday/02-10-2022-parsing-context-free-grammar). Each diagram defines a nonterminal. And th...
Parsing
BNF
**Backus-Naur Form (BNF)** is a metasyntax for [context-free grammars](/everyday/02-10-2022-parsing-context-free-grammar), is used to describe the syntax of languages used in computing such as program...
Parsing
Context-Free Grammar Derivations Leftmost Rightmost
A derivation of *a string* for *a grammar* is a *sequence of production rule applications*. The process of getting the string through the derivation is the parsing process. For example, with the follo...
Parsing
Context-Free Grammar
Context-Free Grammar (CFG) is a grammar where **production (or rewrite) rules** are in the form of: $$ A \rightarrow \alpha...
Parsing
Named imports and dead code elimination
One thing about JavaScript that is sometimes confusing: The **named imports**. When there is a big module that exports a lot of things, we usually think that we can use named import to get just what w...
JavaScript
Expose local server with Tunnel
Like [Ngrok](https://ngrok.com/), Cloudflare Tunnel is a lightweight daemon that run on your server (or local machine) and create a tunnel between your machine and the Cloudflare edge, allowing you to...
Cloudflare
Timing Attack
**Timing attack** is the type of attack when an attacker tries to analyze the time it takes your application to do something, in order to guess the data it's operating on. For example, you build an AP...
Security
Testing with Jest
To use Jest for testing a TypeScript library, we need to install a couple of things: ``` yarn add -D jest @types/jest ts-jest ts-node...
Typescript
Build a library with Parcel
With Parcel 2.0, it's very easy to build a TypeScript library and publish them to NPM later on, with automatically generated types and built-in support for both CommonJS and ESModule. Let's say you ha...
TypeScript
Non-English Variables
In JavaScript, you can use any ASCII characters as variable or function names, even non-English words or some special symbols: ```javascript const π = 3.1415...
JavaScript
Faux Bold and Faux Italic
When you load custom web fonts with just the regular font-weight, no bold or italic styles, the browser tries its best to render them in bold and italic style by **faking** it. These styles are called...
Typography
Interpolation Methods
**Interpolation** is a type of estimation method for finding new data points based on the range of a discrete set of known data points. The most basic kind of interpolation is **Linear Interpolation**...
Math
Auto-fill OTP code from SMS
Safari on iOS and macOS devices have the ability to automatically retrieve and autofill the OTP code sent via SMS if your input has the `autocomplete="one-time-code"` attribute: ```html <form action="...
HTML
Non-blocking FFI Calls
Sometimes, we want to call an FFI function that is CPU-bound. This would block the main thread. For example, in this `sleep_and_scream` method from Rust, we use `std::thread::sleep` to hang the functi...
Deno
FFI API
From version 1.13, Deno introduced the FFI API (foreign function interface API) that allows us to load libraries built in any language that supports the C ABI (like C/C++, Rust, Zig, Kotlin,...). To l...
Deno
Row Level Security
In Postgres, tables can have [Row Level Security](https://www.postgresql.org/docs/current/ddl-rowsecurity.html) that restrict the user's action on each row. With Supabase, we can create a policy that ...
Supabase
Working with wasm-bindgen
[wasm-bindgen](https://github.com/rustwasm/wasm-bindgen) is an awesome tool made by **rustwasm** team, make it very easy to expose Rust's data/functions to JavaScript and vice versa. To use, you can a...
WebAssembly
Stack Machine Execution
WebAssembly is executed using a stack-based virtual machine. There are two types of execution of a WASM module: - **Instance Execution:** If the module contains a **start** section, the referenced fun...
WebAssembly
Tables and Dynamic Linking
**Table** is another shared instance in WebAssembly just like Linear Memory, but it can only store **function references**. It can be shared between modules, and all you can do with tables is to make ...
WebAssembly
Working with Linear Memory
Linear Memory in WebAssembly is a contiguous and mutable array of **uninterpreted bytes**. It is shared between the WASM module and the host runtime. It can be expanded by calling `WebAssembly.Memory....
WebAssembly
How to read WASM code
Just like a good-old-Assembly program, a WebAssembly module is made up of different sections: ![](_meta/wasm-anatomy.png) _(Source: [rsms/Introduction to WebAssembly](https://rsms.me/wasm-intro))_...
WebAssembly
A quick guide
WebAssembly is a new type of code that **can be loaded and run by the JavaScript VM** on web browsers. It can also be run natively on the computer by other WASM runtimes like [Wasmer](https://wasmer.i...
WebAssembly
Notes about Vector memory allocation
A Vector in Rust is fundamentally a (pointer, capacity, length) triplet. For example, a `Vec<Char>` containing two elements `'a'` and `'b'`, with the capacity of 4, can be visualized as the following ...
Rust
Blanket Implementation
By using generic parameters, you can `impl` a trait for any type that satisfies some trait bounds, for example, implement trait `ToString` for every type `T` that implemented the `Display` trait: ```r...
Rust
The Never Type
Rust has a special type `!` to imply that there is no return value. Usually called _never type_. It allows us to write code like this: ```rust...
Rust
Lifetime Elision Rules
Before Rust 1.0, writing code that returns a reference without any lifetime annotation wouldn't compile. Because Rust does not know what's the lifetime of the returned reference: ```rust // 🚫 would n...
Rust
Console Assert Command
The built-in `console` comes with the `console.assert` method, which is pretty useful to write some tests in your code. This method has the syntax of: ```javascript...
JavaScript
Dealing with Integer Overflow
Overflow can happen when doing integer arithmetics in Rust, for example: ```rust let _ = 255u8 + 1;...
Rust
Deref and DerefMut
The traits [`std::ops::Deref`](https://doc.rust-lang.org/std/ops/trait.Deref.html) and [`std::ops::DerefMut`](https://doc.rust-lang.org/std/ops/trait.DerefMut.html) are used for **explicit dereference...
Rust
Implement external traits for external types
One of the rules for working with traits in Rust is: You are not allowed to implement a trait on a type if either the trait or the type is not local to your crate. For example, within your program, bo...
Rust
Comparing floating-point numbers
Due to rounding errors, most floating-point numbers cannot be represented precisely in the computer. This led to some weird situations like: ```javascript 0.1 + 0.2 = 0.30000000000000004...
Algorithms
How ArenaAllocator works
`ArenaAllocator` is one of Zig's built-in allocators. It takes another allocator and wraps some code around to allow you to allocate memory without the need to free them individually. Every allocated ...
Zig
Build system
There are 4 build modes in Zig, each can be enabled via the arguments `-O ReleaseSafe`, `-O ReleaseSmall`, and `-O ReleaseFast` when running `zig run` or `zig test`. Depending on which mode is enabled...
Zig
Handling errors
A function in Zig can return either an error or an actual value, most of the time you will see something like this: ```zig pub fn countTheSheep() !u32 {...
Zig
JSON in 5 minutes
Zig has built-in support for JSON via the `std.json` module. **To convert any object into a JSON string**, we use `std.json.stringify(<input>, <options>, <output stream>)`: ```zig...
Zig
Case Study: Implementing a Generic Stack
Implementing a stack is one of my favorite tests when working with a new language because it will show us a lot about the language's ergonomics. We are going to make this stack a generic data structur...
Zig
Cross-compile C C++ and Zig programs
Zig came with a built-in C/C++ compiler `zig cc` and `zig c++`. So you can compile and run your C/C++ code with Zig! For example, let's compile this simple C program: ```c...
Zig
Comptime
One of the unique features of Zig is the ability to let us control what happens in our code, during both runtime and compile time. For optimization, Zig implicitly performs some evaluations at compile...
Zig
Where data is stored and how to choose an allocator
Zig has no runtime, hence, no automatic memory management. It's the developer's responsibility to manage the allocation/deallocation of memories. It's important to know how memory allocation works, wh...
Zig
Strings in 5 minutes
Just like C/C++, you can define a string in Zig with an array of bytes or as a null-terminated string literal. ```javascript var s = "hello"; // *const [5:0]u8...
Zig
Render a component to any DOM node with React Portals
In React, you can mount a component into any DOM node instead of just the current parent component, with the help of `ReactDOM.createPortal([content], [node] )`. It's very helpful when working with mo...
React
Type Intersection
Let's say, we are building a component to display some images (with lazy loading): ```javascript const LazyImage = (props: ImageProps) => {...
TypeScript
Non-null assertion operator
Sometimes, you'll run into a case where TS keeps complaining about a possibly undefined value. For example: ```javascript const numToString = (a?: number) => {...
TypeScript
Handle Optional Subpath
In Next.js, you can define a [dynamic route](https://nextjs.org/docs/routing/dynamic-routes) by creating a file at `/pages/post/[id].tsx`. And this will catch all URLs like `/post/foo`, `/post/bar`,.....
Next.js
GUI Druid Custom Widget
To create a custom widget in [Druid](https://linebender.org/druid/), we create a new struct and implement [Widget](https://docs.rs/druid/latest/druid/trait.Widget.html) trait. Or create a function tha...
Rust
Find Palindrome
When solving palindrome problems, we need to avoid sliding window solution (a.k.a brute force), where we try to generate every substring and check to find the palindrome. The good approach to go for i...
Algorithms
Partition a number to sum of smaller ones
The array **x** is to keep track of all possible integers we can find, the array **t** is to keep the sum **t[i]** of every **x** number from **x[1]** to **x[i]**. ```javascript const n = 8;...
Algorithms
Partial Applied Function
Like currying, if a function takes some arguments and we invoke that function without all of the arguments, a new function will be created so we can call it with the remaining functions later on. In S...
Scala