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...
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, ...
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...
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: ``...
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....
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. ##...
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...
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...
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...
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...
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...
[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...
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...
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...
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 {...
[**go-staticcheck**](https://github.com/dominikh/go-tools/) is a static code analysis tool for Go. It has an interesting ability to detect infinite recursive calls. For example, infinite calls like th...
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...
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...
[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...
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...
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...
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...
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...
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....
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.  A naive way to impleme...
**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...
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...
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 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>`,... ...
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...
[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...
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...
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...
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...
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...
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...
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...
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...
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...
**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 ...
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,...
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...
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...
**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...
**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...
**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...
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 [...
## 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...
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:/...
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...
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...
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...
**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...
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...
[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...
**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...
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 ...
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...
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...
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...
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...
**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...
**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...
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 ...
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...
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 ...
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...
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 ...
**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...
**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...
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...
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...
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...
**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...
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...
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...
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...
**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**...
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="...
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...
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...
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 ...
[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 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...
**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 ...
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....
Just like a good-old-Assembly program, a WebAssembly module is made up of different sections:  _(Source: [rsms/Introduction to WebAssembly](https://rsms.me/wasm-intro))_...
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...
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 ...
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...
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...
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...
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...
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...
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...
`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 ...
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...
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 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...
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 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...
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 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...
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...
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...
Sometimes, you'll run into a case where TS keeps complaining about a possibly undefined value. For example: ```javascript const numToString = (a?: number) => {...
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`,.....
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...
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...
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;...
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...