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...
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, ...
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...
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...
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: ``...
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....
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. ##...
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...
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...
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...
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...
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...
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...
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...
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...
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 {...
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...
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...
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 {...
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...
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...
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...
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...
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...
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...
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....
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.  A naive way to impleme...
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...
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...
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...
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`,... ...
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...
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...
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...
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...
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...
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...
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...
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...
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)]...
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...
A quick guide to getting started
Đăng ngày 3/19/2022
## Definition Angular is: - A component-based framework to build web apps...
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...
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 | |:----|:------|...
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...
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 ...
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,...
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...
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...
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...
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...
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...
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 [...
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...
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...
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:/...
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...
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...
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...
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...
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...
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...
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...
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 ...
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...
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...
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...
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...
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...
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...
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 ...
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...
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 ...
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...
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 ...
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...
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...
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...
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...
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...
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...
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...
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...
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...
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...
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...
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**...
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="...
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...
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...
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 ...
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...
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...
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 ...
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....
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:  _(Source: [rsms/Introduction to WebAssembly](https://rsms.me/wasm-intro))_...
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...
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 ...
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}...
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...
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...
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...
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...
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;...
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...
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...
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...
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 ...
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...
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 {...
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...
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...
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...
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...
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...
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...
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...
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) => {...
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) => {...
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`,.....
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...
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...
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...
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...
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;...
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...
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...