Huy's Everyday Blog

Huy's Everyday Blog

Using Zig for Advent of Code

Đăng ngày 12/11/2022

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...

Đọc trên blog của tác giả

Test parameter passed into a function with Jest

Đăng ngày 8/31/2022

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, ...

Đọc trên blog của tác giả

Optional Chaining and Code Coverage

Đăng ngày 8/29/2022

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...

Đọc trên blog của tác giả

Mocking File and FileList in Jest

Đăng ngày 8/28/2022

Sometimes we need to mock a `FileList`, for example, when we need to test file upload features. First, create a mock `File` object: ```typescript...

Đọc trên blog của tác giả

Testing localStorage in Jest

Đăng ngày 8/27/2022

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: ``...

Đọc trên blog của tác giả

Migrating docker-compose application

Đăng ngày 6/6/2022

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....

Đọc trên blog của tác giả

Recursive Descent Parser

Đăng ngày 5/8/2022

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. ##...

Đọc trên blog của tác giả

Variable declaration in Virtual Stack Machine

Đăng ngày 4/24/2022

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...

Đọc trên blog của tác giả

Virtual Stack Machines

Đăng ngày 4/21/2022

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...

Đọc trên blog của tác giả

Using the browser's CustomEvent

Đăng ngày 4/20/2022

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...

Đọc trên blog của tác giả

Extract digits of a number from both ends

Đăng ngày 4/19/2022

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...

Đọc trên blog của tác giả

Detect chess piece movement with Bitboard

Đăng ngày 4/18/2022

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...

Đọc trên blog của tác giả

Structures Bitboard Tic Tac Toe

Đăng ngày 4/17/2022

[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...

Đọc trên blog của tác giả

Circle and Ray Intersection

Đăng ngày 4/16/2022

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...

Đọc trên blog của tác giả

Prime Factorization

Đăng ngày 4/15/2022

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...

Đọc trên blog của tác giả

Understanding keyof typeof

Đăng ngày 4/14/2022

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 {...

Đọc trên blog của tác giả

Notes Control Flow Graph and Infinite Recursive Detection

Đăng ngày 4/13/2022

[**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...

Đọc trên blog của tác giả

Notes Monotonic Clock

Đăng ngày 4/12/2022

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...

Đọc trên blog của tác giả

String as enum key

Đăng ngày 4/11/2022

In TypeScript, you can define an enum and access its value with a _string-like value_, like this: ```typescript enum Editor {...

Đọc trên blog của tác giả

Tracking letter frequency

Đăng ngày 4/10/2022

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...

Đọc trên blog của tác giả

Use Delve on M1 Mac

Đăng ngày 4/9/2022

[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...

Đọc trên blog của tác giả

Cyclic Sort

Đăng ngày 4/8/2022

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...

Đọc trên blog của tác giả

Fast and slow pointers for Linked List

Đăng ngày 4/7/2022

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...

Đọc trên blog của tác giả

Code organization when using Nx

Đăng ngày 4/6/2022

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...

Đọc trên blog của tác giả

Some random notes about Classes

Đăng ngày 4/5/2022

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...

Đọc trên blog của tác giả

Notes Dry Run

Đăng ngày 4/4/2022

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....

Đọc trên blog của tác giả

Sliding Window

Đăng ngày 4/3/2022

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...

Đọc trên blog của tác giả

Merge two sorted arrays with extra space

Đăng ngày 4/2/2022

**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...

Đọc trên blog của tác giả

Compilation Process

Đăng ngày 4/1/2022

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...

Đọc trên blog của tác giả

The intrinsic keyword

Đăng ngày 3/31/2022

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...

Đọc trên blog của tác giả

How some utility types are implemented

Đăng ngày 3/30/2022

TypeScript provides several [utility types](https://www.typescriptlang.org/docs/handbook/utility-types.html) to help us manipulate types easier, like: `Partial`, `Required`, `Pick`,... ...

Đọc trên blog của tác giả

A note about lib.dom.d.ts

Đăng ngày 3/29/2022

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...

Đọc trên blog của tác giả

Memorization with React.memo

Đăng ngày 3/28/2022

[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...

Đọc trên blog của tác giả

Respect default font size

Đăng ngày 3/27/2022

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...

Đọc trên blog của tác giả

Hanging Punctuation

Đăng ngày 3/26/2022

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...

Đọc trên blog của tác giả

Counter Reset respects start attribute

Đăng ngày 3/25/2022

In CSS, we can create a custom list numbering with `counter-reset`, `counter-increment` and `counter()` functions. For example: ```css...

Đọc trên blog của tác giả

Source Code Walkthrough InlayHints

Đăng ngày 3/24/2022

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...

Đọc trên blog của tác giả

Active Listening

Đăng ngày 3/23/2022

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...

Đọc trên blog của tác giả

Component CSS Isolation

Đăng ngày 3/22/2022

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...

Đọc trên blog của tác giả

Skip some fields when serializing

Đăng ngày 3/21/2022

Using serde, we can serialize a data structure into different formats, for example, JSON: ```rust #[derive(Serialize)]...

Đọc trên blog của tác giả

Notes Collector Fallacy

Đăng ngày 3/20/2022

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...

Đọc trên blog của tác giả

A quick guide to getting started

Đăng ngày 3/19/2022

## Definition Angular is: - A component-based framework to build web apps...

Đọc trên blog của tác giả

Notes Contributing to complex projects

Đăng ngày 3/18/2022

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...

Đọc trên blog của tác giả

Partial update an object in IndexedDB

Đăng ngày 3/17/2022

Let's say, you have the object store called **characters** as the following table: | Key | Value | |:----|:------|...

Đọc trên blog của tác giả

Moving to IndexedDB

Đăng ngày 3/16/2022

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...

Đọc trên blog của tác giả

Notes How to Edit Your Own Writing

Đăng ngày 3/15/2022

**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 ...

Đọc trên blog của tác giả

Building large applications

Đăng ngày 3/14/2022

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,...

Đọc trên blog của tác giả

Notes Diffuse vs Focused mode

Đăng ngày 3/13/2022

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...

Đọc trên blog của tác giả

Cancel Request with Subscription

Đăng ngày 3/12/2022

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...

Đọc trên blog của tác giả

Structured Data for Google

Đăng ngày 3/11/2022

**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...

Đọc trên blog của tác giả

Notes The Curse of Knowledge

Đăng ngày 3/10/2022

**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...

Đọc trên blog của tác giả

Notes Browser Rendering Painting Compositing

Đăng ngày 3/9/2022

**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...

Đọc trên blog của tác giả

Notes Layout Thrashing

Đăng ngày 3/8/2022

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 [...

Đọc trên blog của tác giả

Notes Two types of Knowledge

Đăng ngày 3/7/2022

**Article:** https://fs.blog/feynman-learning-technique/ There are 2 types of knowledge: - Knowing the name of something...

Đọc trên blog của tác giả

Notes Browser Rendering Process

Đăng ngày 3/6/2022

## 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...

Đọc trên blog của tác giả

How React Diffing Algorithm Works

Đăng ngày 3/5/2022

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:/...

Đọc trên blog của tác giả

Notes Zeigarnik Effect

Đăng ngày 3/4/2022

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...

Đọc trên blog của tác giả

CODEOWNERS file

Đăng ngày 3/3/2022

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...

Đọc trên blog của tác giả

Arrow Function in Classes

Đăng ngày 3/2/2022

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...

Đọc trên blog của tác giả

Notes Tetris Effect

Đăng ngày 3/1/2022

**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...

Đọc trên blog của tác giả

Type Annotation vs Type Assertion

Đăng ngày 2/28/2022

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...

Đọc trên blog của tác giả

Patterns The Elm Architecture

Đăng ngày 2/27/2022

[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...

Đọc trên blog của tác giả

Notes Suffering Oriented Programming

Đăng ngày 2/26/2022

**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...

Đọc trên blog của tác giả

Lookup Types

Đăng ngày 2/25/2022

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 ...

Đọc trên blog của tác giả

Enums at runtime

Đăng ngày 2/24/2022

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...

Đọc trên blog của tác giả

Percentage Padding and Margin

Đăng ngày 2/23/2022

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...

Đọc trên blog của tác giả

How Bitwarden encrypts your data

Đăng ngày 2/22/2022

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...

Đọc trên blog của tác giả

Cryptography PBKDF2

Đăng ngày 2/21/2022

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...

Đọc trên blog của tác giả

Notes Rediscovering the Benefits of Drawing

Đăng ngày 2/20/2022

**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...

Đọc trên blog của tác giả

Notes The Art of Close Reading

Đăng ngày 2/19/2022

**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...

Đọc trên blog của tác giả

Beware the delete

Đăng ngày 2/18/2022

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 ...

Đọc trên blog của tác giả

Structures Graph Represent

Đăng ngày 2/17/2022

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...

Đọc trên blog của tác giả

The unknown Type

Đăng ngày 2/16/2022

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 ...

Đọc trên blog của tác giả

Record and Replay Macro

Đăng ngày 2/15/2022

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` to start record mode and store the macro to the `<r...

Đọc trên blog của tác giả

Implement Rust Result type

Đăng ngày 2/14/2022

In Rust, there is a [Result](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 ...

Đọc trên blog của tác giả

Railroad Diagram

Đăng ngày 2/13/2022

**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...

Đọc trên blog của tác giả

BNF

Đăng ngày 2/12/2022

**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...

Đọc trên blog của tác giả

Context-Free Grammar Derivations Leftmost Rightmost

Đăng ngày 2/11/2022

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...

Đọc trên blog của tác giả

Context-Free Grammar

Đăng ngày 2/10/2022

Context-Free Grammar (CFG) is a grammar where **production (or rewrite) rules** are in the form of: $$ A \rightarrow \alpha...

Đọc trên blog của tác giả

Named imports and dead code elimination

Đăng ngày 2/9/2022

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...

Đọc trên blog của tác giả

Expose local server with Tunnel

Đăng ngày 2/8/2022

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...

Đọc trên blog của tác giả

Timing Attack

Đăng ngày 2/7/2022

**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...

Đọc trên blog của tác giả

Testing with Jest

Đăng ngày 2/6/2022

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...

Đọc trên blog của tác giả

Build a library with Parcel

Đăng ngày 2/5/2022

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...

Đọc trên blog của tác giả

Non-English Variables

Đăng ngày 2/4/2022

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...

Đọc trên blog của tác giả

Faux Bold and Faux Italic

Đăng ngày 2/3/2022

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...

Đọc trên blog của tác giả

Interpolation Methods

Đăng ngày 2/2/2022

**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**...

Đọc trên blog của tác giả

Auto-fill OTP code from SMS

Đăng ngày 2/1/2022

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="...

Đọc trên blog của tác giả

Non-blocking FFI Calls

Đăng ngày 1/31/2022

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...

Đọc trên blog của tác giả

FFI API

Đăng ngày 1/30/2022

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...

Đọc trên blog của tác giả

Row Level Security

Đăng ngày 1/29/2022

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 ...

Đọc trên blog của tác giả

Working with wasm-bindgen

Đăng ngày 1/28/2022

[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...

Đọc trên blog của tác giả

Stack Machine Execution

Đăng ngày 1/27/2022

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...

Đọc trên blog của tác giả

Tables and Dynamic Linking

Đăng ngày 1/26/2022

**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 ...

Đọc trên blog của tác giả

Working with Linear Memory

Đăng ngày 1/25/2022

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....

Đọc trên blog của tác giả

How to read WASM code

Đăng ngày 1/24/2022

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))_...

Đọc trên blog của tác giả

A quick guide

Đăng ngày 1/23/2022

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...

Đọc trên blog của tác giả

Notes about Vector memory allocation

Đăng ngày 1/22/2022

A Vector in Rust is fundamentally a (pointer, capacity, length) triplet. For example, a `Vec` containing two elements `'a'` and `'b'`, with the capacity of 4, can be visualized as the following ...

Đọc trên blog của tác giả

Count number of digits with Logarithm

Đăng ngày 1/21/2022

Suppose that a number $n$ has $d$ digits, then: $$ 10^{d-1} \leq n \lt 10^{d}...

Đọc trên blog của tác giả

Blanket Implementation

Đăng ngày 1/20/2022

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...

Đọc trên blog của tác giả

The Never Type

Đăng ngày 1/19/2022

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...

Đọc trên blog của tác giả

Lifetime Elision Rules

Đăng ngày 1/18/2022

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...

Đọc trên blog của tác giả

Console Assert Command

Đăng ngày 1/17/2022

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...

Đọc trên blog của tác giả

Dealing with Integer Overflow

Đăng ngày 1/16/2022

Overflow can happen when doing integer arithmetics in Rust, for example: ```rust let _ = 255u8 + 1;...

Đọc trên blog của tác giả

Deref and DerefMut

Đăng ngày 1/15/2022

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...

Đọc trên blog của tác giả

Implement external traits for external types

Đăng ngày 1/14/2022

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...

Đọc trên blog của tác giả

Comparing floating-point numbers

Đăng ngày 1/13/2022

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...

Đọc trên blog của tác giả

How ArenaAllocator works

Đăng ngày 1/12/2022

`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 ...

Đọc trên blog của tác giả

Build system

Đăng ngày 1/11/2022

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...

Đọc trên blog của tác giả

Handling errors

Đăng ngày 1/10/2022

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 {...

Đọc trên blog của tác giả

JSON in 5 minutes

Đăng ngày 1/9/2022

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(, , )`: ```zig...

Đọc trên blog của tác giả

Case Study: Implementing a Generic Stack

Đăng ngày 1/8/2022

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...

Đọc trên blog của tác giả

Cross-compile C C++ and Zig programs

Đăng ngày 1/7/2022

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...

Đọc trên blog của tác giả

Comptime

Đăng ngày 1/6/2022

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...

Đọc trên blog của tác giả

Where data is stored and how to choose an allocator

Đăng ngày 1/5/2022

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...

Đọc trên blog của tác giả

Strings in 5 minutes

Đăng ngày 1/4/2022

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...

Đọc trên blog của tác giả

Render a component to any DOM node with React Portals

Đăng ngày 1/3/2022

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...

Đọc trên blog của tác giả

Type Intersection

Đăng ngày 1/2/2022

Let's say, we are building a component to display some images (with lazy loading): ```javascript const LazyImage = (props: ImageProps) => {...

Đọc trên blog của tác giả

Non-null assertion operator

Đăng ngày 1/1/2022

Sometimes, you'll run into a case where TS keeps complaining about a possibly undefined value. For example: ```javascript const numToString = (a?: number) => {...

Đọc trên blog của tác giả

Handle Optional Subpath

Đăng ngày 12/31/2021

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`,.....

Đọc trên blog của tác giả

Structures Binary Search Tree Delete node

Đăng ngày 12/30/2021

Algorithm to delete a node from a BST: - Find the node to delete - Find the deepest right most (DRM) node of the tree...

Đọc trên blog của tác giả

GUI Druid Custom Widget

Đăng ngày 12/29/2021

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...

Đọc trên blog của tác giả

Structures Binary Tree In-order Traversal with Stack

Đăng ngày 12/28/2021

This one is a bit more compex than the pre-order (in term of using stack). Algorithm: - Create an empty stack...

Đọc trên blog của tác giả

Find Palindrome

Đăng ngày 12/27/2021

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...

Đọc trên blog của tác giả

Partition a number to sum of smaller ones

Đăng ngày 12/26/2021

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;...

Đọc trên blog của tác giả

Generate repeated combinatorial

Đăng ngày 12/25/2021

The algorithm is simple: 1. Find the right most element less than n 2. Increase it...

Đọc trên blog của tác giả

Partial Applied Function

Đăng ngày 12/24/2021

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...

Đọc trên blog của tác giả