<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0"><channel><title><![CDATA[Ruben's Blog]]></title><description><![CDATA[Ruben's Blog]]></description><link>https://blog.rubenoalvarado.com</link><generator>RSS for Node</generator><lastBuildDate>Wed, 15 Apr 2026 02:42:19 GMT</lastBuildDate><atom:link href="https://blog.rubenoalvarado.com/rss.xml" rel="self" type="application/rss+xml"/><language><![CDATA[en]]></language><ttl>60</ttl><item><title><![CDATA[Everybody Knows That Drizzle is the Word!]]></title><description><![CDATA[I’ve worked with plenty of ORMs and database tools over the years—JPA, Hibernate, Knex, Mongoose, Prisma. The list is long. There’s always a new “revolutionary” tool. So when I first heard about Drizz]]></description><link>https://blog.rubenoalvarado.com/wiring-drizzle-with-nest-js</link><guid isPermaLink="true">https://blog.rubenoalvarado.com/wiring-drizzle-with-nest-js</guid><category><![CDATA[nestjs]]></category><category><![CDATA[TypeScript]]></category><category><![CDATA[DrizzleORM]]></category><category><![CDATA[supabase]]></category><category><![CDATA[PostgreSQL]]></category><dc:creator><![CDATA[Ruben O. Alvarado]]></dc:creator><pubDate>Mon, 23 Feb 2026 18:30:00 GMT</pubDate><enclosure url="https://cloudmate-test.s3.us-east-1.amazonaws.com/uploads/covers/68d563fa231fcd615851077a/51fead33-d648-4a97-b2df-9f9f5b8fde84.jpg" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>I’ve worked with plenty of ORMs and database tools over the years—JPA, Hibernate, Knex, Mongoose, Prisma. The list is long. There’s always a new “revolutionary” tool. So when I first heard about Drizzle, I was skeptical.</p>
<p>I was happy with Prisma, until I had to integrate with a Supabase Postgres database. After a week fighting the client generation workflow, I gave Drizzle a shot. The integration felt boring in the best way: it was as smooth as working with native Postgres.</p>
<p>Then I plugged it into NestJS, and the experience changed. Supabase felt easy. Nest introduced friction—because the real problem isn’t Drizzle or Nest. It’s the glue code in between.</p>
<p>In this post, we’ll make Drizzle feel <strong>Nest-native</strong> using <em>providers</em>.</p>
<h3>The real problem: your DB client becomes a hidden dependency</h3>
<p>Drizzle is minimal by design. NestJS is modular by design. The friction starts the moment you try to make “minimal” fit inside a DI container.</p>
<p>It usually begins innocently: one file creates the client, another reads <code>DATABASE_URL</code>, and a service imports a singleton from some <code>db.ts</code> file in a random folder.</p>
<p>It works. Until it doesn’t.</p>
<p>Soon the database client becomes a <strong>hidden dependency</strong>. Tests that should be pure unit tests suddenly require wiring. A simple refactor turns into a scavenger hunt for imports.</p>
<p>We’ll get there with a few small building blocks:</p>
<ul>
<li><p><strong>Injection tokens</strong> (stable DI keys).</p>
</li>
<li><p>A <strong>Postgres provider</strong> (creates and owns the connection).</p>
</li>
<li><p>A <strong>Drizzle provider</strong> (builds the typed DB instance).</p>
</li>
<li><p>A thin <strong>DatabaseModule</strong> (Nest wiring only).</p>
</li>
</ul>
<h3>The plan: a thin DatabaseModule</h3>
<p>Here’s the blueprint we’re aiming for. If we do this right, two things become true:</p>
<ul>
<li><p>No service imports a database singleton from a file.</p>
</li>
<li><p>All database access goes through <strong>one DI token</strong>.</p>
</li>
</ul>
<p>We’ll get there with one module boundary and two providers, each with a single responsibility:</p>
<ol>
<li><p><code>PostgresProvider</code></p>
<ul>
<li><p>Input: validated <code>database.url</code> from <code>ConfigService</code>.</p>
</li>
<li><p>Output: a single Postgres client wrapper that owns shutdown.</p>
</li>
</ul>
</li>
<li><p><code>DrizzleProvider</code></p>
<ul>
<li><p>Input: the Postgres client and app env.</p>
</li>
<li><p>Output: the Drizzle DB instance bound to <strong>one DI token</strong>.</p>
</li>
</ul>
</li>
<li><p><code>DatabaseModule</code> (Nest wiring)</p>
<ul>
<li>Guarantee: modules and services only depend on DI tokens, not on a file path.</li>
</ul>
</li>
</ol>
<p>That separation keeps Nest concerns (modules, DI, lifecycle) out of your Drizzle initialization logic.</p>
<p>Next, we’ll build it in five steps.</p>
<h3>Step 1: Create dedicated injection tokens</h3>
<p>Before we write any modules, we need stable injection tokens. These tokens are the <strong>only</strong> thing services should ever inject.</p>
<p>First, install Drizzle and the <code>postgres</code> driver:</p>
<pre><code class="language-bash">pnpm add drizzle-orm@beta postgres
</code></pre>
<div>
<div>💡</div>
<div>Note: I’m using <code>@beta</code> here. If you prefer fewer breaking changes, pin a stable version instead.</div>
</div>

<p>Now define a symbol token in a single place, and don’t redefine it anywhere else:</p>
<pre><code class="language-typescript">// database/database.constants.ts
export const DRIZZLE = Symbol('DRIZZLE');
export const POSTGRES_CLIENT = Symbol('POSTGRES_CLIENT');
</code></pre>
<p>With tokens in place, we can implement the Postgres and Drizzle providers.</p>
<h3>Step 2: Implement postgres provider</h3>
<pre><code class="language-typescript">// database/providers/postgres.provider.ts
import { Logger, OnApplicationShutdown } from '@nestjs/common';
import postgres from 'postgres';
import { POSTGRES_CLIENT } from '../constants/database.constants';
import { ConfigService } from '@nestjs/config';
import { DatabaseConfig } from '@app/config/types/database-config.type';

export class PostgresClientProvider implements OnApplicationShutdown {
  private readonly logger = new Logger(PostgresClientProvider.name);

  constructor(public readonly client: postgres.Sql) {}

  async onApplicationShutdown(signal?: string) {
    this.logger.log(`Closing database connection (signal: ${signal})`);
    await this.client.end();
  }
}

export const PostgresProvider = {
  provide: POSTGRES_CLIENT,
  inject: [ConfigService],
  useFactory: (
    configService: ConfigService&lt;{ database: DatabaseConfig }&gt;,
  ): PostgresClientProvider =&gt; {
    const { url } = configService.get&lt;DatabaseConfig&gt;('database', {
      infer: true,
    }) as DatabaseConfig;

    const client = postgres(url, { prepare: false });
    return new PostgresClientProvider(client);
  },
};
</code></pre>
<h3>Step 3: Implement Drizzle provider</h3>
<pre><code class="language-typescript">// database/providers/drizzle.provider.ts
import { ConfigService } from '@nestjs/config';
import { drizzle } from 'drizzle-orm/postgres-js';

import { DRIZZLE, POSTGRES_CLIENT } from '../constants/database.constants';
import { DrizzleDB } from '../types/database.type';
import { PostgresClientProvider } from './postgres.provider';
import { AppConfig } from '@app/config/types/app-config.types';

import * as schema from '../schema';

export const DrizzleProvider = {
  provide: DRIZZLE,
  inject: [POSTGRES_CLIENT, ConfigService],
  useFactory: (
    postgresProvider: PostgresClientProvider,
    configService: ConfigService&lt;{ app: AppConfig }&gt;,
  ): DrizzleDB =&gt; {
    const { nodeEnv } = configService.get&lt;AppConfig&gt;('app', {
      infer: true,
    }) as AppConfig;

    return drizzle({
      client: postgresProvider.client,
      schema,
      logger: nodeEnv === 'development',
    });
  },
};
</code></pre>
<p>In the next steps we’ll define a single <code>DrizzleDB</code> type (derived from your schema) and reuse it everywhere.</p>
<h3>Step 4: Wire it up in DatabaseModule (Nest-only concerns)</h3>
<p>This is where Nest becomes useful. We register both providers and export <strong>one token</strong> that the rest of the app can inject.</p>
<p>A few rules to keep it boring:</p>
<ul>
<li><p>The module wires providers that read config.</p>
</li>
<li><p>The module creates the Drizzle instance once.</p>
</li>
<li><p>Services only inject <code>DRIZZLE</code>.</p>
</li>
</ul>
<pre><code class="language-typescript">// database/database.module.ts
import { Global, Module } from '@nestjs/common';
import { DRIZZLE } from './constants/database.constants';
import { DrizzleProvider } from './providers/drizzle.provider';
import { PostgresProvider } from './providers/postgres.provider';

@Global()
@Module({
  providers: [PostgresProvider, DrizzleProvider],
  exports: [DRIZZLE],
})
export class DatabaseModule {}
</code></pre>
<p>At this point, your database client is no longer a hidden dependency. It’s a first-class provider with a stable token.</p>
<p>Next, we’ll inject it from any module without importing “random files”.</p>
<h3>Step 5: Inject Drizzle anywhere (no imports from “random files”)</h3>
<p>Now the payoff: modules import <em>a module</em>, and services inject <em>a token</em>.</p>
<p>First, define a single strongly typed DB type derived from your schema:</p>
<pre><code class="language-typescript">// database/types/database.type.ts
import { PostgresJsDatabase } from 'drizzle-orm/postgres-js';
import * as schema from '../schema';

export type DrizzleDB = PostgresJsDatabase&lt;typeof schema&gt;;
</code></pre>
<p>Then use that type anywhere you inject <code>DRIZZLE</code>:</p>
<pre><code class="language-typescript">// any.module.ts
import { Module } from '@nestjs/common';
import { DatabaseModule } from '@database/database.module';

@Module({
  imports: [DatabaseModule],
})
export class AnyModule {}
</code></pre>
<pre><code class="language-typescript">// example.service.ts
import { Inject, Injectable } from '@nestjs/common';
import { DRIZZLE } from '@database/database.constants';
import { DrizzleDB } from '@database/types/database.type';

@Injectable()
export class ExampleService {
  constructor(@Inject(DRIZZLE) private readonly db: DrizzleDB) {}
}
</code></pre>
<p>Because the provider was created with <code>schema</code>, <code>DrizzleDB</code> stays in sync with your tables and queries.</p>
<h3>Takeaway: keep database initialization boring and isolated</h3>
<p>If you treat your database client as infrastructure and give it a dedicated module boundary, three things happen:</p>
<ul>
<li><p><strong>Config stays centralized</strong> (and validated).</p>
</li>
<li><p><strong>Services stay clean</strong> (they inject a token, not a file import).</p>
</li>
<li><p><strong>Future work gets easier</strong> (schema, migrations, and tests build on a stable foundation).</p>
</li>
</ul>
<p>The goal is not cleverness. The goal is a database client that feels <em>boring</em> to use.</p>
<div>
<div>💡</div>
<div><strong>Next post</strong>: Defining a typed Drizzle schema.</div>
</div>

<hr />
<p><strong>🔗 Code so far</strong>: <a href="https://github.com/RubenOAlvarado/finance-api/tree/v0.3.0">https://github.com/RubenOAlvarado/finance-api/tree/v0.3.0</a></p>
]]></content:encoded></item><item><title><![CDATA[Developing a Tailored Config Module for NestJS Applications]]></title><description><![CDATA[Have you ever struggled with more environment variables than actual features? DATABASE_URL, SUPABASE_URL, JWT_SECRET, a couple of flags for local vs production, and maybe some “temporary” variables you promise you’ll clean up later.
If you read proce...]]></description><link>https://blog.rubenoalvarado.com/developing-a-tailored-config-module-for-nestjs-applications</link><guid isPermaLink="true">https://blog.rubenoalvarado.com/developing-a-tailored-config-module-for-nestjs-applications</guid><category><![CDATA[nestjs]]></category><category><![CDATA[DrizzleORM]]></category><category><![CDATA[supabase]]></category><category><![CDATA[TypeScript]]></category><category><![CDATA[Finance App Development]]></category><dc:creator><![CDATA[Ruben O. Alvarado]]></dc:creator><pubDate>Mon, 16 Feb 2026 18:00:47 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/stock/unsplash/An6M5zgFPj4/upload/0469a070eb5ff997268f02dde5c4ccfb.jpeg" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>Have you ever struggled with <strong>more environment variables than actual features?</strong> <code>DATABASE_URL</code>, <code>SUPABASE_URL</code>, <code>JWT_SECRET</code>, a couple of flags for local vs production, and maybe some “temporary” variables you promise you’ll clean up later.</p>
<p>If you read <code>process.env</code> directly everywhere, the codebase becomes fragile fast:</p>
<ul>
<li><p>One typo silently breaks your connection.</p>
</li>
<li><p>One missing variable makes the app crash at runtime.</p>
</li>
<li><p>You end up debugging configuration instead of shipping.</p>
</li>
</ul>
<p>What if there's a better, cleaner, and more professional way to handle this mess? In this post, we'll build a <strong>small, type-safe, validated Config Module</strong> that will serve as the foundation for the rest of this series.</p>
<h2 id="heading-why-a-custom-config-module">Why a custom Config Module?</h2>
<p>Nest already provides <code>@nestjs/config</code>, and it’s great. The issue is that most tutorials stop at “install it and call it a day”.</p>
<p>For a production-grade API, we want a little more:</p>
<ul>
<li><p><strong>One place</strong> to load and validate environment variables</p>
</li>
<li><p><strong>Clear namespaces</strong> like <code>app</code>, and <code>db</code> (for now)</p>
</li>
<li><p><strong>Type inference</strong> so configuration access is safe and discoverable</p>
</li>
<li><p><strong>Fail fast</strong> validations (before the app starts)</p>
</li>
</ul>
<p>This is especially important in our Personal Finance API because our next steps depend on stable configuration:</p>
<ul>
<li><p>Drizzle needs a valid Postgres connection string</p>
</li>
<li><p>Local and production environments must behave predictably</p>
</li>
</ul>
<h2 id="heading-creating-the-module">Creating the module</h2>
<p>We’ll create a module that is <strong>global</strong> and acts as the single source of truth for configuration.</p>
<p>Generate a config module (choose your own path):</p>
<pre><code class="lang-bash">nest g mo config
</code></pre>
<p>Now set up the module using Nest’s <code>ConfigModule</code>, but keep it wrapped behind your own module.</p>
<p>Here’s the baseline:</p>
<pre><code class="lang-tsx">// config/config.module.ts
import { Global, Module } from '@nestjs/common';
import { ConfigModule as NestConfigModule } from '@nestjs/config';

@Global()
@Module({
  imports: [
    NestConfigModule.forRoot({
      isGlobal: true,
      cache: true,
      envFilePath: [`.env.${process.env.NODE_ENV}`, '.env'],
    }),
  ],
  exports: [NestConfigModule],
})
export class ConfigModule {}
</code></pre>
<p>This already gives us:</p>
<ul>
<li><p>Global config (no need to import it everywhere)</p>
</li>
<li><p>Environment-specific <code>.env</code> loading</p>
</li>
<li><p>Caching for performance</p>
</li>
</ul>
<h2 id="heading-defining-configuration-namespaces-app-db">Defining configuration namespaces (app, db)</h2>
<p>Instead of scattering variable names throughout the codebase, we’ll create configuration “namespaces”. This keeps things organized and makes future posts easier to follow.</p>
<p>Example: <code>app</code> config. You can do the same for <code>db</code>.</p>
<pre><code class="lang-tsx">// config/configurations/app.config.ts
import { registerAs } from '@nestjs/config';

export default registerAs(
  'app',
  (): AppConfig =&gt; ({
    port: parseInt(process.env.PORT || '3000', 10),
    nodeEnv: (process.env.NODE_ENV || 'development') as AppConfig['nodeEnv'],
  }),
);

// config/types/app-config.types.ts
export type AppConfig = {
  port: number;
  nodeEnv: 'development' | 'production' | 'test' | 'staging';
};
</code></pre>
<p>For this series, the important part is that by the time we connect Drizzle, we can read something like:</p>
<ul>
<li><code>db.connectionString</code></li>
</ul>
<h2 id="heading-validating-environment-variables-with-joi">Validating environment variables with Joi</h2>
<p>Type safety is nice, but <strong>validation</strong> is what prevents bad configuration from reaching production. We’ll use Joi to validate env variables before the app boots.</p>
<p>Install Joi:</p>
<pre><code class="lang-bash">pnpm i joi
</code></pre>
<p>Create a validation schema:</p>
<pre><code class="lang-tsx">// config/validations/env.validation.ts
import * as Joi from 'joi';

export const envValidationSchema = Joi.object({
  PORT: Joi.number().default(3000),
  NODE_ENV: Joi.string()
    .valid('development', 'production', 'test', 'staging')
    .default('development'),
});
</code></pre>
<p>Now wire everything together:</p>
<pre><code class="lang-tsx">// config/config.module.ts
import { Global, Module } from '@nestjs/common';
import { ConfigModule as NestConfigModule } from '@nestjs/config';

import appConfig from './configurations/app.config';
import { envValidationSchema } from './validations/env.validation';

@Global()
@Module({
  imports: [
    NestConfigModule.forRoot({
      isGlobal: true,
      cache: true,
      envFilePath: [`.env.${process.env.NODE_ENV}`, '.env'],
      load: [appConfig],
      validationSchema: envValidationSchema,
    }),
  ],
  exports: [NestConfigModule],
})
export class ConfigModule {}
</code></pre>
<h2 id="heading-testing-it-quickly">Testing it quickly</h2>
<p>Create a <code>.env</code> file with the variables you defined and boot the app. If any variable is missing or invalid, Nest will fail fast and tell you exactly what's wrong. That's the whole point.</p>
<p>If you see <code>Nest application successfully started</code> in the console, you nailed it.</p>
<h2 id="heading-wrapping-up">Wrapping Up</h2>
<p>At this point, you’ve built a configuration layer that is:</p>
<ul>
<li><p><strong>Centralized</strong> (one module)</p>
</li>
<li><p><strong>Type-safe</strong> (structured config objects)</p>
</li>
<li><p><strong>Validated</strong> (Joi schema)</p>
</li>
<li><p><strong>Ready for the next steps</strong> (Drizzle + Supabase integration)</p>
</li>
</ul>
<p>In the next post, we'll use this module to initialize <strong>Drizzle</strong> with the Supabase Postgres connection string and start defining our schema. But to be ready, we'll need the database config—so that's your homework. See you in the next one!</p>
<div data-node-type="callout">
<div data-node-type="callout-emoji">💡</div>
<div data-node-type="callout-text"><strong>Next post</strong>: Connecting Supabase Postgres to NestJS using Drizzle and our Config Module.</div>
</div>

<hr />
<p><strong>🔗 Code</strong>: <a target="_blank" href="https://github.com/RubenOAlvarado/finance-api/tree/v0.2.0">https://github.com/RubenOAlvarado/finance-api/tree/v0.2.0</a></p>
]]></content:encoded></item><item><title><![CDATA[An Easy Recap of Supabase Essentials]]></title><description><![CDATA[Picture this: you're building your next project, and you know you need authentication, a database, and maybe storage. You could spend days configuring Postgres, setting up auth from scratch, and managing deployment—or you could have it all running in...]]></description><link>https://blog.rubenoalvarado.com/an-easy-recap-of-supabase-essentials</link><guid isPermaLink="true">https://blog.rubenoalvarado.com/an-easy-recap-of-supabase-essentials</guid><category><![CDATA[supabase]]></category><category><![CDATA[TypeScript]]></category><category><![CDATA[DrizzleORM]]></category><category><![CDATA[nestjs]]></category><dc:creator><![CDATA[Ruben O. Alvarado]]></dc:creator><pubDate>Mon, 09 Feb 2026 18:00:49 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/stock/unsplash/LWD60a5a15I/upload/c618ef07bf2f238850a7166f2c98b0d4.jpeg" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>Picture this: you're building your next project, and you know you need authentication, a database, and maybe storage. You <em>could</em> spend days configuring Postgres, setting up auth from scratch, and managing deployment—or you could have it all running in under 5 minutes.</p>
<p>In the vibe coding era, tools like Supabase and Firebase are winning because they solve this exact problem. They let you ship fast without wrestling with infrastructure.</p>
<p>But here's where it gets interesting: when you combine Supabase with your own NestJS backend, you're not sacrificing control for speed—you get <strong>both</strong>. Full control over your database logic, custom business rules, your own auth flow, and the ability to scale exactly how you want. No vendor lock-in, no "this feature isn't supported" roadblocks.</p>
<p>In this post, I'll show you how to set up Supabase as the foundation for a NestJS API that gives you the best of both worlds.</p>
<h2 id="heading-understanding-postgres-auth">Understanding Postgres + Auth</h2>
<p>Here's what makes Supabase special: you're not just getting a database and auth as separate tools. You're getting <strong>a database that knows who your users are</strong>.</p>
<h3 id="heading-postgres-database">Postgres Database</h3>
<p>Supabase gives you a production-grade PostgreSQL database with three ways to access it:</p>
<ul>
<li><p><strong>Direct connection</strong>: Connect with any Postgres client using the connection string (this is what we'll use with Drizzle)</p>
</li>
<li><p><strong>REST API</strong>: PostgREST automatically generates a RESTful API for your tables—no backend needed</p>
</li>
<li><p><strong>Realtime subscriptions</strong>: Listen to database changes in real-time (think collaborative docs, live dashboards)</p>
</li>
</ul>
<p>Why does this matter? <strong>Flexibility</strong>. Start with direct connection for your NestJS API, but if you need to prototype a quick feature, you can hit the REST API directly from your frontend. Need live updates? Turn on realtime subscriptions. Same database, multiple access patterns.</p>
<h3 id="heading-authentication-system">Authentication System</h3>
<p>Supabase Auth handles everything you'd expect:</p>
<ul>
<li><p>Email/password and magic links</p>
</li>
<li><p>OAuth providers (Google, GitHub, etc.)</p>
</li>
<li><p>JWT token generation and validation</p>
</li>
<li><p>User management and sessions</p>
</li>
</ul>
<p>Imagine you have a <code>transactions</code> table. Normally, you'd write backend logic to ensure users can only see their own transactions. With RLS, you write that rule <em>once</em> at the database level:</p>
<p>But here's where it gets powerful: <strong>Row Level Security (RLS)</strong>.</p>
<pre><code class="lang-sql"><span class="hljs-keyword">CREATE</span> <span class="hljs-keyword">POLICY</span> <span class="hljs-string">"Users can only see their own transactions"</span>
<span class="hljs-keyword">ON</span> transactions <span class="hljs-keyword">FOR</span> <span class="hljs-keyword">SELECT</span>
<span class="hljs-keyword">USING</span> (auth.uid() = user_id);
</code></pre>
<p>Now your database automatically enforces this. Whether you access it via your NestJS API, the REST API, or directly—users can only see their own data. No leaked queries, no forgotten permission checks in your code.</p>
<p>And because Supabase stores auth data in the <code>auth</code> schema of the same database, you can join auth tables in your queries, extend user profiles, or add custom claims—all in Postgres.</p>
<h2 id="heading-creating-your-supabase-project">Creating Your Supabase Project</h2>
<p>Alright, let's get your hands dirty. Head over to <a target="_blank" href="http://supabase.com">supabase.com</a> and spin up a new project. The process takes about 5 minutes total, and here's what you need to do:</p>
<p><strong>1. Sign in and start a new project</strong></p>
<ul>
<li><p>Sign in to your Supabase account (or create one if you haven't)</p>
</li>
<li><p>Click "New Project"</p>
</li>
<li><p>Choose your organization or create a new one</p>
</li>
</ul>
<p><strong>2. Configure your project</strong></p>
<ul>
<li>Name your project (e.g., "Finance-API")</li>
</ul>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1770603544395/73f83df2-7ab2-45e5-8048-3bd5acbdc51b.jpeg" alt class="image--center mx-auto" /></p>
<ul>
<li><p><strong>Set a database password</strong>: Click the "Generate a password" button. This is your Postgres database password, so <strong>save it somewhere safe</strong> (password manager, <code>.env</code> file, wherever you keep secrets). You'll need it later.</p>
</li>
<li><p><strong>Select your region</strong>: Choose the one closest to your users. This affects latency—a project in <code>us-east-1</code> will be noticeably slower for users in Europe or Asia. If you're not sure, pick the region closest to <em>you</em> for now.</p>
</li>
</ul>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1770603568892/3d20439a-4b0b-4178-a115-bb30c0fbe296.jpeg" alt class="image--center mx-auto" /></p>
<p><strong>3. Wait for provisioning</strong></p>
<p>Click "Create new project" and wait 2-3 minutes. Supabase is spinning up your Postgres instance, setting up auth, and configuring everything behind the scenes.</p>
<p>Once it's ready, you'll see your project dashboard with all your connection details, API keys, and database info. Before we connect anything, though, we need to understand how Supabase's API keys work—because using the wrong one can create security issues.</p>
<h2 id="heading-a-quick-note-on-api-keys">A Quick Note on API Keys</h2>
<p>Before we move forward, you might notice that Supabase provides two API keys in your dashboard: a <strong>publishable key</strong> and a <strong>secret key</strong>. Here's the thing: <strong>we won't be using either of them for this project</strong>.</p>
<p>We're connecting to Supabase using the <strong>direct Postgres connection string</strong> with Drizzle. This gives us full control over our database queries and lets us use Drizzle's type-safe ORM instead of Supabase's client libraries.</p>
<p>So why mention the API keys at all? Because they're still useful to understand:</p>
<p><strong>Publishable Key (anon key)</strong></p>
<ul>
<li><p>Safe to expose in client-side code (React, Vue, mobile apps)</p>
</li>
<li><p>Respects Row Level Security policies</p>
</li>
<li><p>Perfect if you want your frontend to talk directly to Supabase</p>
</li>
</ul>
<p><strong>Secret Key (service_role key)</strong></p>
<ul>
<li><p>Bypasses ALL security policies—treats you as admin</p>
</li>
<li><p>Backend-only, never expose this</p>
</li>
<li><p>Useful for migrations, admin scripts, or background jobs</p>
</li>
</ul>
<div data-node-type="callout">
<div data-node-type="callout-emoji">💡</div>
<div data-node-type="callout-text"><strong>For this series</strong>: We're using the connection string for our NestJS backend. But if you later want to add a React frontend that reads data directly from Supabase, you'd use the publishable key there. Different tools for different jobs.</div>
</div>

<p>Alright, with that cleared up, let's talk about what we actually covered in this post.</p>
<h2 id="heading-wrapping-up">Wrapping Up</h2>
<p>At this point, you've got a production-ready Supabase project with Postgres and Auth configured. Here's what you now understand:</p>
<ul>
<li><p><strong>Why Supabase + NestJS is powerful</strong>: You get the speed of a BaaS with the control of your own backend</p>
</li>
<li><p><strong>How Postgres and Auth integrate</strong>: Row Level Security lets your database enforce permissions automatically, eliminating entire classes of security bugs</p>
</li>
<li><p><strong>Your connection options</strong>: Direct connection (what we'll use), REST API, or Realtime—each serving different use cases</p>
</li>
<li><p><strong>The foundation is ready</strong>: Your Supabase project is live and waiting for a connection</p>
</li>
</ul>
<p>The next step? We need to connect our NestJS app to this Supabase instance using Drizzle. That means setting up a config module to handle our database credentials securely.</p>
<div data-node-type="callout">
<div data-node-type="callout-emoji">💡</div>
<div data-node-type="callout-text">I'll cover that in the next post. We'll wire up the connection string, configure Drizzle, and get ready to start building our Finance API.</div>
</div>

<p>See you there! 🚀</p>
]]></content:encoded></item><item><title><![CDATA[Bootstrapping a NestJS API for Personal Finance]]></title><description><![CDATA[The majority of NestJS tutorials available online tend to stop at basic CRUD operations or simple TODO list applications. Let's move beyond these beginner examples and build something real and practical that you can actually use in production.
What W...]]></description><link>https://blog.rubenoalvarado.com/bootstrapping-a-nestjs-api-for-personal-finance</link><guid isPermaLink="true">https://blog.rubenoalvarado.com/bootstrapping-a-nestjs-api-for-personal-finance</guid><category><![CDATA[nestjs]]></category><category><![CDATA[TypeScript]]></category><category><![CDATA[JavaScript]]></category><category><![CDATA[Node.js]]></category><category><![CDATA[DrizzleORM]]></category><category><![CDATA[supabase]]></category><category><![CDATA[finance]]></category><dc:creator><![CDATA[Ruben O. Alvarado]]></dc:creator><pubDate>Tue, 03 Feb 2026 01:37:51 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/stock/unsplash/dA0SA67EgOQ/upload/c2742f704c2993d609c8e90abb8b71e8.jpeg" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>The majority of NestJS tutorials available online tend to stop at basic CRUD operations or simple TODO list applications. Let's move beyond these beginner examples and build something real and practical that you can actually use in production.</p>
<h2 id="heading-what-were-building">What We're Building</h2>
<p>We're building a <strong>Personal Finance API</strong> from scratch. This series will guide you through creating a production-ready REST API to manage income, expenses,and accounts types—everything you need to track your money with confidence.</p>
<p>Each post is a <strong>3–4 minute read</strong> focusing on one specific aspect of the application. By the end, you'll have a fully functional API that you can extend or integrate with any frontend.</p>
<h2 id="heading-architecture-overview">Architecture Overview</h2>
<p>Our API will follow a modular, scalable architecture:</p>
<ul>
<li><p><strong>NestJS</strong> as our backend framework (TypeScript, dependency injection, decorators)</p>
</li>
<li><p><strong>Supabase</strong> for PostgreSQL database hosting and authentication</p>
</li>
<li><p><strong>Drizzle ORM</strong> for type-safe database queries and migrations</p>
</li>
<li><p><strong>REST</strong> architecture with clear resource modeling</p>
</li>
</ul>
<p>The application will be organized into feature modules:</p>
<ul>
<li><p><code>auth</code>: User authentication and authorization</p>
</li>
<li><p><code>accounts</code>: account types: cash, debit, and credit</p>
</li>
<li><p><code>transactions</code>: Income and expense tracking</p>
</li>
<li><p><code>categories</code>: Transaction categorization</p>
</li>
</ul>
<p>We'll use semantic versioning throughout this series. For example, by the end of this post we'll have v0.1.0. Minor changes like adding a constraint will bump to v0.1.1, and so on until we reach v1.0.0—a production-ready API.</p>
<p>This approach helps you break down large problems into manageable steps, making planning and execution much easier.</p>
<h2 id="heading-setting-up-the-project">Setting Up the Project</h2>
<p>Let's bootstrap our NestJS application:</p>
<pre><code class="lang-bash"><span class="hljs-comment"># Install the Nest CLI globally</span>
npm i -g @nestjs/cli

<span class="hljs-comment"># Create a new project</span>
nest new finance-api

<span class="hljs-comment"># Choose your preferred package manager (npm, yarn, or pnpm)</span>
</code></pre>
<p>The CLI will generate a clean project structure with:</p>
<ul>
<li><p>TypeScript configuration</p>
</li>
<li><p>Basic module, controller, and service</p>
</li>
<li><p>Testing setup with Jest</p>
</li>
<li><p>ESLint and Prettier configurations</p>
</li>
</ul>
<h2 id="heading-project-structure">Project Structure</h2>
<p>After setup, we'll organize our code following NestJS best practices:</p>
<pre><code class="lang-bash">src/
├── auth/             <span class="hljs-comment"># Authentication module</span>
├── accounts/         <span class="hljs-comment"># Accounts module</span>
├── transactions/     <span class="hljs-comment"># Transactions module</span>
├── categories/       <span class="hljs-comment"># Categories module</span>
├── common/           <span class="hljs-comment"># Shared utilities, decorators, guards</span>
│   ├── decorators/
│   ├── guards/
│   ├── interceptors/
│   └── filters/
├── config/           <span class="hljs-comment"># Configuration module</span>
├── database/         <span class="hljs-comment"># Database connection and Drizzle setup</span>
│   ├── migrations/
│   └── schema/
│   └── seeds/
├── app.module.ts
└── main.ts
</code></pre>
<h2 id="heading-technical-decisions">Technical Decisions</h2>
<h3 id="heading-why-supabase">Why Supabase?</h3>
<p><strong>Supabase</strong> provides:</p>
<ul>
<li><p>Managed PostgreSQL database with automatic backups</p>
</li>
<li><p>Built-in authentication (email/password, OAuth, magic links)</p>
</li>
<li><p>Real-time subscriptions (optional for future features)</p>
</li>
<li><p>Auto-generated REST API (though we'll build our own)</p>
</li>
<li><p>Free tier perfect for development</p>
</li>
</ul>
<h3 id="heading-why-drizzle-orm">Why Drizzle ORM?</h3>
<p><strong>Drizzle</strong> offers:</p>
<ul>
<li><p>Full TypeScript type safety without decorators</p>
</li>
<li><p>Lightweight and performant (faster than TypeORM)</p>
</li>
<li><p>SQL-like syntax that's easy to learn</p>
</li>
<li><p>Migration system that's version-control friendly</p>
</li>
<li><p>Perfect integration with NestJS's modular architecture</p>
</li>
</ul>
<p><strong>Alternative considered</strong>: Prisma (great, but Drizzle gives us more control over queries and has better performance for complex relations).</p>
<p>We'll discuss each of these tools in detail in their own posts. For now, this is a high-level overview of the project we're building. At the end, you can use it as a guide and choose your preferred option.</p>
<h2 id="heading-final-thoughts">Final thoughts</h2>
<p>Here's what you now have:</p>
<p>✅ A clean NestJS project ready for development</p>
<p>✅ Understanding of the overall architecture</p>
<p>✅ A clear folder structure to keep code organized</p>
<p>✅ Knowledge of why we chose Supabase and Drizzle</p>
<p>I know this post is simple, but we're taking small steps to build gradually rather than rushing ahead. I hope this series serves as a guide for your future projects and gives you a framework for accomplishing those big goals.</p>
<p>Review the code so far at the link below:</p>
<p><strong>🔗 Code</strong>: <a target="_blank" href="https://github.com/RubenOAlvarado/finance-api/tree/post-1">[GitHub repository]</a></p>
<div data-node-type="callout">
<div data-node-type="callout-emoji">💡</div>
<div data-node-type="callout-text"><strong>Next post</strong>: We'll set up Supabase</div>
</div>]]></content:encoded></item><item><title><![CDATA[A Guide to Fibonacci Series and Recursion in Go Language]]></title><description><![CDATA[The Fibonacci sequence is one of the most common problems you'll solve throughout your software career. Its implementation can be as simple or complex as you want.
One of the most frequently used solutions is recursion—a core concept in computer scie...]]></description><link>https://blog.rubenoalvarado.com/fibonacci-series-and-recursion-in-go</link><guid isPermaLink="true">https://blog.rubenoalvarado.com/fibonacci-series-and-recursion-in-go</guid><category><![CDATA[Go Language]]></category><category><![CDATA[data structures]]></category><category><![CDATA[algorithms]]></category><category><![CDATA[Recursion]]></category><category><![CDATA[Computer Science]]></category><dc:creator><![CDATA[Ruben O. Alvarado]]></dc:creator><pubDate>Tue, 27 Jan 2026 00:30:27 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/stock/unsplash/_QcLpud-gD0/upload/942aad5cf2231aeb35c16650e6aff5eb.jpeg" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>The Fibonacci sequence is one of the most common problems you'll solve throughout your software career. Its implementation can be as simple or complex as you want.</p>
<p>One of the most frequently used solutions is recursion—a core concept in computer science. Whether you're learning computer science, preparing for your next interview, or simply reinforcing old concepts, join me in writing a Fibonacci sequence using recursion with Go.</p>
<h2 id="heading-what-is-recursion">What is recursion?</h2>
<p>Recursion means breaking a problem into smaller subproblems. Sometimes you'll add or remove something <code>f(n)</code>, or you'll need to adjust the solution <code>f(n - 1)</code>. In some cases, you might solve the problem for half of the dataset.</p>
<p>In the Fibonacci sequence, the function calls itself with smaller inputs. Each recursive call works toward the base case.</p>
<h2 id="heading-problem-statement">Problem Statement</h2>
<blockquote>
<p>Given n calculate the nth Fibonacci number.</p>
</blockquote>
<p>The Fibonacci sequence is a series of numbers where each number is the sum of the two preceding ones, starting with 0 and 1. The sequence begins as follows: 0, 1, 1, 2, 3, 5, 8, 13, 21, 34, ...</p>
<p>Breaking it down:</p>
<ul>
<li><p><strong>Input</strong>: an integer where the series will stop.</p>
</li>
<li><p><strong>Output</strong>: the sequence from <code>0</code> to <code>n</code>.</p>
</li>
</ul>
<p>Now that we've identified the input, output, and approach, it's time to implement it.</p>
<h2 id="heading-algorithm">Algorithm</h2>
<p>First, since the function calls itself, I need to prevent infinite loops. To do this, I define a base case—a condition that tells the function when to stop.</p>
<pre><code class="lang-go"><span class="hljs-keyword">if</span> n &lt;= <span class="hljs-number">1</span> {
    <span class="hljs-keyword">return</span> n
}
</code></pre>
<p>Every recursive function consists of two parts: the base case (when to stop) and the recursive case (when to call itself). I've already defined the base case. Now it's time to declare the recursive case. For Fibonacci, I need to call the function twice with smaller inputs—specifically <code>n - 1</code> and <code>n - 2</code>.</p>
<pre><code class="lang-go"><span class="hljs-keyword">return</span> fibonacci(n<span class="hljs-number">-1</span>) + fibonacci(n<span class="hljs-number">-2</span>)
</code></pre>
<p>You might be asking: "Why does it call itself twice?" Good question. Each number is the sum of the two preceding ones.</p>
<p>The Fibonacci function is mathematically defined as: <code>F(n) = F(n-1) + F(n-2)</code> for <code>n &gt; 1</code>. <code>1</code></p>
<p>So to compute <code>F(4)</code>, you need:</p>
<ul>
<li><p><code>F(3)</code> (which needs <code>F(2)</code> and <code>F(1)</code>)</p>
</li>
<li><p><code>F(2)</code> (which needs <code>F(1)</code> and <code>F(0)</code>)</p>
</li>
</ul>
<p>Easy, right? And there you have it—you've solved the Fibonacci sequence using recursion. But I'm afraid to say it's the worst solution.</p>
<h2 id="heading-visual-example">Visual example</h2>
<p>Why learn something that's a bad solution? Well, because it's the core concept for complex solutions like dynamic programming or memoization. If you're a React programmer, you've used memoization plenty of times with the <code>useMemo</code> or <code>useCallback</code> hooks. So that's why you need to learn recursion first.</p>
<p>An example will make this clearer. Let's find the Fibonacci sequence for the number 4.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1769473721796/4eb7b831-3ee0-4a00-96eb-43b2bdbfe4b8.jpeg" alt class="image--center mx-auto" /></p>
<p>Let's trace through the recursion step by step:</p>
<ol>
<li><p><strong>F(4)</strong> calls <code>F(3)</code> and <code>F(2)</code></p>
</li>
<li><p><strong>F(3)</strong> calls <code>F(2)</code> and <code>F(1)</code></p>
<ul>
<li><p><code>F(2)</code> calls <code>F(1)</code> and <code>F(0)</code></p>
</li>
<li><p><code>F(1)</code> returns 1 (base case)</p>
</li>
<li><p><code>F(0)</code> returns 0 (base case)</p>
</li>
<li><p>So <code>F(2) = 1 + 0 = 1</code></p>
</li>
<li><p><code>F(1)</code> returns 1 (base case)</p>
</li>
<li><p>So <code>F(3) = 1 + 1 = 2</code></p>
</li>
</ul>
</li>
<li><p><strong>F(2)</strong> calls <code>F(1)</code> and <code>F(0)</code></p>
<ul>
<li><p><code>F(1)</code> returns 1 (base case)</p>
</li>
<li><p><code>F(0)</code> returns 0 (base case)</p>
</li>
<li><p>So <code>F(2) = 1 + 0 = 1</code></p>
</li>
</ul>
</li>
<li><p><strong>Final result:</strong> <code>F(4) = 2 + 1 = 3</code></p>
</li>
</ol>
<p>Notice how <code>F(2)</code> is calculated <strong>twice</strong> and <code>F(1)</code> is calculated <strong>three times</strong>. This redundancy is why the naive recursive solution is inefficient—it has exponential time complexity of O(2ⁿ). For larger values of n, the same calculations are repeated thousands or even millions of times.</p>
<p>This is exactly why we need optimization techniques like memoization or dynamic programming, which store previously calculated values to avoid redundant work.</p>
<h2 id="heading-final-thougths">Final Thougths</h2>
<p>Recursion is best used when it makes the solution clearer. When you call a function from another function, the calling function pauses in a partially completed state. Imagine what this does to memory.</p>
<p>Despite its drawbacks, recursion powers many important algorithms, so it's worth understanding how it works.</p>
<p>If you want to dive deeper or practice, try other exercises like factorial or the Tower of Hanoi. Happy coding, and I'll see you in the next one!</p>
]]></content:encoded></item><item><title><![CDATA[Efficiently Reverse Arrays In-Place in Go Language]]></title><description><![CDATA[If you are preparing for technical interviews, sooner or later someone will ask you to reverse an array. At first glance it looks trivial, but it quietly tests how well you understand indexing, boundaries, and memory.
In Go, this problem becomes a gr...]]></description><link>https://blog.rubenoalvarado.com/efficiently-reverse-arrays-in-place-in-go-language</link><guid isPermaLink="true">https://blog.rubenoalvarado.com/efficiently-reverse-arrays-in-place-in-go-language</guid><category><![CDATA[Go Language]]></category><category><![CDATA[data structures]]></category><category><![CDATA[algorithms]]></category><category><![CDATA[Algorithms Data Structures ]]></category><dc:creator><![CDATA[Ruben O. Alvarado]]></dc:creator><pubDate>Mon, 19 Jan 2026 18:00:43 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/stock/unsplash/w50ESgh2h5U/upload/f76f63ce84d844fd8eb80b21235238bd.jpeg" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>If you are preparing for technical interviews, sooner or later someone will ask you to reverse an array. At first glance it looks trivial, but it quietly tests how well you understand indexing, boundaries, and memory.</p>
<p>In Go, this problem becomes a great opportunity: the language gives you clean syntax and multiple assignment, so you can write an in-place solution that is both efficient and easy to read.</p>
<p>In this post I’ll walk you through my approach to reversing a slice in place using start and end indices, without any extra memory. Think of it as a pattern you can reuse in many other algorithms—not just a one-off interview trick.</p>
<p>Let’s start by formalizing the problem we’re trying to solve.</p>
<h3 id="heading-problem-statement"><strong>Problem Statement</strong></h3>
<blockquote>
<p>Given an array of integers, a start index, and an end index, write a function that reverses the integers in-place without using extra memory.</p>
</blockquote>
<p>More formally:</p>
<ul>
<li><p><strong>Input</strong>: an array of integers, an integer for the starting index and another integer for the ending index.</p>
</li>
<li><p><strong>Output</strong>: the same array modified in place, with the elements start and end reversed.</p>
</li>
</ul>
<p>Now that we know exactly what goes in and what should come out, we can focus on defining a simple, safe algorithm to get there.</p>
<h3 id="heading-algorithm"><strong>Algorithm</strong></h3>
<p>Before touching the array, I need to make sure the indices are safe. If start or end are out of range, or if start is not strictly less than end, there is nothing to do and I can just return the original array.</p>
<pre><code class="lang-go"><span class="hljs-keyword">if</span> start &gt;= end || start &lt; <span class="hljs-number">0</span> || end &gt;= <span class="hljs-built_in">len</span>(arr) {
    <span class="hljs-keyword">return</span> arr
}
</code></pre>
<p>Once the input is valid, the idea is simple: swap elements from the edges of the range towards the center. I only need to visit <strong>half</strong> of the elements between start and end. For each position i from the left, I swap it with its counterpart from the right:</p>
<ul>
<li><p>left index: <code>start + i</code></p>
</li>
<li><p>right index: <code>end - i</code></p>
</li>
</ul>
<p>That is why the loop runs up to half the length of the range:</p>
<pre><code class="lang-go"><span class="hljs-keyword">for</span> i := <span class="hljs-number">0</span>; i &lt; (end-start+<span class="hljs-number">1</span>)/<span class="hljs-number">2</span>; i++ {}
</code></pre>
<p>The expression <code>(end - start + 1)</code> is the number of elements in the range <code>[start, end]</code>. Dividing it by <code>2</code> gives the number of swaps we need to perform.</p>
<p>To see this in action, take the array <code>[1, 2, 3]</code> and reverse the whole range:</p>
<ul>
<li><p>First iteration (<code>i = 0</code>): swap <code>arr[0]</code> and <code>arr[2]</code> → <code>[3, 2, 1]</code>.</p>
</li>
<li><p>There is no second iteration, because we already reached the middle.</p>
</li>
</ul>
<p>Thanks to Go's multiple assignment, the swap stays readable and we keep the space complexity at <code>O(1)</code>. When the loop finishes, the original slice has been modified in place, using the same underlying memory.</p>
<pre><code class="lang-go">arr[start+i], arr[end-i] = arr[end-i], arr[start+i]
</code></pre>
<p>When the loop ends, my original array has been modified while keeping the same memory range. To ensure this is true, I’m going to make a simple test.</p>
<h3 id="heading-being-my-own-qa"><strong>Being my Own QA</strong></h3>
<p>Now that the algorithm is in place, I want to prove that it actually does what it says. I'll start with a simple test case and let Go’s testing package be my QA.</p>
<p>In this example, I reverse the entire array <code>[1, 2, 3, 4]</code> by using <code>start = 0</code> and <code>end = 3</code>:</p>
<pre><code class="lang-go"><span class="hljs-function"><span class="hljs-keyword">func</span> <span class="hljs-title">TestReverseArray</span><span class="hljs-params">(t *testing.T)</span></span> {
    arr := []<span class="hljs-keyword">int</span>{<span class="hljs-number">1</span>, <span class="hljs-number">2</span>, <span class="hljs-number">3</span>, <span class="hljs-number">4</span>}
    start := <span class="hljs-number">0</span>
    end := <span class="hljs-number">3</span>

    result := ReverseInPlace(arr, start, end)

    expected := []<span class="hljs-keyword">int</span>{<span class="hljs-number">4</span>, <span class="hljs-number">3</span>, <span class="hljs-number">2</span>, <span class="hljs-number">1</span>}

    <span class="hljs-keyword">for</span> i := <span class="hljs-keyword">range</span> expected {
        <span class="hljs-keyword">if</span> result[i] != expected[i] {
            t.Errorf(<span class="hljs-string">"Expected %v, but got %v"</span>, expected[i], result[i])
            <span class="hljs-keyword">break</span>
        }
    }

    <span class="hljs-keyword">if</span> &amp;arr[<span class="hljs-number">0</span>] != &amp;result[<span class="hljs-number">0</span>] {
        t.Error(<span class="hljs-string">"Expected array to be modified in place, but got a different array reference"</span>)
    }
}
</code></pre>
<p>This test checks two things:</p>
<ul>
<li><p>The <strong>values</strong> are correct: <code>[1, 2, 3, 4]</code> becomes <code>[4, 3, 2, 1]</code>.</p>
</li>
<li><p>The <strong>memory</strong> is the same: comparing <code>&amp;arr[0]</code> and <code>&amp;result[0]</code> ensures that we did not create a new array behind the scenes, we modified the original one in place.</p>
</li>
</ul>
<p>You can add more test cases to cover edge scenarios, for example:</p>
<ul>
<li><p>A subrange in the middle of the array.</p>
</li>
<li><p>A range of length 1.</p>
</li>
<li><p>Invalid ranges, such as <code>start &gt; end</code> or <code>end out of bounds</code>, where the function should simply return the original array.</p>
</li>
</ul>
<h3 id="heading-final-thoughts"><strong>Final Thoughts</strong></h3>
<p>Reversing an array in place isn’t just a classic interview question. It is a nice way to practice things you use all the time: indexes, boundaries, and how memory works in Go.</p>
<p>The goal is not to memorize this exact solution, but to keep the pattern: move from the ends toward the middle, touch only half of the range, and stay at <code>O(1)</code> space. From there you can play with variations like subranges, rotations, or different data types.</p>
<p>If you want more exercises like this, check out my algorithms repo: <a target="_blank" href="https://github.com/RubenOAlvarado/algorithms">github.com/RubenOAlvarado/algorithms</a></p>
<p>Pick a problem, try your own solution, then compare it with mine. That kind of practice is what really adds up over time.</p>
<p>Happy coding and I’ll see you in the next one!</p>
]]></content:encoded></item><item><title><![CDATA[Easy Steps to Generate a Config Module in NestJS]]></title><description><![CDATA[When I started with NestJS, I didn't understand modules, interceptors, guards, and other advanced techniques the framework offers. As a result, I built insecure applications with poor practices. Over time, I learned the hard way which patterns truly ...]]></description><link>https://blog.rubenoalvarado.com/easy-steps-to-generate-a-config-module-in-nestjs</link><guid isPermaLink="true">https://blog.rubenoalvarado.com/easy-steps-to-generate-a-config-module-in-nestjs</guid><category><![CDATA[Node.js]]></category><category><![CDATA[nestjs]]></category><category><![CDATA[TypeScript]]></category><category><![CDATA[configuration]]></category><dc:creator><![CDATA[Ruben O. Alvarado]]></dc:creator><pubDate>Mon, 01 Dec 2025 18:00:46 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/stock/unsplash/UMlT0bviaek/upload/2706d5a8bd1e5234cb46f75bc20fa986.jpeg" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>When I started with NestJS, I didn't understand modules, interceptors, guards, and other advanced techniques the framework offers. As a result, I built insecure applications with poor practices. Over time, I learned the hard way which patterns truly matter for production-grade applications.</p>
<p>After several years working with NestJS, I've collected capabilities I want to share. One is creating a custom config module where you can declare, load, and validate environment variables. After reading this post, you'll build more robust, production-ready applications.</p>
<h2 id="heading-setting-up-the-project">Setting up the project</h2>
<p>First, I'll install the Nest CLI globally to access the framework's capabilities. I like using the CLI to boost my productivity when working with Nest.</p>
<pre><code class="lang-bash">npm install -g @nestjs/cli
</code></pre>
<p>With the CLI installed, I can create a new Nest project using the command <code>nest new</code>. I prefer working with pnpm as my package manager, but you can choose whichever works best for you. I'll name my project <code>config-module-example</code>.</p>
<pre><code class="lang-bash">nest new config-module-example
</code></pre>
<p>Now I'll install the config service from Nest.</p>
<pre><code class="lang-bash">pnpm i @nestjs/config
</code></pre>
<p>With the project set up, it's time to start building. I'll begin by creating a new module.</p>
<h2 id="heading-creating-the-module">Creating the Module</h2>
<p>As a best practice, I create a common folder for configurations, database schemas, definitions, validations, and other non-business logic utilities. Let's start there.</p>
<p>Using the CLI, I'll run this command:</p>
<pre><code class="lang-bash">nest g mo common/config
</code></pre>
<p>This command creates a config module inside the common folder and a <code>config.module.ts</code> file where I'll define my custom configuration module—don't confuse it with the built-in one.</p>
<p>To make my module global, I'll add the <code>@Global</code> decorator so I can use it throughout the entire application. I also need to import the <code>@nestjs/config</code> package but rename it as <code>NestConfigModule</code> to avoid confusion with my own config module.</p>
<pre><code class="lang-typescript"><span class="hljs-keyword">import</span> { ConfigModule <span class="hljs-keyword">as</span> NestConfigModule } <span class="hljs-keyword">from</span> <span class="hljs-string">'@nestjs/config'</span>;
</code></pre>
<p>Now I'll configure how the module behaves. Since I'm working with .env files, I need to tell the Nest container where to find them and enable caching. I also need to export this module so it can be used as a provider.</p>
<p>With these configurations in place, my module looks like this:</p>
<pre><code class="lang-typescript"><span class="hljs-meta">@Global</span>()
<span class="hljs-meta">@Module</span>({
  imports: [
    NestConfigModule.forRoot({
      isGlobal: <span class="hljs-literal">true</span>,
      envFilePath: [
        <span class="hljs-string">`.env<span class="hljs-subst">${process.env.NODE_ENV ? <span class="hljs-string">`.<span class="hljs-subst">${process.env.NODE_ENV}</span>`</span> : <span class="hljs-string">''</span>}</span>`</span>,
      ],
      cache: <span class="hljs-literal">true</span>,
    }),
  ],
  <span class="hljs-built_in">exports</span>: [NestConfigModule],
})
<span class="hljs-keyword">export</span> <span class="hljs-keyword">class</span> ConfigModule {}
</code></pre>
<p>Pay attention to the <code>envFilePath</code> property—this tells the module to use the environment-specific .env file if <code>NODE_ENV</code> is present, or the default one if not. With my config module defined, I'll now define the types for working.</p>
<h2 id="heading-defining-configuration-types">Defining Configuration Types</h2>
<p>For this example, I'll declare some basic environment variables. You can extend them as needed.</p>
<p>Under the common folder, I'll create a types folder with a file called <code>app.types.ts</code>. Here I'll define the <code>AppConfig</code> type:</p>
<pre><code class="lang-typescript"><span class="hljs-keyword">export</span> <span class="hljs-keyword">type</span> AppConfig = {
  port: <span class="hljs-built_in">number</span>;
  nodeEnv: <span class="hljs-string">'development'</span> | <span class="hljs-string">'production'</span> | <span class="hljs-string">'test'</span> | <span class="hljs-string">'staging'</span>;
};
</code></pre>
<p>With the types defined, I can now set up the application's configuration.</p>
<h2 id="heading-working-with-configurations">Working with Configurations</h2>
<p>With the types defined, I'll now create the configuration file. Inside the <code>config</code> folder, I'll create a <code>configurations</code> folder and add a file called <code>app.config.ts</code>. I need to import the <code>registerAs</code> function from <code>@nestjs/config</code>. This function registers a configuration namespace that I can reference later. Here's how it looks:</p>
<pre><code class="lang-typescript"><span class="hljs-keyword">export</span> <span class="hljs-keyword">default</span> registerAs(
  <span class="hljs-string">'app'</span>,
  (): <span class="hljs-function"><span class="hljs-params">AppConfig</span> =&gt;</span> ({
    port: <span class="hljs-built_in">parseInt</span>(process.env.PORT || <span class="hljs-string">'3000'</span>, <span class="hljs-number">10</span>),
    nodeEnv: (process.env.NODE_ENV || <span class="hljs-string">'development'</span>) <span class="hljs-keyword">as</span>
      | <span class="hljs-string">'development'</span>
      | <span class="hljs-string">'production'</span>
      | <span class="hljs-string">'test'</span>
      | <span class="hljs-string">'staging'</span>,
  }),
);
</code></pre>
<p>I'm using <code>registerAs</code> with two arguments: the namespace token <code>'app'</code> and a factory function that returns the <code>AppConfig</code> object. This maps my environment variables to a type-safe configuration. But what happens if someone loads a corrupt .env file with invalid variables? To prevent this, the next step is to define and validate a schema.</p>
<h2 id="heading-validating-schemas-with-joi">Validating Schemas with Joi</h2>
<p>With the configuration in place, I need to ensure the .env file doesn't have corrupt or invalid variables. To do this, I'll create a schema with validations using Joi.</p>
<p>First, I'll install Joi:</p>
<pre><code class="lang-bash">pnpm i joi
</code></pre>
<p>Next, I'll create a validations folder under my config module to hold my schemas. Using Joi, I'll define the validation schema:</p>
<pre><code class="lang-typescript"><span class="hljs-keyword">export</span> <span class="hljs-keyword">const</span> appValidationSchema = Joi.object({
  PORT: Joi.number().default(<span class="hljs-number">3000</span>),
  NODE_ENV: Joi.string()
    .valid(<span class="hljs-string">'development'</span>, <span class="hljs-string">'production'</span>, <span class="hljs-string">'test'</span>)
    .default(<span class="hljs-string">'development'</span>),
});
</code></pre>
<p>The schema validates that <code>PORT</code> is a number and <code>NODE_ENV</code> is one of the allowed environment values, with sensible defaults for both. With all the pieces ready, it's time to wire everything together and make this configuration work.</p>
<h2 id="heading-wiring-it-all-together">Wiring It All Together</h2>
<p>Now I'll connect all the pieces. I'll return to the <code>config.module.ts</code> file and add the configuration loader and validation schema:</p>
<pre><code class="lang-typescript"><span class="hljs-meta">@Global</span>()
<span class="hljs-meta">@Module</span>({
  imports: [
    NestConfigModule.forRoot({
      isGlobal: <span class="hljs-literal">true</span>,
      load: [appConfig],
      validationSchema: appValidationSchema,
      envFilePath: [
        <span class="hljs-string">`.env<span class="hljs-subst">${process.env.NODE_ENV ? <span class="hljs-string">`.<span class="hljs-subst">${process.env.NODE_ENV}</span>`</span> : <span class="hljs-string">''</span>}</span>`</span>,
      ],
      cache: <span class="hljs-literal">true</span>,
    }),
  ],
  <span class="hljs-built_in">exports</span>: [NestConfigModule],
})
<span class="hljs-keyword">export</span> <span class="hljs-keyword">class</span> ConfigModule {}
</code></pre>
<p>The <code>load</code> property tells the module which configuration files to load, and <code>validationSchema</code> ensures the environment variables are valid before the app starts. With the module complete, let's test that it works.</p>
<h2 id="heading-testing-the-configuration-works">Testing the Configuration works</h2>
<p>To test the configuration, I'll log the port and environment at startup. In my <code>main.ts</code> file, I'll inject the <code>ConfigService</code> and retrieve the configuration values:</p>
<pre><code class="lang-typescript"><span class="hljs-keyword">const</span> configService = app.get(ConfigService);

<span class="hljs-keyword">const</span> port = configService.get&lt;<span class="hljs-built_in">number</span>&gt;(<span class="hljs-string">'app.port'</span>, { infer: <span class="hljs-literal">true</span> }) <span class="hljs-keyword">as</span> <span class="hljs-built_in">number</span>;

<span class="hljs-keyword">const</span> nodeEnv = configService.get&lt;<span class="hljs-built_in">string</span>&gt;(<span class="hljs-string">'app.nodeEnv'</span>, { infer: <span class="hljs-literal">true</span> }) <span class="hljs-keyword">as</span> <span class="hljs-built_in">string</span>;

<span class="hljs-keyword">if</span> (nodeEnv === <span class="hljs-string">'development'</span>) {

    <span class="hljs-built_in">console</span>.log(<span class="hljs-string">`Application is running in <span class="hljs-subst">${nodeEnv}</span> mode`</span>);

    <span class="hljs-built_in">console</span>.log(<span class="hljs-string">`Listening on port <span class="hljs-subst">${port}</span>`</span>);

}
</code></pre>
<p>Before running the application, I'll create a <code>.env</code> file with the environment variables:</p>
<pre><code class="lang-plaintext">PORT=3000

NODE_ENV=development
</code></pre>
<p>Now I'll run <code>pnpm run start:dev</code>. If everything is configured correctly, the application will start and display the development logs.</p>
<h2 id="heading-final-thoughts">Final Thoughts</h2>
<p>Creating a custom configuration module in NestJS is essential for building robust, maintainable applications. In this article, I've shown you how to structure environment variables, validate them with Joi schemas, and organize them in a way that scales with your project.</p>
<p>This setup prevents the configuration mistakes I made early in my NestJS journey. Type-safe configurations with validation catch errors before they reach production, making your applications more reliable and easier to maintain.</p>
<p>You can find the complete code in my Github repository: <a target="_blank" href="https://github.com/RubenOAlvarado/config-module-example">https://github.com/RubenOAlvarado/config-module-example</a></p>
<p>Happy coding—see you in the next one!</p>
]]></content:encoded></item><item><title><![CDATA[Learn Array Chunking in Go: A Comprehensive Algorithm Approach]]></title><description><![CDATA[Throughout my career, I've encountered array chunking in everything from pagination systems to batch processing jobs. What seems simple at first glance hides tricky edge cases that can silently corrupt your data—like out-of-bounds errors or inconsist...]]></description><link>https://blog.rubenoalvarado.com/learn-array-chunking-in-go</link><guid isPermaLink="true">https://blog.rubenoalvarado.com/learn-array-chunking-in-go</guid><category><![CDATA[Go Language]]></category><category><![CDATA[algorithms]]></category><category><![CDATA[Algorithms Data Structures ]]></category><category><![CDATA[leetcode]]></category><category><![CDATA[leetcode-solution]]></category><dc:creator><![CDATA[Ruben O. Alvarado]]></dc:creator><pubDate>Mon, 24 Nov 2025 18:00:32 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/stock/unsplash/uHOLsLKYOCY/upload/2a23a9bf40dbf1356aac1e189d485701.jpeg" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>Throughout my career, I've encountered array chunking in everything from pagination systems to batch processing jobs. What seems simple at first glance hides tricky edge cases that can silently corrupt your data—like out-of-bounds errors or inconsistent chunk sizes.</p>
<p>Today, I'm going to show you my battle-tested algorithm for chunking arrays in Go—one that handles all those edge cases cleanly.</p>
<h2 id="heading-problem-statement">Problem Statement</h2>
<blockquote>
<p>Write a function that takes an array and a chunk size as input. The function should return a new array where the original array is split into chunk of the specific size.</p>
</blockquote>
<p>I like to start by breaking down the problem into three parts: input, process, and expected output. This way, I can identify the steps to go from A (the input) to B (the output).</p>
<p><strong><em>Input:</em></strong> The array to be split and an integer that indicates the chunk size.</p>
<p><strong><em>Output:</em></strong> An array of arrays.</p>
<p>With this identified, I can start with my solution. The expected array is formed by smaller arrays, where each one is a chunk from the original array with the specified size. Now, I can plan an algorithm to obtain these chunks.</p>
<h2 id="heading-algorithm-to-solve-it">Algorithm to Solve it</h2>
<p>The first step for splitting the array into chunks is validating the size. My first code block is an if statement that checks whether the input is less than or equal to zero. If it is, I return nil since the array can't be split into chunks of zero length.</p>
<pre><code class="lang-go"><span class="hljs-keyword">if</span> size &lt;= <span class="hljs-number">0</span> {
        <span class="hljs-keyword">return</span> <span class="hljs-literal">nil</span>
}
</code></pre>
<p>Next, I initialize a new array to hold the chunks.</p>
<pre><code class="lang-go"><span class="hljs-keyword">var</span> chunks [][]<span class="hljs-keyword">int</span>
</code></pre>
<p>Then, I loop through the original array in increments of the chunk size. I start at index zero, and in each iteration, I increment my index by the chunk size value. For example, if the chunk size is 2, in the first iteration <code>i = 0</code>, in the second <code>i = 2</code>, in the third <code>i = 4</code>, and so on.</p>
<pre><code class="lang-go"><span class="hljs-keyword">for</span> i := <span class="hljs-number">0</span>; i &lt; <span class="hljs-built_in">len</span>(arr); i += size {}
</code></pre>
<p>For each iteration, I need to determine the end position of the chunk. My <code>i</code> variable marks where the chunk starts, so I use the <a target="_blank" href="https://pkg.go.dev/builtin#min">min</a> built-in function to find where it should end.</p>
<pre><code class="lang-go">end := min(i+size, <span class="hljs-built_in">len</span>(arr))
</code></pre>
<p>Finally, I append the <code>chunks</code> array with the portion of the original array, using a slice with my two variables <code>i</code> and <code>end</code>.</p>
<pre><code class="lang-go">chunks = <span class="hljs-built_in">append</span>(chunks, arr[i:end])
</code></pre>
<p>Once I've looped through the entire original array, I have all the chunks stored in the new array. I get my expected output—now I just need to return it.</p>
<pre><code class="lang-go"><span class="hljs-keyword">return</span> chunks
</code></pre>
<h2 id="heading-final-thoughts">Final Thoughts</h2>
<p>As you can see, my approach is simple but effective. I like to keep things simple—I prefer understanding the problem over chasing fancy solutions.</p>
<p>If you want to see the code for this and other algorithms, check out my GitHub repository: <a target="_blank" href="https://github.com/RubenOAlvarado/algorithms">https://github.com/RubenOAlvarado/algorithms</a></p>
<p>Remember, this is my algorithm—you can define your own. Use this as a guide if you're stuck or have questions about the topic. After all, the best artists steal, and coding is an art.</p>
<p>What other chunking strategies have you used in production? Or better yet—try extending this to handle 2D arrays and share your solution on GitHub. Keep coding, and I'll see you in the next one.</p>
]]></content:encoded></item><item><title><![CDATA[Step-by-Step: Implementing Custom Decorators in NestJs Using Class-Validator and Drizzle]]></title><description><![CDATA[When building APIs, you must validate your inputs and outputs. If your API accepts any data, failure is only a matter of time. Instead of adding more ifs, use declarative validation: NestJS + class-validator + class-transformer, an async constraint t...]]></description><link>https://blog.rubenoalvarado.com/implementing-custom-decorators-in-nestjs</link><guid isPermaLink="true">https://blog.rubenoalvarado.com/implementing-custom-decorators-in-nestjs</guid><category><![CDATA[class-transfomer]]></category><category><![CDATA[REST API]]></category><category><![CDATA[nestjs]]></category><category><![CDATA[TypeScript]]></category><category><![CDATA[TypeScript Tutorial]]></category><category><![CDATA[class-validator]]></category><category><![CDATA[DrizzleORM]]></category><category><![CDATA[PostgreSQL]]></category><dc:creator><![CDATA[Ruben O. Alvarado]]></dc:creator><pubDate>Mon, 17 Nov 2025 18:00:49 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/stock/unsplash/g5jpH62pwes/upload/d5fa7f39e55795d63581d3ee05895e4f.jpeg" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>When building APIs, you must validate your inputs and outputs. If your API accepts any data, failure is only a matter of time. Instead of adding more ifs, use declarative validation: NestJS + class-validator + class-transformer, an async constraint that queries your DB, and a custom decorator integrated with the container. Result: errors stopped before the service layer and reusable rules across all your DTOs, with less duplicated logic.</p>
<p>In this tutorial, I'll teach you how to build your own custom decorator to prevent these scenarios.</p>
<h2 id="heading-setting-up-the-project">Setting Up the Project</h2>
<p>Let's start with a base project. I have a template repository with a RESTful API using NestJS as the framework, PostgreSQL as the database, and Drizzle as the ORM—but you can create your own.</p>
<p>This is the repo I'm using: <a target="_blank" href="https://github.com/RubenOAlvarado/nestjs-drizzle-template">https://github.com/RubenOAlvarado/nestjs-drizzle-template</a> This also includes Swagger integration and a Docker Compose file for your own use.</p>
<p>With the repository set up and the API running, the next natural step is to model our data.</p>
<h2 id="heading-userschema">UserSchema</h2>
<p>Let's start with the simplest model in our application. For the user, we have these properties: id, name, and email. You can skip the timestamps if you want—I like to include them as good practice. And since we're working with Postgres, we need to import from the pg-core package from Drizzle.</p>
<pre><code class="lang-tsx">export const users = pgTable('users', {
  id: integer('id').primaryKey().generatedByDefaultAsIdentity(),
  name: text('name').notNull(),
  email: text('email').notNull().unique(),
  createdAt: timestamp('created_at').defaultNow().notNull(),
  updatedAt: timestamp('updated_at').defaultNow().notNull(),
});

export type User = typeof users.$inferSelect;
export type NewUser = typeof users.$inferInsert;
</code></pre>
<p>As you can see, we're defining the ID as identity. We're also creating types from the schema—this is a bonus we don't need for this tutorial, but it's a helpful tip for your future projects. This schema defines the pattern we'll follow throughout this application.</p>
<h2 id="heading-taskschema">TaskSchema</h2>
<p>Now let's model our tasks, which are related to users through a foreign key to enable compound queries.</p>
<p>A task has these properties: id, title, and description. The user field references the users schema using the ID field with on delete cascade.</p>
<pre><code class="lang-tsx">export const tasks = pgTable('tasks', {
  id: integer('id').primaryKey().generatedByDefaultAsIdentity(),
  title: text('title').notNull(),
  description: text('description').notNull(),
  userId: integer('user_id')
    .notNull()
    .references(() =&gt; users.id, { onDelete: 'cascade' }),
  createdAt: timestamp('created_at').defaultNow().notNull(),
  updatedAt: timestamp('updated_at').defaultNow().notNull(),
});

export type Task = typeof tasks.$inferSelect;
export type NewTask = typeof tasks.$inferInsert;
</code></pre>
<p>With both schemas defined, we can now declare relations to unlock readable queries with Drizzle.</p>
<h2 id="heading-sql-like-or-not-sql-like">SQL-like or Not SQL-like?</h2>
<p>There's ongoing debate about whether SQL-like syntax or ORM-style syntax is better. Drizzle offers both. I prefer the SQL-like functionality, but for this tutorial we're using the Queries API to keep things simple. To make this work, we need to define relations: a task has one user, and a user has many tasks.</p>
<pre><code class="lang-tsx">export const tasksRelations = relations(tasks, ({ one }) =&gt; ({
  user: one(users, {
    fields: [tasks.userId],
    references: [users.id],
    relationName: 'user_tasks',
  }),
}));

export const userRelations = relations(users, ({ many }) =&gt; ({
  tasks: many(tasks, { relationName: 'user_tasks' }),
}));
</code></pre>
<p>With the schemas and relations defined, we can now work on our endpoints. But first, generate and run your migration—this will connect your database to your application. If you're using my template, you're all set. If not, <a target="_blank" href="https://orm.drizzle.team/docs/overview">read the Drizzle documentation</a> to fully set up your database connection and migrations.</p>
<h2 id="heading-working-with-controllers">Working with Controllers</h2>
<p>Since tasks belong to users, our API design will follow this structure. This creates a semantic hierarchy showing that tasks belong to the users resource. If you want to dive deeper into RESTful API design, read this excellent article from Microsoft: <a target="_blank" href="https://learn.microsoft.com/en-us/azure/architecture/best-practices/api-design">https://learn.microsoft.com/en-us/azure/architecture/best-practices/api-design</a>. And for God's sake, never return a 200 status code with an empty array or an error message.</p>
<p>If you've been working with NestJS, you already know how to generate resources with the CLI. Let's generate resources for our two modules: users and tasks.</p>
<pre><code class="lang-bash">nest g res users
nest g res tasks
</code></pre>
<p>For the transport layer, select REST API and enter <code>y</code> when prompted to generate CRUD endpoints.</p>
<p>With both modules created, open the <code>tasks.controller.ts</code> file and update the controller definition from <code>tasks</code> to <code>users/:userId/tasks</code>.</p>
<pre><code class="lang-bash">@Controller(<span class="hljs-string">'users/:userId/tasks'</span>)
<span class="hljs-built_in">export</span> class TasksController {}
</code></pre>
<p>Next, define a GET method to fetch all tasks belonging to a specific user.</p>
<pre><code class="lang-tsx">@Get()
findAll(@Param() { userId }: UserIdParamDto) {
    return this.tasksService.findAllByUserId(userId);
}
</code></pre>
<p>Since our route depends on the <code>userId</code>, we need to validate this path parameter to prevent errors before they reach the service layer.</p>
<h2 id="heading-creating-the-param-dto">Creating the Param DTO</h2>
<p>We'll define a param DTO that transforms and validates the userId from the path. This DTO has these key elements: the <code>ApiProperty</code> decorator tells Swagger how to present this attribute and its metadata. The <code>IsNotEmpty</code> decorator marks it as required. The <code>Type</code> decorator from class-transformer converts the ID to a number—all URL params and query fields come through as strings.</p>
<p>Once transformed, we use the <code>IsInt</code> and <code>Min</code> decorators together to ensure the ID is an integer greater than or equal to 1. Since we don't have an ID 0 (or at least we shouldn't), this validation keeps our data clean. Our DTO definition looks like this:</p>
<pre><code class="lang-tsx">export class UserIdParamDto {
  @ApiProperty({
    description: 'Unique identifier of the user',
    example: 1,
    type: Number,
  })
  @IsNotEmpty({ message: 'User ID must be provided' })
  @Type(() =&gt; Number)
  @Transform(({ value }) =&gt; parseInt(String(value), 10))
  @IsInt({ message: 'User ID must be a valid number' })
  @Min(1, { message: 'User ID must be a positive number' })
  userId: number;
}
</code></pre>
<p>These checks cover type and range, but they don’t verify existence in the database. Let’s add an async constraint.</p>
<h2 id="heading-creating-the-findone-method">Creating the findOne Method</h2>
<p>Open your <code>UsersService</code> file and leave the class empty:</p>
<pre><code class="lang-tsx">@Injectable()
export class UsersService {}
</code></pre>
<p>If you're using my template, you have an injectable DrizzleClient; if not, you'll figure it out later. In the constructor, inject the DrizzleClient.</p>
<pre><code class="lang-tsx">constructor(@Inject(DRIZZLE) private readonly drizzle: DrizzleClient) {}
</code></pre>
<p>Now, define the <code>findOne</code> method. This will use the Queries API from Drizzle, returning the first occurrence where the retrieved ID equals the user ID. To verify this equality, import the <code>eq</code> utility from the Drizzle package. This leaves our method looking like this:</p>
<pre><code class="lang-tsx">findOne(id: number) {
    return this.drizzle.query.users.findFirst({ where: eq(users.id, id) });
}
</code></pre>
<p>With the TasksService, follow the same approach—but this time, return all tasks found and include the user.</p>
<pre><code class="lang-tsx">@Injectable()
export class TasksService {
  constructor(@Inject(DRIZZLE) private readonly drizzle: DrizzleClient) {}

  findAllByUserId(userId: number) {
    return this.drizzle.query.tasks.findMany({
      where: eq(tasks.userId, userId),
      with: { user: true },
    });
  }
}
</code></pre>
<p>Make sure to export both services in their module classes. With our service layer defined, we can create our constraint that injects it.</p>
<h2 id="heading-creating-our-constraint">Creating our Constraint</h2>
<p>We'll create an async constraint that uses the <code>UsersService</code> to verify whether the user exists.</p>
<p>Create a class called <code>UserExistConstraint</code> that implements the <code>ValidatorConstraintInterface</code> from class-validator. Use the <code>ValidatorConstraint</code> decorator to mark this as an async validator—we're connecting to the database. You can also optionally provide a name for the constraint. Make it <code>Injectable</code> so Nest recognizes it as a provider. Here's what our code looks like so far:</p>
<pre><code class="lang-tsx">@ValidatorConstraint({ async: true, name: 'UserExist' })
@Injectable()
export class UserExistConstraint implements ValidatorConstraintInterface {}
</code></pre>
<p>Implement the validate method from the interface. This method receives a userId number as a parameter. Call the <code>findOne</code> method from <code>UsersService</code> to retrieve the user with that ID. Return <code>!!user</code> for true if exists and false otherwise.</p>
<p>Finally, define a defaultMessage in case you don't specify one when using the decorator. That's it—your constraint is ready.</p>
<pre><code class="lang-tsx">@ValidatorConstraint({ async: true, name: 'UserExist' })
@Injectable()
export class UserExistConstraint implements ValidatorConstraintInterface {
  constructor(private readonly usersService: UsersService) {}

  async validate(userId: number) {
    const user = await this.usersService.findOne(userId);
    return !!user;
  }

  defaultMessage() {
    return 'User with the given ID does not exist.';
  }
}
</code></pre>
<p>To avoid sprinkling Validate everywhere, we’ll wrap the constraint in a reusable decorator.</p>
<h2 id="heading-making-it-a-decorator">Making it a Decorator</h2>
<p>Let's wrap our constraint in a reusable decorator so we can apply it to any DTO using the decorator pattern. Register the decorator as <code>UserExist</code> with the <code>registerDecorator</code> utility. In the validator property, use the constraint we just defined: <code>UserExistConstraint</code>.</p>
<pre><code class="lang-tsx">export function UserExist(validationOptions?: ValidationOptions) {
  return function (object: object, propertyName: string) {
    registerDecorator({
      target: object.constructor,
      async: true,
      propertyName,
      options: validationOptions,
      validator: UserExistConstraint,
    });
  };
}
</code></pre>
<p>And there you go—your userId will be validated each time you call the tasks endpoint. Or will it? Not yet. We need to integrate it into the Nest lifecycle.</p>
<h2 id="heading-the-final-spice-in-our-recipe">The final spice in our Recipe</h2>
<p>We need to tell Nest that this constraint is a provider and tell class-validator to use the Nest container to resolve dependencies.</p>
<p>First, add <code>UserExistConstraint</code> as a provider in the <code>TasksModule</code>. This way, Nest will allow <code>TasksModule</code> to inject this constraint. Don't forget to import the <code>UsersModule</code> so you can inject the <code>UsersService</code>.</p>
<pre><code class="lang-tsx">@Module({
  imports: [UsersModule],
  controllers: [TasksController],
  providers: [TasksService, UserExistConstraint],
})
export class TasksModule {}
</code></pre>
<p>Finally, in the <code>main.ts</code> file, import the <code>useContainer</code> function from class-validator and configure it to use the Nest app (the Nest container) for dependency injection. And voilà! Your custom validator should now work.</p>
<pre><code class="lang-tsx">useContainer(app.select(AppModule), { fallbackOnErrors: true });
</code></pre>
<p>With DI in place, we can verify runtime behavior with a quick request.</p>
<h2 id="heading-integrations-tests-kind-of">Integrations Tests… Kind of</h2>
<p>Add some dummy data to your database using Drizzle Studio, Drizzle Seed, or directly in your database; for this example, I used Drizzle Seed. Now, test the tasks endpoint. If the ID exists, you should see a result similar to this:</p>
<pre><code class="lang-bash">[
  {
    <span class="hljs-string">"id"</span>: 3,
    <span class="hljs-string">"title"</span>: <span class="hljs-string">"ulcXZ7wJVwvLI6whPeg"</span>,
    <span class="hljs-string">"description"</span>: <span class="hljs-string">"cfMBXl9heU9w75Ijkpx"</span>,
    <span class="hljs-string">"userId"</span>: 4,
    <span class="hljs-string">"createdAt"</span>: <span class="hljs-string">"2025-07-23T03:18:12.712Z"</span>,
    <span class="hljs-string">"updatedAt"</span>: <span class="hljs-string">"2025-03-27T16:56:35.363Z"</span>,
    <span class="hljs-string">"user"</span>: {
      <span class="hljs-string">"id"</span>: 4,
      <span class="hljs-string">"name"</span>: <span class="hljs-string">"Shauna"</span>,
      <span class="hljs-string">"email"</span>: <span class="hljs-string">"inflatable_autum@web.de"</span>,
      <span class="hljs-string">"createdAt"</span>: <span class="hljs-string">"2023-10-24T10:58:31.664Z"</span>,
      <span class="hljs-string">"updatedAt"</span>: <span class="hljs-string">"2024-02-18T23:40:17.943Z"</span>
    }
  }
]
</code></pre>
<p>If not, you should receive a 400 error with the message <code>User with the given ID does not exist.</code> You can also specify a custom message when using the decorator.</p>
<pre><code class="lang-bash">{<span class="hljs-string">"message"</span>:[<span class="hljs-string">"User with the given ID does not exist."</span>],<span class="hljs-string">"error"</span>:<span class="hljs-string">"Bad Request"</span>,<span class="hljs-string">"statusCode"</span>:400}
</code></pre>
<p>This flow confirms that validation happens before executing business logic, reducing errors and coupling.</p>
<h2 id="heading-final-thoughts">Final Thoughts</h2>
<p>This pattern is easy to extend and customize when building custom decorators and getting the most from Drizzle ORM and the NestJS framework. As homework, try validating task existence by creating a find-one endpoint, or validate email uniqueness—your imagination or stakeholder requirements are the limit.</p>
<p>Let me know in the comments how you feel about this approach or if you want to dive deeper into any topic covered in this tutorial. You can check the complete code in this repository: <a target="_blank" href="https://github.com/RubenOAlvarado/custom-validations-example">https://github.com/RubenOAlvarado/custom-validations-example</a></p>
<p>I hope this helped you create better RESTful APIs with NestJS. I'll see you in the next one!</p>
]]></content:encoded></item><item><title><![CDATA[Learn to Capitalize the First Letter of Each Word with Go]]></title><description><![CDATA[Hey, there! Golang enthusiastics. I hope you are putting effort in the Golang journey. This week we are improving the learning by using Go’s internal packages. We are using string package.
Problem Statement

Write a function that takes a string as in...]]></description><link>https://blog.rubenoalvarado.com/learn-to-capitalize-the-first-letter-of-each-word-with-go</link><guid isPermaLink="true">https://blog.rubenoalvarado.com/learn-to-capitalize-the-first-letter-of-each-word-with-go</guid><category><![CDATA[Go Language]]></category><category><![CDATA[datastructuresandalogrithm]]></category><category><![CDATA[algorithms]]></category><category><![CDATA[leetcode]]></category><category><![CDATA[leetcode-solution]]></category><dc:creator><![CDATA[Ruben O. Alvarado]]></dc:creator><pubDate>Tue, 04 Nov 2025 00:08:20 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/stock/unsplash/tozJDPvGemU/upload/3b87d6199e6a217c7ce860d4e88489d7.jpeg" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>Hey, there! Golang enthusiastics. I hope you are putting effort in the Golang journey. This week we are improving the learning by using Go’s internal packages. We are using <a target="_blank" href="https://pkg.go.dev/strings">string package</a>.</p>
<h2 id="heading-problem-statement">Problem Statement</h2>
<blockquote>
<p>Write a function that takes a string as input and returns the string with the first letter of each word capitalized. The words are separated by spaces.</p>
</blockquote>
<p>Breaking down the problem statement: we have an input—a string of words separated by spaces. We need to process each word to capitalize its first letter. Finally, our output will be the same string, but processed.</p>
<p>Now it's time to define our algorithm to process the string and obtain the requested output.</p>
<h2 id="heading-algorithm-to-solve-it">Algorithm to Solve it</h2>
<p>First, we need to split the whole string into words. This is where the string package comes to save the day—without it, we'd have to find each space in the string and split from there. Better to choose the correct tool.</p>
<pre><code class="lang-go">words := strings.Fields(s)
</code></pre>
<p>Using the strings package and its Fields method, we split our string into a slice of words separated by spaces. Easy, right? Don't forget to import the strings package.</p>
<p>Now, using a for range loop, we'll iterate through our slice of words, obtaining both the index and the word itself.</p>
<pre><code class="lang-go"><span class="hljs-keyword">for</span> i, word := <span class="hljs-keyword">range</span> words {}
</code></pre>
<p>For each string, we'll pick the first letter and replace it with the same character uppercased. To do this, we're going to use an external package called <a target="_blank" href="https://pkg.go.dev/golang.org/x/text@v0.29.0/cases">cases</a> in combination with the <a target="_blank" href="https://pkg.go.dev/golang.org/x/text@v0.29.0/language">language</a> package.</p>
<p>This line tells Go that the word variable is a string that should be titled (capitalize its first letter) in English. The result is then reassigned to the word at the current index in the words slice.</p>
<pre><code class="lang-go">words[i] = cases.Title(language.English).String(word)
</code></pre>
<p>Finally, once the entire slice has been processed, return it as a single string. Use the strings package again to join the slice elements with blank spaces between them.</p>
<pre><code class="lang-go"><span class="hljs-keyword">return</span> strings.Join(words, <span class="hljs-string">" "</span>)
</code></pre>
<p>And there you have it! You've successfully capitalized the first letter of each word in the string using the right tools.</p>
<h2 id="heading-final-thoughts">Final Thoughts</h2>
<p>As you can see, leveraging Go's built-in and external packages leads to cleaner, more maintainable code. Rather than implementing complex string manipulation from scratch, we can rely on well-tested libraries that solve common problems efficiently.</p>
<p>With just a handful of lines, Go enables us to write elegant solutions that are both readable and performant. This approach not only saves development time but also reduces the potential for bugs.</p>
<p>Don't forget to declare your modules to use the cases and language packages—they aren't built-in ones. As always, you can find the complete code in my GitHub repo: <a target="_blank" href="https://github.com/RubenOAlvarado/algorithms">https://github.com/RubenOAlvarado/algorithms</a></p>
<p>Keep learning, and I'll see you in the next one!</p>
]]></content:encoded></item><item><title><![CDATA[Why Your Side Project Remains Unfinished: Burnout Explained]]></title><description><![CDATA[We all been there—you have this revolutionary idea for a side project or startup. You start writing code, create your repo, and set up your architecture. You spend hours searching for the most cutting-edge technologies. Two or three days pass and you...]]></description><link>https://blog.rubenoalvarado.com/why-your-side-project-remains-unfinished-burnout-explained</link><guid isPermaLink="true">https://blog.rubenoalvarado.com/why-your-side-project-remains-unfinished-burnout-explained</guid><category><![CDATA[side project]]></category><category><![CDATA[burnout]]></category><category><![CDATA[clean code]]></category><dc:creator><![CDATA[Ruben O. Alvarado]]></dc:creator><pubDate>Mon, 27 Oct 2025 18:00:42 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/stock/unsplash/OXmym9cuaEY/upload/ccb006657ed5401c9ee8005d33efa724.jpeg" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>We all been there—you have this revolutionary idea for a side project or startup. You start writing code, create your repo, and set up your architecture. You spend hours searching for the most cutting-edge technologies. Two or three days pass and your initial rush of energy starts to fade. Then you start to procrastinate. You get distracted. The three hours you dedicated per day become one, until suddenly they drop to zero. And you abandon the project.</p>
<p>Then the next idea comes along and you feel that adrenaline rush again—"this time I'm going to finish this project. This one will work." But you're lying to yourself, because you said the same thing for the last three projects and none of them are completed yet.</p>
<h2 id="heading-divide-and-conquer">Divide and Conquer</h2>
<p>In Mexico, there's something called "misiles"—translated as missiles. They're huge glasses that hold around two or three liters of alcohol. Sometimes just beer, sometimes prepared beer, and sometimes a mix of different drinks.</p>
<p>Here's the thing: people try to drink it all in one go. The obvious result? They get an absurd level of alcohol in their body, getting fully drunk and even blacking out. The body can't process that much alcohol at once.</p>
<p>Wouldn't it be better to drink it in sips and enjoy the whole night? The same thing happens with side projects. People try to finish everything in a weekend, then get burned out and quit.</p>
<h2 id="heading-clear-your-path-setting-goals">Clear your path setting goals</h2>
<p>Why try to finish it all in one rush? Instead, plan and deliver part by part.</p>
<p>Set a plan before you even start coding. Define where you want to go and how you'll get there. Once you have the whole picture, you might realize your idea isn't as original as you thought, or not as easy as you thought, or even not what you thought.</p>
<p>You want to create the next Facebook? Start with the post creation flow. Once it's working and deployed, move on to user profiles. Then add photos, stories, reels, etc. You get the idea.</p>
<h2 id="heading-avoid-overengineering">Avoid Overengineering</h2>
<p>Please, please. For God's sake. YOU DON'T NEED NETFLIX ARCHITECTURE for your startup.</p>
<p>Forget about microservices, Kubernetes, and Kafka. You don't need them now.</p>
<p>Avoid complex code that builds itself from just an entity name—it only adds complexity and coupling. As I've been saying throughout this post: it's better to deliver something simple than nothing.</p>
<p>I'm not saying you should never think about scaling or that you won't need it. But not at the start, not right now.</p>
<h3 id="heading-have-you-considered-validating-your-idea-before-thinking-about-microservices">Have you considered validating your idea before thinking about microservices?</h3>
<p>Let me tell you a story:</p>
<p>Some friends and I got together with an idea for an app to break the system and be our own bosses. We started planning the architecture. I defined the backend with microservices in Node.js to ensure speed. The frontend guy proposed Flutter to compile for both iOS and Android. The infrastructure guy proposed using Gorilla and Kubernetes to keep microservices always available.</p>
<p>But do you know what the idea was? A Tinder for dogs… Yeah, I know. We were young, and at the time the idea sounded cool. But when we presented it to someone else, they looked at us like "what?"</p>
<p>Why did we need Kubernetes for something people wouldn't even use? You see my point?</p>
<h2 id="heading-is-not-about-motivation-its-about-discipline">Is not about motivation, it’s about discipline</h2>
<p>Maybe you're thinking: "What a fraud—this guy won't tell me how to get things done." But I challenge you to name more than ten people who've created something through brute force alone.</p>
<p>We all have ideas. So why can't we turn them into something tangible? Because we lose motivation along the way.</p>
<p>So how can we keep motivation? Well, the secret isn't keeping motivation—it's building discipline.</p>
<p>As Uncle Bob said: "Dedication and professionalism are more about discipline than hours." Make sure you respect your time and energy. Paraphrasing Uncle Bob again: "The worst code I wrote was the code I wrote at 3 AM."</p>
<p>This brings us back to the beginning. You tried so hard to complete that side project or SaaS idea in a brute force rush, but when motivation fades, you abandon it.</p>
<h2 id="heading-conclusion-becoming-super-saiyan">Conclusion: Becoming Super Saiyan</h2>
<p>Remember the Namek saga? Goku recovered from his battle with Vegeta and started training to join his friends on Namek.</p>
<p>His spaceship had gravity settings up to 300G. But he didn't start there—he began with 20G. Once he adapted, he moved up to 50G, and kept progressing gradually. If he had jumped straight to 300G, he would have gotten injured and failed. We'd never have seen the Super Saiyan transformation—one of the most iconic moments in anime culture.</p>
<p>So why do you keep trying to rush through a project or only work when you feel motivated? Take your time to think about it, and I'll see you in the next one.</p>
]]></content:encoded></item><item><title><![CDATA[Cracking Blackjack with Go: A Step-by-Step Guide to Your First Move]]></title><description><![CDATA[Hey there, Go enthusiasts! How's the roadmap to that desired job going? Today we're covering an interesting exercise I found on exercism.
We'll solve the first turn of a BlackJack game. In this exercise, we're covering Go fundamentals and the underes...]]></description><link>https://blog.rubenoalvarado.com/cracking-blackjack-with-go-a-step-by-step-guide-to-your-first-move</link><guid isPermaLink="true">https://blog.rubenoalvarado.com/cracking-blackjack-with-go-a-step-by-step-guide-to-your-first-move</guid><category><![CDATA[Go Language]]></category><category><![CDATA[data structures]]></category><category><![CDATA[exercism]]></category><category><![CDATA[algorithms]]></category><dc:creator><![CDATA[Ruben O. Alvarado]]></dc:creator><pubDate>Mon, 13 Oct 2025 14:00:25 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/stock/unsplash/m0EzHtexapU/upload/47d1565b65fb7ed4ab95053f8de08d39.jpeg" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>Hey there, Go enthusiasts! How's the roadmap to that desired job going? Today we're covering an interesting exercise I found on <a target="_blank" href="https://exercism.org/">exercism</a>.</p>
<p>We'll solve the first turn of a BlackJack game. In this exercise, we're covering Go fundamentals and the underestimated switch statement, which isn't used frequently—even in technical interviews.</p>
<h2 id="heading-problem-statement">Problem Statement</h2>
<p>Simulate the first turn of a <a target="_blank" href="https://en.wikipedia.org/wiki/Blackjack">BlackJack</a> game. You'll receive two cards and see the dealer's face-up card. All cards are represented as strings like "ace", "king", "two", etc.</p>
<p>The value of each card is:</p>
<div class="hn-table">
<table>
<thead>
<tr>
<td>Card</td><td>Value</td></tr>
</thead>
<tbody>
<tr>
<td>ace</td><td>11</td></tr>
<tr>
<td>two</td><td>2</td></tr>
<tr>
<td>three</td><td>3</td></tr>
<tr>
<td>four</td><td>4</td></tr>
<tr>
<td>five</td><td>5</td></tr>
<tr>
<td>six</td><td>6</td></tr>
<tr>
<td>seven</td><td>7</td></tr>
<tr>
<td>eight</td><td>8</td></tr>
<tr>
<td>nine</td><td>9</td></tr>
<tr>
<td>ten</td><td>10</td></tr>
<tr>
<td>jack</td><td>10</td></tr>
<tr>
<td>queen</td><td>10</td></tr>
<tr>
<td>king</td><td>10</td></tr>
<tr>
<td>other</td><td>0</td></tr>
</tbody>
</table>
</div><p><strong>Note:</strong> Commonly, aces can take the value of 1 or 11 but for simplicity we will assume that they can only take the value of 11.</p>
<p>Depending on your two cards and the card of the dealer, there is a strategy for the first turn of the game, in which you have the following options:</p>
<ul>
<li><p>Stand (S)</p>
</li>
<li><p>Hit (H)</p>
</li>
<li><p>Split (P)</p>
</li>
<li><p>Automatically win (W)</p>
</li>
</ul>
<p>Although not optimal yet, you will follow the strategy your friend Alex has been developing, which is as follows:</p>
<ul>
<li><p>If you have a pair of aces you must always split them.</p>
</li>
<li><p>If you have a Blackjack (two cards that sum up to a value of 21), and the dealer does not have an ace, a face card (Jack/Queen/King) or a ten then you automatically win. If the dealer does have any of those cards then you'll have to stand and wait for the reveal of the other card.</p>
</li>
<li><p>If your cards sum up to a value within the range [17, 20] you should always stand.</p>
</li>
<li><p>If your cards sum up to a value within the range [12, 16] you should always stand unless the dealer has a 7 or higher, in which case you should always hit.</p>
</li>
<li><p>If your cards sum up to 11 or lower you should always hit.</p>
</li>
</ul>
<h2 id="heading-breaking-down-the-problem">Breaking Down the Problem</h2>
<p>At first glance, the problem looks complex because there are too many constraints and scenarios. But if you break it down as we've been doing throughout this series, you'll find it's not as hard as it looks.</p>
<p>Let's start by identifying our input. We'll receive three strings with card representations: two for our cards and one for the dealer.</p>
<p>Next, we need to determine each card's value—its number representation—so we can sum them up and decide our move.</p>
<p>Finally, the desired output is the first turn move based on Alex's strategy from the problem statement.</p>
<p>This algorithm consists of two crucial steps: convert the input strings to their number representations, and determine which move corresponds to them.</p>
<h2 id="heading-parse-input-cards">Parse Input Cards</h2>
<p>The first step is converting input string cards into their number representation. While the exercism exercise focuses on learning how to work with switches, we're using maps to simplify this solution. In the next part, we'll use the switch statement as intended in the original exercise.</p>
<p>Let's define the ParseCard function using a map with string keys and int values:</p>
<pre><code class="lang-go"><span class="hljs-function"><span class="hljs-keyword">func</span> <span class="hljs-title">ParseCard</span><span class="hljs-params">(card <span class="hljs-keyword">string</span>)</span> <span class="hljs-title">int</span></span> {
    <span class="hljs-keyword">return</span> <span class="hljs-keyword">map</span>[<span class="hljs-keyword">string</span>]<span class="hljs-keyword">int</span>{
        <span class="hljs-string">"ace"</span>: <span class="hljs-number">11</span>, <span class="hljs-string">"two"</span>: <span class="hljs-number">2</span>, <span class="hljs-string">"three"</span>: <span class="hljs-number">3</span>, <span class="hljs-string">"four"</span>: <span class="hljs-number">4</span>, <span class="hljs-string">"five"</span>: <span class="hljs-number">5</span>,
        <span class="hljs-string">"six"</span>: <span class="hljs-number">6</span>, <span class="hljs-string">"seven"</span>: <span class="hljs-number">7</span>, <span class="hljs-string">"eight"</span>: <span class="hljs-number">8</span>, <span class="hljs-string">"nine"</span>: <span class="hljs-number">9</span>, <span class="hljs-string">"ten"</span>: <span class="hljs-number">10</span>,
        <span class="hljs-string">"jack"</span>: <span class="hljs-number">10</span>, <span class="hljs-string">"queen"</span>: <span class="hljs-number">10</span>, <span class="hljs-string">"king"</span>: <span class="hljs-number">10</span>,
    }[card]
}
</code></pre>
<p>And voilà! You've solved the first part in just one line. There are other approaches for this function, but I think this is the most effective way to demonstrate the use of maps.</p>
<p>For example, you can use constants if you want to impress your interviewer:</p>
<pre><code class="lang-go"><span class="hljs-keyword">const</span> (
    Ace   = <span class="hljs-string">"ace"</span>
    Two   = <span class="hljs-string">"two"</span>
    Three = <span class="hljs-string">"three"</span>
    <span class="hljs-comment">// ... another values</span>
)

<span class="hljs-keyword">var</span> cardValues = <span class="hljs-keyword">map</span>[<span class="hljs-keyword">string</span>]<span class="hljs-keyword">int</span>{
    Ace:   <span class="hljs-number">11</span>,
    Two:   <span class="hljs-number">2</span>,
    Three: <span class="hljs-number">3</span>,
    <span class="hljs-comment">// ...other values</span>
}

<span class="hljs-function"><span class="hljs-keyword">func</span> <span class="hljs-title">ParseCard</span><span class="hljs-params">(card <span class="hljs-keyword">string</span>)</span> <span class="hljs-title">int</span></span> {
    <span class="hljs-keyword">return</span> cardValues[card] <span class="hljs-comment">// default value is 0 for a int in Go</span>
}
</code></pre>
<h2 id="heading-algorithm-to-solve-the-first-turn">Algorithm to Solve the First Turn</h2>
<p>Now that we've mapped each card name to its corresponding value, we need to determine our first move.</p>
<p>We'll create a simple switch statement with the different constraints from the problem statement.</p>
<p>First, we need to parse our input cards.</p>
<pre><code class="lang-go">parsedCard1 := ParseCard(card1)
parsedCard2 := ParseCard(card2)
parsedDealerCard := ParseCard(dealerCard)
</code></pre>
<p>Now that we know how much each card is worth, we need to sum the values of our two cards to check if it's a blackjack.</p>
<pre><code class="lang-go">sumCards := parsedCard1 + parsedCard2
</code></pre>
<p>Now, with the elegance and magic of Go's syntax, let's validate each scenario to determine our first move. The first constraint is <code>if you have a pair of aces, you must split</code>—this means if our cards sum to 22 (each ace values 11), then our first turn is a split and we should return the letter <code>"P"</code>.</p>
<pre><code class="lang-go"><span class="hljs-keyword">switch</span>{
    <span class="hljs-keyword">case</span> sumCards == <span class="hljs-number">22</span>:
        <span class="hljs-keyword">return</span> <span class="hljs-string">"P"</span>
}
</code></pre>
<p>The second constraint: if you have a Blackjack (21) and the dealer doesn't have an ace, face card (Jack/Queen/King), or ten, you automatically win. In other words, if you have 21 and the dealer's card is less than 10, you win.</p>
<pre><code class="lang-go"><span class="hljs-keyword">case</span> sumCards == <span class="hljs-number">21</span> &amp;&amp; parsedDealerCard &lt; <span class="hljs-number">10</span>:
    <span class="hljs-keyword">return</span> <span class="hljs-string">"W"</span>
</code></pre>
<p>However, if you have 21 and the dealer has any of these cards (an ace or a face card), you must stand this turn.</p>
<pre><code class="lang-go"><span class="hljs-keyword">case</span> sumCards == <span class="hljs-number">21</span> &amp;&amp; parsedDealerCard &gt;= <span class="hljs-number">10</span>:
    <span class="hljs-keyword">return</span> <span class="hljs-string">"S"</span>
</code></pre>
<p>Next, if your cards sum to a value within the range [17, 20], you should always stand.</p>
<pre><code class="lang-go"><span class="hljs-keyword">case</span> sumCards &gt;= <span class="hljs-number">17</span> &amp;&amp; sumCards &lt;= <span class="hljs-number">20</span>:
    <span class="hljs-keyword">return</span> <span class="hljs-string">"S"</span>
</code></pre>
<p>If your cards sum to a value between 12 and 16, you should always stand—unless the dealer has a 7 or higher, in which case you should hit.</p>
<p>The first condition looks like this:</p>
<pre><code class="lang-go"><span class="hljs-keyword">case</span> sumCards &gt;= <span class="hljs-number">12</span> &amp;&amp; sumCards &lt;= <span class="hljs-number">16</span> &amp;&amp; parsedDealerCard &gt;= <span class="hljs-number">7</span>: <span class="hljs-comment">//dealers card equal or higher than 7</span>
    <span class="hljs-keyword">return</span> <span class="hljs-string">"H"</span>
</code></pre>
<p>The next condition handles when the dealer's card is less than 7:</p>
<pre><code class="lang-go"><span class="hljs-keyword">case</span> sumCards &gt;= <span class="hljs-number">12</span> &amp;&amp; sumCards &lt;= <span class="hljs-number">16</span> &amp;&amp; parsedDealerCard &lt; <span class="hljs-number">7</span>:
    <span class="hljs-keyword">return</span> <span class="hljs-string">"S"</span>
</code></pre>
<p>If your cards sum to 11 or lower, you should always hit. This means any uncovered scenario equals a hit, since we've covered all possible scenarios. So our default is <code>"H"</code>.</p>
<pre><code class="lang-go"><span class="hljs-keyword">default</span>:
    <span class="hljs-keyword">return</span> <span class="hljs-string">"H"</span>
</code></pre>
<p>And voilà! You've created an algorithm to calculate the first turn in a Blackjack game. You've also learned about maps, switch statements, and conditionals.</p>
<h2 id="heading-final-thoughts">Final Thoughts</h2>
<p>This exercise demonstrates how breaking down complex problems into smaller, manageable steps makes them much easier to solve. What initially seemed like a complicated set of rules turned into a straightforward algorithm by identifying the key components: parsing card values and evaluating conditions systematically.</p>
<p>The switch statement in Go proves to be incredibly powerful for handling multiple conditional branches in a clean, readable way. Combined with maps for value lookup, we created an elegant solution.</p>
<p>As you continue your Go journey, remember that most real-world problems can be tackled the same way—break them down, identify patterns, and leverage Go's simple yet powerful features.</p>
<p>Keep practicing, keep coding, and most importantly—have fun with it! If you enjoyed this exercise, explore more challenges on <a target="_blank" href="https://exercism.org/">exercism</a> to continue building your Go skills. As always, you can find the complete code in my GitHub repo: <a target="_blank" href="https://github.com/RubenOAlvarado/algorithms">https://github.com/RubenOAlvarado/algorithms</a></p>
<p>Happy coding and see you in the next one!</p>
]]></content:encoded></item><item><title><![CDATA[Unlocking Uniqueness: Mastering the Unique Character Algorithm in Go]]></title><description><![CDATA[Hello, Go enthusiast! Today we're covering a new algorithm in Go.
This is a commonly asked question for entry-level positions as it covers Go basics like maps, runes, and string manipulation. We'll explore how to determine if all characters in a stri...]]></description><link>https://blog.rubenoalvarado.com/unlocking-uniqueness-mastering-the-unique-character-algorithm-in-go</link><guid isPermaLink="true">https://blog.rubenoalvarado.com/unlocking-uniqueness-mastering-the-unique-character-algorithm-in-go</guid><category><![CDATA[Go Language]]></category><category><![CDATA[data structures]]></category><category><![CDATA[algorithms]]></category><category><![CDATA[Algorithms Data Structures ]]></category><category><![CDATA[leetcode-solution]]></category><dc:creator><![CDATA[Ruben O. Alvarado]]></dc:creator><pubDate>Mon, 06 Oct 2025 15:25:45 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/stock/unsplash/VyD_UzTDm9o/upload/cb64142dc7ea67c8960c88e748da2972.jpeg" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>Hello, Go enthusiast! Today we're covering a new algorithm in Go.</p>
<p>This is a commonly asked question for entry-level positions as it covers Go basics like maps, runes, and string manipulation. We'll explore how to determine if all characters in a string are unique.</p>
<h2 id="heading-problem-statement">Problem Statement</h2>
<p>As we have been doing, let's start by understanding the problem statement.</p>
<blockquote>
<p>Implement an algorithm to determine if a string contains only unique characters.</p>
</blockquote>
<p>Breaking down the problem statement, we have a string as input, we need to process each character in the string to determine if any are repeated, and finally return a boolean as output.</p>
<p>Now that we've established our input, process, and output, let's define our algorithm to solve it.</p>
<h2 id="heading-algorithm-to-solve-it">Algorithm to Solve it</h2>
<p>The first step is to initialize a data structure to contain each character and track its occurrences. In Go, we have maps for this purpose. Using the <a target="_blank" href="https://www.codingexplorations.com/blog/understanding-the-make-function-in-go">make built-in function</a>, let's declare our set of characters.</p>
<p>When used for maps, this function expects just one argument: the type for the map. Here, we're declaring a map of runes with bool values to keep track of each character's occurrence.</p>
<pre><code class="lang-go">charMap := <span class="hljs-built_in">make</span>(<span class="hljs-keyword">map</span>[<span class="hljs-keyword">rune</span>]<span class="hljs-keyword">bool</span>)
</code></pre>
<p>Next, utilizing Go's elegant for-range loop syntax, we iterate through each character in the string.</p>
<pre><code class="lang-go"><span class="hljs-keyword">for</span> _, c := <span class="hljs-keyword">range</span> s {} <span class="hljs-comment">//s is the input string</span>
</code></pre>
<p>Here's where the magic happens: if c is already in charMap, we return false because this character has appeared previously in the string.</p>
<pre><code class="lang-go"><span class="hljs-keyword">if</span> charMap[c] {
    <span class="hljs-keyword">return</span> <span class="hljs-literal">false</span>
}
</code></pre>
<p>If the character isn't in the charMap yet, we add it to track it for future iterations.</p>
<pre><code class="lang-go">charMap[c] = <span class="hljs-literal">true</span>
</code></pre>
<p>Finally, if the loop completes without finding any repetition, it means every character is unique, so we return true.</p>
<pre><code class="lang-go"><span class="hljs-keyword">return</span> <span class="hljs-literal">true</span>
</code></pre>
<p>And voilà! We've solved the unique character algorithm. Here are some test cases you can use to verify the solution:</p>
<ul>
<li><p><code>abcdef</code> → returns <code>true</code> because it contains no repeated characters.</p>
</li>
<li><p><code>hello</code> → returns <code>false</code> because it contains a repeated letter <code>l</code></p>
</li>
</ul>
<h2 id="heading-final-thoughts">Final Thoughts</h2>
<p>We are gradually increasing the difficulty of algorithms in this series. As I've been emphasizing throughout, you must strengthen your fundamentals before tackling more complex challenges. There's a saying: "Learn to walk before you run."</p>
<p>So, keep practicing and remember me when you land that desired job. As usual, you can find this and other algorithms in Go and TypeScript in my algorithms GitHub repo: <a target="_blank" href="https://github.com/RubenOAlvarado/algorithms">https://github.com/RubenOAlvarado/algorithms</a></p>
<p>Until the next one!</p>
]]></content:encoded></item><item><title><![CDATA[Sum of Digits in Go: A Simple Algorithm Tutorial]]></title><description><![CDATA[Hello, Go enthusiast! We're continuing our roadmap toward landing that dream job. Today we're covering another simple algorithm to help you practice working with data types and basic looping in Go.
Join me as we solve the classic Sum Digits algorithm...]]></description><link>https://blog.rubenoalvarado.com/sum-of-digits-in-go-a-simple-algorithm-tutorial</link><guid isPermaLink="true">https://blog.rubenoalvarado.com/sum-of-digits-in-go-a-simple-algorithm-tutorial</guid><category><![CDATA[data structures]]></category><category><![CDATA[algorithms]]></category><category><![CDATA[data structure and algorithms ]]></category><category><![CDATA[Algorithms Data Structures ]]></category><category><![CDATA[Go Language]]></category><category><![CDATA[golang]]></category><dc:creator><![CDATA[Ruben O. Alvarado]]></dc:creator><pubDate>Mon, 29 Sep 2025 14:00:19 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1758999907458/04bcc4fb-a68c-4044-b0f7-55854d6e9754.jpeg" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>Hello, Go enthusiast! We're continuing our roadmap toward landing that dream job. Today we're covering another simple algorithm to help you practice working with data types and basic looping in Go.</p>
<p>Join me as we solve the classic Sum Digits algorithm and land that dreamed job.</p>
<h3 id="heading-problem-statement">Problem Statement</h3>
<blockquote>
<p>Given an integer, return the sum of its digits. For example, if the input is <code>123</code> the output should be <code>6</code> (1+2+3).</p>
</blockquote>
<p>Let's break down the problem statement: we have an integer as input, we need to process each of its digits, and return an integer as output.</p>
<p>Now that we've established our input, process, and output, let's define our algorithm to solve it.</p>
<h3 id="heading-algorithm-to-solve-it">Algorithm to Solve It</h3>
<p>First, we need to check if our input is negative. If it is, we'll convert it to a positive value.</p>
<pre><code class="lang-go"><span class="hljs-keyword">if</span> n &lt; <span class="hljs-number">0</span> {
    n = -n
}
</code></pre>
<p>Initialize a variable <code>sum</code> to <code>0</code> to track our running total</p>
<pre><code class="lang-go">sum := <span class="hljs-number">0</span>
</code></pre>
<p>Now, implement a loop that continues as long as <code>n</code> is not zero. In Go, this for loop works like a while loop, checking if <code>n</code> is greater than <code>0</code></p>
<pre><code class="lang-go"><span class="hljs-keyword">for</span> n != <span class="hljs-number">0</span> {}
</code></pre>
<p>For each iteration, add the last digit of the number to the <code>sum</code> variable using the modulo operator.</p>
<pre><code class="lang-go">sum += n % <span class="hljs-number">10</span>
</code></pre>
<p>Then, use the division assignment operator to remove the last digit from the number.</p>
<pre><code class="lang-go">n /= <span class="hljs-number">10</span>
</code></pre>
<p>Finally, return the accumulated sum.</p>
<pre><code class="lang-go"><span class="hljs-keyword">return</span> sum
</code></pre>
<h3 id="heading-complete-function-implementation">Complete Function Implementation</h3>
<pre><code class="lang-go"><span class="hljs-function"><span class="hljs-keyword">func</span> <span class="hljs-title">sumDigits</span><span class="hljs-params">(n <span class="hljs-keyword">int</span>)</span> <span class="hljs-title">int</span></span> {
    <span class="hljs-keyword">if</span> n &lt; <span class="hljs-number">0</span> {
        n = -n
    }
    sum := <span class="hljs-number">0</span>
    <span class="hljs-keyword">for</span> n != <span class="hljs-number">0</span> {
        sum += n % <span class="hljs-number">10</span>
        n /= <span class="hljs-number">10</span>
    }
    <span class="hljs-keyword">return</span> sum
}
</code></pre>
<h2 id="heading-final-thoughts">Final Thoughts</h2>
<p>Go is a beautiful language. This simple yet efficient function demonstrates the language's minimalist mindset. With the rapidly growing demand for Go developers, strengthening your fundamentals is essential to landing that desired job.</p>
<p>Remember, keep learning. Improvement is a marathon, not a sprint. As always, you can find the code for this and other examples in my GitHub repository: <a target="_blank" href="https://github.com/RubenOAlvarado/algorithms">https://github.com/RubenOAlvarado/algorithms</a></p>
<blockquote>
<p>Cover photo belongs to <a target="_blank" href="https://unsplash.com/es/@bekkybekks?utm_content=creditCopyText&amp;utm_medium=referral&amp;utm_source=unsplash">Bekky Bekks</a> in <a target="_blank" href="https://unsplash.com/es/fotos/un-primer-plano-de-un-letrero-blanco-con-letras-verdes-q3MxHh3kF7U?utm_content=creditCopyText&amp;utm_medium=referral&amp;utm_source=unsplash">Unsplash</a></p>
</blockquote>
]]></content:encoded></item><item><title><![CDATA[Sum of Natural Numbers — A First Step into Algorithms in Go]]></title><description><![CDATA[Photo belongs to Susan Holt Simpson in Unsplash
Throughout my technical interview journey, I’ve observed a shortage of Go-based Data Structures and Algorithms (DSA) examples. As Go has become increasingly in-demand and I’ve been studying it extensive...]]></description><link>https://blog.rubenoalvarado.com/sum-of-natural-numbers-a-first-step-into-algorithms-in-go-1da0d1e3a080</link><guid isPermaLink="true">https://blog.rubenoalvarado.com/sum-of-natural-numbers-a-first-step-into-algorithms-in-go-1da0d1e3a080</guid><category><![CDATA[Go Language]]></category><category><![CDATA[data structures]]></category><category><![CDATA[algorithms]]></category><category><![CDATA[Technical interview]]></category><dc:creator><![CDATA[Ruben O. Alvarado]]></dc:creator><pubDate>Mon, 22 Sep 2025 14:31:45 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1758815999575/fefa9420-979d-4ea8-9260-69e2015a8cd8.jpeg" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>Photo belongs to <a target="_blank" href="https://unsplash.com/es/@shs521?utm_content=creditCopyText&amp;utm_medium=referral&amp;utm_source=unsplash">Susan Holt Simpson</a> in <a target="_blank" href="https://unsplash.com/es/fotos/bloques-de-juguete-de-madera-marron-GQ327RPuxhI?utm_content=creditCopyText&amp;utm_medium=referral&amp;utm_source=unsplash">Unsplash</a></p>
<p>Throughout my technical interview journey, I’ve observed a shortage of Go-based Data Structures and Algorithms (DSA) examples. As Go has become increasingly in-demand and I’ve been studying it extensively, I’ve decided to transition my DSA series from JavaScript/TypeScript to Go. The elegant syntax of Go makes this transition exciting — it feels like exploring a whole new world.</p>
<p>I’ll start with a super basic algorithm to warm up: The Sum of Natural Numbers. Join me as we explore this simple yet effective algorithm.</p>
<blockquote>
<p><em>Disclaimer: This post assumes you have basic knowledge of Go and are preparing for job interviews.</em></p>
</blockquote>
<h3 id="heading-problem-statement">Problem Statement</h3>
<blockquote>
<p><em>Given a positive integer n return the sum of all natural numbers from 1 to n .</em></p>
</blockquote>
<p>Breaking down the problem statement, we have: an input (a positive integer), the required logic (sum all natural numbers), and an output (the resulting integer from the sum). Let’s use this structure to define our algorithm.</p>
<h3 id="heading-how-to-solve-it">How to Solve it</h3>
<p>If you’ve read my previous posts about DSA, you know I prefer a straightforward approach: explaining the problem statement first, then the algorithm to solve it, and finally the implementation.</p>
<p>Now, let’s continue. The first step is to handle the input. We need to validate if it’s a positive number since this is a constraint in the problem statement. This is a basic validation: if the input number (<code>n</code>) is less than <code>0</code>, it means it's not positive, so we return 0.</p>
<pre><code class="lang-go"><span class="hljs-keyword">if</span> n &lt; <span class="hljs-number">0</span> {
    <span class="hljs-keyword">return</span> <span class="hljs-number">0</span>
}
</code></pre>
<p>Now, declare a <code>sum</code> variable where we'll accumulate the value of every number.</p>
<pre><code class="lang-go">sum := <span class="hljs-number">0</span>
</code></pre>
<p>Thanks to the elegance of Go, we can create a loop using the range syntax. When we declare a variable i that iterates through the range of <code>n</code>, we're creating a loop that runs from <code>0</code> to <code>n-1</code>.</p>
<pre><code class="lang-go"><span class="hljs-keyword">for</span> i := <span class="hljs-keyword">range</span> n {}
</code></pre>
<p>Go is such a beautiful language. It’s important to note that this syntax only works with Go 1.22 or newer. With older versions, you’ll need to use a conventional for loop instead.</p>
<pre><code class="lang-go"><span class="hljs-keyword">for</span> i := <span class="hljs-number">0</span>; i &lt; n; i++ {}
</code></pre>
<p>Next, add the value of the current iteration plus <code>1</code> to our <code>sum</code> variable, since our loop starts from <code>0</code>.</p>
<pre><code class="lang-go">sum += i + <span class="hljs-number">1</span>
</code></pre>
<p>Once the loop concludes, you simply return the accumulated sum.</p>
<pre><code class="lang-go"><span class="hljs-keyword">return</span> sum;
</code></pre>
<h3 id="heading-complete-implementation">Complete Implementation</h3>
<p>The complete implementation of our solution for summing natural numbers is presented below. When reviewing this implementation, notice how concise yet readable the Go syntax is:</p>
<pre><code class="lang-go"><span class="hljs-function"><span class="hljs-keyword">func</span> <span class="hljs-title">sumNaturalNumbers</span><span class="hljs-params">(n <span class="hljs-keyword">int</span>)</span> <span class="hljs-title">int</span></span> {
    <span class="hljs-keyword">if</span> n &lt; <span class="hljs-number">0</span> {
        <span class="hljs-keyword">return</span> <span class="hljs-number">0</span>
    }
    sum := <span class="hljs-number">0</span>
    <span class="hljs-keyword">for</span> i := <span class="hljs-keyword">range</span> n {
        sum += i + <span class="hljs-number">1</span>
    }
    <span class="hljs-keyword">return</span> sum
}
</code></pre>
<p>And voila! You’ve just completed your first technical interview question using Go. While we haven’t covered any data structures yet, this example serves as an excellent starting point for your Go DSA journey.</p>
<h3 id="heading-final-thoughts">Final Thoughts</h3>
<p>While this algorithm is simple, it effectively demonstrates Go’s capabilities as a programming language. The elegant syntax and performance characteristics make Go particularly attractive for technical interviews and real-world applications.</p>
<p>There’s a saying in the arts: “you need to know the rules to break them.” Similarly, to excel in technical interviews, you need strong fundamentals. The best approach combines a clear starting point (like this basic algorithm), a solid plan for tackling more complex problems, and consistent discipline in practice. I hope this example helps you in your next technical interview and assists you in landing your desired job.</p>
<p>You can find the code for this and other algorithms in my GitHub repository: <a target="_blank" href="https://github.com/RubenOAlvarado/algorithms">https://github.com/RubenOAlvarado/algorithms</a></p>
<p>Keep learning, and I’ll see you in the next one!</p>
]]></content:encoded></item><item><title><![CDATA[Advanced Filtering with Nestjs: The Easy Way]]></title><description><![CDATA[Photo belongs to Luca Bravo in Unsplash
When building an API, you often need to handle complex query parameters. If you’re just coding casually, this might not be a concern, but when building a real-world solution, pagination, filtering, and sorting ...]]></description><link>https://blog.rubenoalvarado.com/advanced-filtering-with-nestjs-the-easy-way-53f717150b9f</link><guid isPermaLink="true">https://blog.rubenoalvarado.com/advanced-filtering-with-nestjs-the-easy-way-53f717150b9f</guid><category><![CDATA[TypeScript]]></category><category><![CDATA[nestjs]]></category><category><![CDATA[REST API]]></category><category><![CDATA[Backend Development]]></category><dc:creator><![CDATA[Ruben O. Alvarado]]></dc:creator><pubDate>Mon, 15 Sep 2025 17:10:13 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1758816009567/d0cb2c89-8bfa-4fa8-8683-b144956929d1.jpeg" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>Photo belongs to <a target="_blank" href="https://unsplash.com/es/@lucabravo?utm_content=creditCopyText&amp;utm_medium=referral&amp;utm_source=unsplash">Luca Bravo</a> in <a target="_blank" href="https://unsplash.com/es/fotos/computadora-portatil-gris-encendida-XJXWbfSo2f0?utm_content=creditCopyText&amp;utm_medium=referral&amp;utm_source=unsplash">Unsplash</a></p>
<p>When building an API, you often need to handle complex query parameters. If you’re just coding casually, this might not be a concern, but when building a real-world solution, pagination, filtering, and sorting are essential for creating a robust and scalable API.</p>
<p>In my current project with NestJs, I faced this challenge. Initially, I thought, “Easy, I just need to write the DTOs” — but it wasn’t that simple. Today, I’m going to show you how to implement complex filtering in a NestJs endpoint.</p>
<h3 id="heading-nestexpressapplication">NestExpressApplication</h3>
<p>First, we need to create a new Nest project. If you’ve already installed the <a target="_blank" href="https://docs.nestjs.com/cli/overview">CLI</a>, this is a simple step. If not, I highly recommend installing it.</p>
<pre><code class="lang-bash">nest new complex-query-filters
</code></pre>
<p>Since we’ll need to validate and transform our DTOs, let’s install class-validator and class-transformer packages.</p>
<pre><code class="lang-bash">npm i class-validator class-transformer
</code></pre>
<p>There you have it — a minimal NestJs API. However, to handle complex queries, we need to make a small change in our project: declaring the app as a <code>NestExpressApplication</code>. You might ask, "Isn't it an Express app by definition?" And you're right, but explicitly declaring the app type gives us access to Express-specific utilities.</p>
<pre><code class="lang-typescript"><span class="hljs-keyword">const</span> app = <span class="hljs-keyword">await</span> NestFactory.create&lt;NestExpressApplication&gt;(AppModule);
</code></pre>
<p>Now, we can define the query parser of our application, letting Nest know that our application is going to handle complex query parameters.</p>
<pre><code class="lang-typescript">app.set(<span class="hljs-string">'query parser'</span>, <span class="hljs-string">'extended'</span>);
</code></pre>
<h3 id="heading-validations-a-pragmatic-programer-always-include-validations">Validations, A Pragmatic Programer Always Include Validations</h3>
<p>That’s it! Now your Nest app handles complex queries like: <code>dateRange[lte]=2023-10-26T10:00:00.000Z&amp;search=something</code>. But what happens if someone sends a SQL injection or something that could crash your app? As software engineers, we need to ensure we're building robust applications.</p>
<p>To accomplish this, we’ll follow a simple structure by creating DTOs that tell our server which properties we want to receive. Let’s start with the search fields. Create a new file with a class called <code>SearchFieldsDto</code> that will define the valid properties clients can search by. I'll keep it simple by declaring just two properties.</p>
<pre><code class="lang-tsx">export class SearchFieldsDto {
  @IsOptional()
  @IsString()
  @IsAlphanumeric()
  @MinLength(2)
  @MaxLength(30)
  category?: string;

  @IsOptional()
  @IsString()
  @IsAlphanumeric()
  @MinLength(2)
  @MaxLength(20)
  status?: string;
}
</code></pre>
<p>For a more detailed look at the validations we’re using, I highly recommend checking the <a target="_blank" href="https://www.npmjs.com/package/class-validator">class-validator docs</a>. Now, let’s build our FiltersDto.</p>
<h3 id="heading-building-the-filtersdto">Building the FiltersDto</h3>
<p>To keep this post concise, I’ll add some simple filters to demonstrate the approach. Let’s create our FiltersDto class with three properties: status, category, and dateRange. We’ll also create another class for the operators that can filter by date range.</p>
<pre><code class="lang-tsx">export class DateRangeDto {
  @IsOptional()
  @IsDateString()
  gte?: Date;

  @IsOptional()
  @IsDateString()
  lte?: Date;
}

export class FiltersDto {
  @IsOptional()
  @IsEnum(['active', 'inactive', 'pending'], {
    message: 'Status must be one of: active, inactive, pending',
  })
  @IsString()
  status?: string;

  @IsOptional()
  @IsString()
  @IsEnum(['electronics', 'furniture', 'clothing'], {
    message: 'Category must be one of: electronics, furniture, clothing',
  })
  category?: string;

  @IsOptional()
  @IsObject()
  dateRange?: DateRangeDto;
}
</code></pre>
<p>With this structure, we’re telling our Nest application that it can handle requests with nested attributes, such as: <code>dateRange[lte]=2023-10-26T10:00:00.000Z</code>.</p>
<h3 id="heading-the-querydto-class">The QueryDto Class</h3>
<p>Finally, let’s combine everything into a single <code>QueryDto class</code>. We'll add <code>page</code> and <code>limit</code> attributes, plus a <code>sort</code> property that specifies which fields we can sort by and in which direction. First, let's create the <code>SortFieldsDto</code>.</p>
<pre><code class="lang-tsx">export class SortFieldsDto {
  @IsOptional()
  @IsString()
  @IsIn(['asc', 'desc'])
  category?: 'asc' | 'desc';
}
</code></pre>
<p>Now when someone sends the sort parameter, it can only sort by category and only accept the values “asc” or “desc” — something like this: <code>sort[category]=asc</code>. Let's combine everything into our <code>QueryDto</code> class, which will extend our <code>FiltersDto</code>.</p>
<pre><code class="lang-tsx">export class QueryDto extends FiltersDto {
  @IsOptional()
  @IsObject()
  @ValidateNested()
  @Type(() =&gt; SearchFieldsDto)
  search?: SearchFieldsDto;

  @IsOptional()
  @IsInt()
  page?: number;

  @IsOptional()
  @IsInt()
  limit?: number;

  @IsOptional()
  @IsObject()
  @ValidateNested()
  @Type(() =&gt; SortFieldsDto)
  sort?: SortFieldsDto;
}
</code></pre>
<p>We could separate everything into its own DTO and group them with the <a target="_blank" href="http://docs.nestjs.com/openapi/mapped-types#intersection">Intersection</a> utility, but I think this approach better demonstrates how to structure the DTO visually. So there you have it — your API is now validated and prevents SQL or RSQL injections… or does it? Well, not yet.</p>
<h3 id="heading-validationpipe-comes-to-the-rescue">ValidationPipe Comes to the Rescue</h3>
<p>If you send a request like <code>dateRange[lt]=today&amp;search[magumbos]=something</code> with the current project setup, NestJS will accept it as valid because we haven't explicitly defined our validation and transformation rules yet. To fix this, let's go to the <code>main.ts</code> file and add the <code>useGlobalPipes</code> method before the <code>app.listen</code> line.</p>
<pre><code class="lang-typescript">app.useGlobalPipes();
</code></pre>
<p>This method requires a <code>ValidationPipe</code> instance to function. The validation instance accepts an object containing key-value pairs that define our validation and transformation rules for the entire project. You can configure these rules at different levels (per module, controller, etc.), but that's a topic for another post.</p>
<pre><code class="lang-tsx">new ValidationPipe({
    whitelist: true,
  transform: true,
  forbidNonWhitelisted: true,
  transformOptions: { enableImplicitConversion: true },
}),
</code></pre>
<p>With this configuration, we’re instructing our validation pipe that all properties should be whitelisted, transformed, and any non-whitelisted properties should be forbidden. We’re also enabling implicit object conversion. As a result, when you send a request like <code>dateRange[lt]=today</code>, you'll receive a bad request response indicating that the property <code>lt</code> should not be present.</p>
<p>If you send this request: <code>http://localhost:3000/?dateRange[lte]=2023-10-26T10:00:00.000Z&amp;search[status]=so&amp;page=1&amp;limit=10&amp;sort[category]=asc</code>, you'll get this result:</p>
<p>Hello World! Query: <code>{"dateRange":{"lte":"2023-10-26T10:00:00.000Z"},"search":{"status":"so"},"page":1,"limit":10,"sort":{"category":"asc"}}</code></p>
<h3 id="heading-final-thoughts">Final Thoughts</h3>
<p>With this simple example, I’ve demonstrated the importance of being a software developer rather than relying entirely on AI tools. I spent several minutes asking ChatGPT, Claude, and DeepSeek how to handle this type of query in NestJS.</p>
<p>They all suggested complex solutions and approaches, when I just needed to read the documentation to realize it was a one-line change. The lesson here is that while it’s great to use new tools to help solve problems, there’s always a need to develop solutions on your own.</p>
<p>Keep learning, and I’ll see you in the next one. You can find all the code for this example in the following GitHub repository: <a target="_blank" href="https://github.com/RubenOAlvarado/complex-query-filters">https://github.com/RubenOAlvarado/complex-query-filters</a></p>
]]></content:encoded></item><item><title><![CDATA[The Queue: Understanding FIFO Data Structures in TypeScript]]></title><description><![CDATA[Photo belongs to Xiangkun ZHU in Unsplash
Have you ever waited in line for an artist’s autograph? If so, you know what I’m talking about. You wake up early in the morning to be first in line and get your favorite record, poster, or book signed.
Well,...]]></description><link>https://blog.rubenoalvarado.com/the-queue-understanding-fifo-data-structures-in-typescript-64da98c675d1</link><guid isPermaLink="true">https://blog.rubenoalvarado.com/the-queue-understanding-fifo-data-structures-in-typescript-64da98c675d1</guid><category><![CDATA[data structures]]></category><category><![CDATA[TypeScript]]></category><category><![CDATA[TypeScript Generics]]></category><category><![CDATA[algorithms]]></category><dc:creator><![CDATA[Ruben O. Alvarado]]></dc:creator><pubDate>Mon, 08 Sep 2025 14:43:39 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1758816011705/7aefaa9e-5cd0-46e6-9d28-42b1463b216f.jpeg" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>Photo belongs to <a target="_blank" href="https://unsplash.com/es/@arttoinspire?utm_content=creditCopyText&amp;utm_medium=referral&amp;utm_source=unsplash">Xiangkun ZHU</a> in <a target="_blank" href="https://unsplash.com/es/fotos/un-grupo-de-personas-de-pie-en-una-acera-U0QaV_H8-R4?utm_content=creditCopyText&amp;utm_medium=referral&amp;utm_source=unsplash">Unsplash</a></p>
<p>Have you ever waited in line for an artist’s autograph? If so, you know what I’m talking about. You wake up early in the morning to be first in line and get your favorite record, poster, or book signed.</p>
<p>Well, that’s FIFO in action. And the data structure we’re going to review this week follows this principle. We are learning how to implement Queues.</p>
<h3 id="heading-first-in-first-out">First In First Out</h3>
<p>Queues implement FIFO (First In First Out) ordering. This means items are removed from the queue in the same order that they are added.</p>
<p>Unlike the stack data structure, queue ordering works like waiting in line to meet your favorite idol. The position you get in line is the position in which you’ll get to shake those famous hands.</p>
<h3 id="heading-hold-the-line">Hold the Line</h3>
<p>This week we are going to implement a Queue. Like a stack, it can be implemented with a linked list, as they are essentially the same structure — just with items added and removed from opposite sides.</p>
<p>We’ll reuse the Node class we created earlier in the stack post:</p>
<pre><code class="lang-tsx">export class Node&lt;T&gt; {
    value: T;
    next: Node&lt;T&gt; | null;

    constructor(value: T) {
        this.value = value;
        this.next = null;
    }
}
</code></pre>
<p>This Node class will store each item in the Queue, holding the actual value along with a reference to the next item.</p>
<p>Now for our Queue class, we’ll follow the same approach, taking advantage of TypeScript Generics. Unlike a stack, however, we’ll keep track of both the first and last items in our queue.</p>
<pre><code class="lang-tsx">export class Queue&lt;T&gt; {
    first: Node&lt;T&gt; | null;
    last: Node&lt;T&gt; | null;
    size: number;
}
</code></pre>
<p>In our constructor, we need to initialize the first and last node references. This ensures that each time a new Queue is instantiated, we have default values for our first and last items in the Queue.</p>
<pre><code class="lang-tsx">constructor(value: T) {
  this.first = new Node(value);
  this.last = this.first;
  this.size = 1;
}
</code></pre>
<h3 id="heading-enqueueing-an-item">Enqueueing an Item</h3>
<p>The enqueue operation adds an item to the end of the queue. The first step is to create a new node.</p>
<pre><code class="lang-typescript"><span class="hljs-keyword">const</span> newNode = <span class="hljs-keyword">new</span> Node(value);
</code></pre>
<p>Since this new node will become the last item in the queue (as it’s the newest to join), we need to check if the last variable is not null. If it has a value, we connect its next pointer to this new node.</p>
<pre><code class="lang-typescript"><span class="hljs-keyword">if</span>(<span class="hljs-built_in">this</span>.last !== <span class="hljs-literal">null</span>) <span class="hljs-built_in">this</span>.last.next = newNode;
</code></pre>
<p>Next, we update the last pointer to reference our newly created node.</p>
<pre><code class="lang-typescript"><span class="hljs-built_in">this</span>.last = newNode;
</code></pre>
<p>We also need to ensure that the first variable has a value. If it’s null, it means this new node is the first element in the queue.</p>
<pre><code class="lang-typescript"><span class="hljs-keyword">if</span>(<span class="hljs-built_in">this</span>.first === <span class="hljs-literal">null</span>) <span class="hljs-built_in">this</span>.first = <span class="hljs-built_in">this</span>.last;
</code></pre>
<p>Finally, we increment the queue size. And voila! Our queue can now enqueue new items.</p>
<h3 id="heading-dequeueing-an-item">Dequeueing an Item</h3>
<p>This operation removes the first item in the queue. The first step is to verify that the first variable is not null. If it is null, we simply return null because there are no items in the queue.</p>
<pre><code class="lang-typescript"><span class="hljs-keyword">if</span>(<span class="hljs-built_in">this</span>.first === <span class="hljs-literal">null</span>) <span class="hljs-keyword">return</span> <span class="hljs-literal">null</span>;
</code></pre>
<p>Now that we’ve verified the first variable has a value, we assign this value to a new constant called nodeToDequeue to keep track of the node we’ll remove.</p>
<pre><code class="lang-typescript"><span class="hljs-keyword">const</span> nodeToDequeue = <span class="hljs-built_in">this</span>.first;
</code></pre>
<p>Next, we need to reassign the first variable to point to the next item (node) in the queue, as this will become our new first element.</p>
<pre><code class="lang-typescript"><span class="hljs-built_in">this</span>.first = <span class="hljs-built_in">this</span>.first.next;
</code></pre>
<p>Next, we need to check if there are any nodes left in the queue. If the first pointer is now null, it means our queue is empty and we must also clear the last pointer.</p>
<pre><code class="lang-typescript"><span class="hljs-keyword">if</span>(<span class="hljs-built_in">this</span>.first === <span class="hljs-literal">null</span>) <span class="hljs-built_in">this</span>.last = <span class="hljs-literal">null</span>;
</code></pre>
<p>Finally, we decrement the queue size and return the value of the removed node.</p>
<pre><code class="lang-typescript"><span class="hljs-built_in">this</span>.size--;
<span class="hljs-keyword">return</span> nodeToDequeue.value;
</code></pre>
<p>And voila! Our queue now has the capability to dequeue its elements. Simple, isn’t it?</p>
<h3 id="heading-peeking-the-top">Peeking the Top</h3>
<p>This operation returns the first item in the queue while ensuring it has a value. It’s straightforward since we’ve already created our first variable — we simply return its value if it exists, or null if it doesn’t.</p>
<pre><code class="lang-typescript"><span class="hljs-keyword">return</span> <span class="hljs-built_in">this</span>.first ? <span class="hljs-built_in">this</span>.first.value : <span class="hljs-literal">null</span>;
</code></pre>
<p>As you can see, we resolved this with an elegant one-liner. This simple operation allows us to peek at the first item in our queue without removing it.</p>
<h3 id="heading-is-the-queue-empty">Is the Queue Empty?</h3>
<p>This operation checks if our queue is empty by examining its size. If the size equals 0, it means there are no items in our queue, indicating it’s empty. The method simply returns this evaluation.</p>
<pre><code class="lang-typescript"><span class="hljs-keyword">return</span> <span class="hljs-built_in">this</span>.size === <span class="hljs-number">0</span>;
</code></pre>
<h3 id="heading-complete-typescript-implementation">Complete Typescript Implementation</h3>
<pre><code class="lang-typescript"><span class="hljs-keyword">export</span> <span class="hljs-keyword">class</span> Queue&lt;T&gt; {
    first: Node&lt;T&gt; | <span class="hljs-literal">null</span>;
    last: Node&lt;T&gt; | <span class="hljs-literal">null</span>;
    size: <span class="hljs-built_in">number</span>;

    <span class="hljs-keyword">constructor</span>(<span class="hljs-params">value: T</span>) {
        <span class="hljs-built_in">this</span>.first = <span class="hljs-keyword">new</span> Node(value);
        <span class="hljs-built_in">this</span>.last = <span class="hljs-built_in">this</span>.first;
        <span class="hljs-built_in">this</span>.size = <span class="hljs-number">1</span>;
    }

    enqueue(value: T): <span class="hljs-built_in">void</span> {
        <span class="hljs-keyword">const</span> newNode = <span class="hljs-keyword">new</span> Node(value);
        <span class="hljs-keyword">if</span>(<span class="hljs-built_in">this</span>.last !== <span class="hljs-literal">null</span>) <span class="hljs-built_in">this</span>.last.next = newNode;
        <span class="hljs-built_in">this</span>.last = newNode;
        <span class="hljs-keyword">if</span>(<span class="hljs-built_in">this</span>.first === <span class="hljs-literal">null</span>) <span class="hljs-built_in">this</span>.first = <span class="hljs-built_in">this</span>.last;
        <span class="hljs-built_in">this</span>.size++;
    }

    dequeue(): T | <span class="hljs-literal">null</span> {
        <span class="hljs-keyword">if</span>(<span class="hljs-built_in">this</span>.first === <span class="hljs-literal">null</span>) <span class="hljs-keyword">return</span> <span class="hljs-literal">null</span>;
        <span class="hljs-keyword">const</span> nodeToDequeue = <span class="hljs-built_in">this</span>.first;
        <span class="hljs-built_in">this</span>.first = <span class="hljs-built_in">this</span>.first.next;
        <span class="hljs-keyword">if</span>(<span class="hljs-built_in">this</span>.first === <span class="hljs-literal">null</span>) <span class="hljs-built_in">this</span>.last = <span class="hljs-literal">null</span>;
        <span class="hljs-built_in">this</span>.size--;
        <span class="hljs-keyword">return</span> nodeToDequeue.value;
    }

    peek(): T | <span class="hljs-literal">null</span> {
        <span class="hljs-keyword">return</span> <span class="hljs-built_in">this</span>.first ? <span class="hljs-built_in">this</span>.first.value : <span class="hljs-literal">null</span>;
    }

    isEmpty(): <span class="hljs-built_in">boolean</span> {
        <span class="hljs-keyword">return</span> <span class="hljs-built_in">this</span>.size === <span class="hljs-number">0</span>;
    }
}
</code></pre>
<h3 id="heading-final-thoughts">Final Thoughts</h3>
<p>In this post, we have explored the Queue data structure and its FIFO (First In, First Out) principle. We reviewed how to implement a Queue in TypeScript, using linked nodes similar to those we used in stacks, but with the crucial difference of adding elements to the end and removing them from the beginning.</p>
<p>We implemented four fundamental operations: enqueue to add elements, dequeue to remove them, peek to check the first element without removing it, and isEmpty to verify if the queue is empty. These operations allow us to manipulate the queue efficiently, always maintaining the order of arrival.</p>
<p>Queues are fundamental data structures that appear in numerous programming contexts and in everyday situations, like waiting in line for your favorite artist’s autograph. Understanding their operation and implementation gives us powerful tools to solve problems that require processing elements in the same order they were received.</p>
<p>As alway you can find the code in my Data Structures repository: <a target="_blank" href="https://github.com/RubenOAlvarado/data-structures">https://github.com/RubenOAlvarado/data-structures</a></p>
<p>Until the next one!</p>
]]></content:encoded></item><item><title><![CDATA[Untangling the Stack: How TypeScript and Dirty Dishes Share the Same Data Structure]]></title><description><![CDATA[Photo belongs to Jeremy Thomas in Unsplash
It’s Friday night, and after a hard week, all you want is to play ranked matches in Street Fighter 6 for that dopamine rush from defeating novice players. But before that, you realize your dishes have gone u...]]></description><link>https://blog.rubenoalvarado.com/untangling-the-stack-how-typescript-and-dirty-dishes-share-the-same-data-structure-b59c063b93ab</link><guid isPermaLink="true">https://blog.rubenoalvarado.com/untangling-the-stack-how-typescript-and-dirty-dishes-share-the-same-data-structure-b59c063b93ab</guid><category><![CDATA[data structure and algorithms ]]></category><category><![CDATA[data structures]]></category><category><![CDATA[TypeScript]]></category><category><![CDATA[TypeScript Generics]]></category><category><![CDATA[algorithms]]></category><category><![CDATA[Algorithms Data Structures ]]></category><dc:creator><![CDATA[Ruben O. Alvarado]]></dc:creator><pubDate>Tue, 02 Sep 2025 00:39:06 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1758816014699/5ab776ed-0c98-4aed-90c3-2f97d3339ae0.jpeg" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>Photo belongs to <a target="_blank" href="https://unsplash.com/es/@jeremythomasphoto?utm_content=creditCopyText&amp;utm_medium=referral&amp;utm_source=unsplash">Jeremy Thomas</a> in <a target="_blank" href="https://unsplash.com/es/fotos/roca-apilada-en-la-orilla-del-mar-FO7bKvgETgQ?utm_content=creditCopyText&amp;utm_medium=referral&amp;utm_source=unsplash">Unsplash</a></p>
<p>It’s Friday night, and after a hard week, all you want is to play ranked matches in Street Fighter 6 for that dopamine rush from defeating novice players. But before that, you realize your dishes have gone unwashed for three days, and your wife is as furious as a Ken player who failed to trap you in the corner.</p>
<p>You need to tackle this stack of plates before you can even think about putting your hands on that controller. When you reach the last plate, you realize that you forgot to throw away the food remains, and now it’s an indescribable, amorphous thing staring directly at you. This plate was the first in and the last out — and now you regret not maintaining this basic habit.</p>
<h3 id="heading-lifo-in-action">LIFO in Action</h3>
<p>This is a great example of the LIFO principle, this means that the last item to be added to the stack is going to be the first to be removed.</p>
<p>This has great usability in scenarios when you need to keep track of function calls, undo operations or manage resources in a controlled manner.</p>
<p>Stacks are there in our daily basis, so today we are going to implement our own custom stack in typescript.</p>
<h3 id="heading-all-about-nodes">All About Nodes</h3>
<p>To store each item in the stack, we’ll create a Node class. We’ll take an approach similar to linked lists, where each node connects to the next one. This structure allows us to efficiently add or remove items from the same side of the stack.</p>
<pre><code class="lang-tsx">export class Node&lt;T&gt; {
    value: T;
    next: Node&lt;T&gt; | null;

    constructor(value: T) {
        this.value = value;
        this.next = null;
    }
}
</code></pre>
<p>This is a simple yet effective implementation that serves two essential purposes: storing the actual value we want to keep in our stack and maintaining a reference to the next Node in the sequence. The Node class uses generics (represented by ) to allow for type flexibility, meaning our stack can store any data type — whether numbers, strings, objects, or custom types — while maintaining type safety throughout the application. When we instantiate a new Node, the next property is initially set to null, indicating it’s not connected to any other node yet.</p>
<h3 id="heading-creating-our-stack-class">Creating our Stack Class</h3>
<p>Now, let’s proceed with creating our Stack class implementation using TypeScript generics. Generics allow us to build reusable components that can work with different data types while maintaining type safety throughout our application. By leveraging TypeScript’s type system, we’ll ensure our stack operates consistently regardless of what type of data it stores.</p>
<pre><code class="lang-typescript"><span class="hljs-keyword">export</span> <span class="hljs-keyword">class</span> Stack {}
</code></pre>
<p>This class will have two properties: <code>first</code>, which stores the top item in our stack, and <code>size</code>, which keeps track of our stack's length.</p>
<pre><code class="lang-typescript">first: Node | <span class="hljs-literal">null</span>;
size: <span class="hljs-built_in">number</span>;
</code></pre>
<p>Then, in our constructor, when our stack is instantiated, we are going to initialize our stack with the necessary properties. This initialization process establishes the foundation of our data structure by setting up the first node and determining the initial size. The constructor takes a value parameter, which becomes the first element in our stack, ensuring that our stack begins with at least one item. This approach provides a clean starting point for stack operations and maintains type safety throughout the implementation.</p>
<pre><code class="lang-typescript"><span class="hljs-keyword">constructor</span>(<span class="hljs-params">value: T</span>){
    <span class="hljs-keyword">const</span> newNode = <span class="hljs-keyword">new</span> Node(value);
    <span class="hljs-built_in">this</span>.first = newNode;
    <span class="hljs-built_in">this</span>.size = <span class="hljs-number">1</span>;
}
</code></pre>
<h3 id="heading-popping-up">Popping Up</h3>
<p>This method removes the top node from our stack. First, we need to check our <code>first</code> variable to ensure the stack isn't empty.</p>
<pre><code class="lang-typescript"><span class="hljs-keyword">if</span>(<span class="hljs-built_in">this</span>.first === <span class="hljs-literal">null</span>) {
    <span class="hljs-keyword">return</span> <span class="hljs-literal">null</span>; <span class="hljs-comment">// Stack is empty</span>
}
</code></pre>
<p>Now that we’ve ensured our stack isn’t empty, we retrieve the top node’s value in a temporary variable called <code>poppedNode</code>. Then we set our <code>first</code> pointer to the next node in line, making it the new top of our stack.</p>
<pre><code class="lang-typescript"><span class="hljs-keyword">const</span> poppedNode = <span class="hljs-built_in">this</span>.first;
<span class="hljs-built_in">this</span>.first = <span class="hljs-built_in">this</span>.first.next;
</code></pre>
<p>Finally, we decrement our <code>size</code> property to reflect the removal and return the value of the <code>poppedNode</code>.</p>
<pre><code class="lang-typescript"><span class="hljs-built_in">this</span>.size--;
<span class="hljs-keyword">return</span> poppedNode.value;
</code></pre>
<p>And there you go, our <code>pop</code> method is now fully implemented and ready to efficiently remove items from the top of our stack. This implementation follows the LIFO principle we discussed earlier, ensuring that only the most recently added element can be removed.</p>
<h3 id="heading-pushing-a-new-item">Pushing a New Item</h3>
<p>This method adds a new node to the top of our stack. Similar to the pop method, we first check if our stack is empty. If it is, this new node becomes the first one in our stack.</p>
<pre><code class="lang-typescript"><span class="hljs-keyword">if</span>(<span class="hljs-built_in">this</span>.first === <span class="hljs-literal">null</span>) {
    <span class="hljs-built_in">this</span>.first = <span class="hljs-keyword">new</span> Node(value);
    <span class="hljs-built_in">this</span>.size = <span class="hljs-number">1</span>;
    <span class="hljs-keyword">return</span>;
}
</code></pre>
<p>If the stack is not empty, we need to add the new node to the top. First, we create a new Node instance. Then we link our existing first node as the next value of our new node and reassign the first pointer to this new node. Finally, we increment the size of our stack.</p>
<pre><code class="lang-typescript"><span class="hljs-keyword">const</span> newNode = <span class="hljs-keyword">new</span> Node(value);
newNode.next = <span class="hljs-built_in">this</span>.first;
<span class="hljs-built_in">this</span>.first = newNode;
<span class="hljs-built_in">this</span>.size++;
</code></pre>
<p>And there you go, our stack implementation now has the ability to efficiently push new nodes to the top of the stack. This method adheres to the LIFO principle by ensuring that newly added elements become immediately accessible at the top of the stack, ready to be the first ones removed when a pop operation is performed.</p>
<h3 id="heading-peeking-the-top-node">Peeking the Top Node</h3>
<p>This method allows us to examine the top node of our stack without removing it, providing a valuable way to inspect the most recently added element. When implementing the peek operation, we first need to perform a crucial validation to verify that our stack contains at least one element.</p>
<pre><code class="lang-typescript"><span class="hljs-keyword">if</span>(<span class="hljs-built_in">this</span>.first === <span class="hljs-literal">null</span>) {
    <span class="hljs-keyword">return</span> <span class="hljs-literal">null</span>; <span class="hljs-comment">// Stack is empty</span>
}
</code></pre>
<p>Once we confirm the stack isn’t empty, we can simply return the value of the top node. Since we’ve already stored this in the <code>first</code> variable, we just need to return the value property of this node.</p>
<pre><code class="lang-typescript"><span class="hljs-keyword">return</span> <span class="hljs-built_in">this</span>.first.value;
</code></pre>
<p>And there you have it. Our stack implementation now allows us to peek at the top node without removing it.</p>
<h3 id="heading-the-stack-is-empty">The Stack is Empty?</h3>
<p>This method will check if our stack has nodes in it. It serves as a useful utility function that allows us to determine whether our stack contains any elements or if it’s completely empty. To determine this, we simply check whether the <code>size</code> property equals zero.</p>
<pre><code class="lang-typescript"><span class="hljs-keyword">return</span> <span class="hljs-built_in">this</span>.size === <span class="hljs-number">0</span>;
</code></pre>
<h3 id="heading-complete-typescript-implementation">Complete Typescript Implementation</h3>
<p>Node class:</p>
<pre><code class="lang-tsx">export class Node&lt;T&gt; {
    value: T;
    next: Node&lt;T&gt; | null;

    constructor(value: T) {
        this.value = value;
        this.next = null;
    }
}
</code></pre>
<p>Stack class:</p>
<pre><code class="lang-tsx">export class Stack&lt;T&gt; {
    first: Node&lt;T&gt; | null;
    size: number;

    constructor(value: T){
        const newNode = new Node(value);
        this.first = newNode;
        this.size = 1;
    }

    push(value: T): void {
        if(this.first === null) {
          this.first = new Node(value);
        this.size = 1;
        return;
      }
      const newNode = new Node(value);
      newNode.next = this.first;
      this.first = newNode;
      this.size++;
    }

    pop(): T | null {
        if(this.first === null) {
            return null;
          }
          const poppedNode = this.first;
          this.first = this.first.next;
          this.size--;
          return poppedNode.value;
    }

    peek(): T | null {
        if(this.first === null) {
            return null;
          }
          return this.first.value;
        }

        isEmpty(): boolean {
            return this.size === 0;
        }
}
</code></pre>
<h3 id="heading-final-thoughts">Final Thoughts</h3>
<p>Stacks play a crucial role in recursive algorithms, offering an elegant solution for managing function calls and tracking execution states. Implementing a stack from scratch, as we’ve done here, provides valuable insight into the inner workings of this fundamental data structure. It serves as an excellent exercise for strengthening your understanding of both data structures and TypeScript’s type system, while also developing practical skills that can be applied to solve complex programming challenges in real-world applications.</p>
<p>As usual, you can find this code and other Data Structures implementations in my GitHub repository: <a target="_blank" href="https://github.com/RubenOAlvarado/data-structures">https://github.com/RubenOAlvarado/data-structures</a></p>
<p>Continue your learning journey and stay persistent with DSA challenges. See you in the next article!</p>
]]></content:encoded></item><item><title><![CDATA[Balancing Act: Mastering the Valid Parenthesis Problem]]></title><description><![CDATA[Photo belongs to Nick Fewings on Unsplash
Welcome back, algorithm enthusiasts! I hope you are enjoying this series revisiting the most frequently asked algorithms and data structures in technical interviews.
Throughout this series, we’ve covered a wi...]]></description><link>https://blog.rubenoalvarado.com/balancing-act-mastering-the-valid-parenthesis-problem-348863ad9b07</link><guid isPermaLink="true">https://blog.rubenoalvarado.com/balancing-act-mastering-the-valid-parenthesis-problem-348863ad9b07</guid><dc:creator><![CDATA[Ruben O. Alvarado]]></dc:creator><pubDate>Mon, 25 Aug 2025 14:54:46 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1758816016963/41a7a634-0c98-45cc-8535-a8fad65a7dc2.jpeg" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>Photo belongs to <a target="_blank" href="https://unsplash.com/es/@jannerboy62?utm_content=creditCopyText&amp;utm_medium=referral&amp;utm_source=unsplash">Nick Fewings</a> on <a target="_blank" href="https://unsplash.com/es/fotos/un-grupo-de-sillas-de-jardin-sentadas-en-la-cima-de-una-playa-de-arena-OngETOdYjm8?utm_content=creditCopyText&amp;utm_medium=referral&amp;utm_source=unsplash">Unsplash</a></p>
<p>Welcome back, algorithm enthusiasts! I hope you are enjoying this series revisiting the most frequently asked algorithms and data structures in technical interviews.</p>
<p>Throughout this series, we’ve covered a wide range of topics — from implementing custom Arrays and Hash Tables to solving common coding challenges like reversing strings, finding the maximum character in a string, and validating palindromes.</p>
<p>Today we are moving forward in difficulty and we are going to implement another one at the top of the notch. The <code>balanced string</code> also now as <code>valid parenthesis</code> problem.</p>
<h3 id="heading-understanding-the-problem">Understanding the Problem</h3>
<p>The problem statement for this challenge is as follows:</p>
<blockquote>
<p><em>Given a string s containing just the characters ‘(‘, ‘)’, ‘{‘, ‘}’, ‘[‘ and ‘]’, determine if the input string is valid.</em></p>
</blockquote>
<p>Now, let’s consider the constraints we need to follow when solving this problem:</p>
<ul>
<li><p>Open brackets must be closed by the same type of brackets.</p>
</li>
<li><p>Open brackets must be closed in the correct order.</p>
</li>
<li><p>Every close bracket has a corresponding open bracket of the same type.</p>
</li>
</ul>
<p>This is interesting — we have specific constraints to follow. Let’s analyze the problem statement: we have an input string containing only certain bracket characters, and we need to return a boolean indicating whether the input is valid according to the given rules.</p>
<p>“How do I solve this?” you might be asking yourself. The first time I faced this problem, I brute-forced it with numerous if statements and for loops. I even tried creating a map to count each character’s appearances, then dividing and checking modular results to ensure each bracket pair balanced to zero.</p>
<p>I know, I know. Like <a target="_blank" href="https://scholar.harvard.edu/files/seyer/files/plato_republic_514b-518d_allegory-of-the-cave.pdf">Plato’s cave allegory</a>, I was blinded by my limited knowledge. After studying data structures and algorithms more thoroughly, I realized there’s a simple and efficient way to solve this challenge using a common structure known as a stack.</p>
<h3 id="heading-last-in-first-out">Last In First Out</h3>
<p>It’s Friday night, and after a hard week, all you want is to play ranked matches in Street Fighter 6 for that dopamine rush from defeating novice players. But before that, you realize your dishes have gone unwashed for three days, and your wife is as furious as a Ken player who failed to trap you in the corner.</p>
<p>You need to tackle this stack of plates before you can even think about putting your hands on that controller. When you reach the last plate, you realize that you forgot to throw away the food remains, and now it’s an indescribable, amorphous thing staring directly at you. This plate was the first in and the last out — and now you regret not maintaining this basic habit.</p>
<h3 id="heading-stack-of-plates">Stack of Plates</h3>
<p>With the plates analogy, we’ve revealed the core concept of stacks: the first item to be stacked will be the last one to be retrieved. This principle is known as <code>LIFO</code> (Last In First Out) and explains how stacks work under the hood.</p>
<p>Now, imagine that instead of a pile of plates, there are brackets. This is the first step to solving this problem.</p>
<p>Before diving into the code, I need to clarify something first. To solve this exercise, we’ll use a <code>JavaScript</code> array that functions as a stack. The array class has built-in methods that work perfectly for stack operations: <code>push()</code>, <code>pop()</code>, etc. We'll discuss stacks in more detail in the next post, but for now, I wanted to explain this so you won't be confused when you see an array named "stack."</p>
<h3 id="heading-algorithm-to-solve-it">Algorithm to Solve It</h3>
<ul>
<li>First, declare an empty array called <code>stack</code> where we'll store our characters.</li>
</ul>
<pre><code class="lang-typescript"><span class="hljs-keyword">const</span> stack: <span class="hljs-built_in">string</span>[] = [];
</code></pre>
<ul>
<li>Next, let’s create a <code>map-like</code> object to match opening and closing brackets. We'll use a simple object since we have a specific number of characters to map and need to reduce space complexity. Alternatively, we could use a <a target="_blank" href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Map">Map</a> object.</li>
</ul>
<pre><code class="lang-typescript"><span class="hljs-keyword">const</span> pairs: Record&lt;<span class="hljs-built_in">string</span>, <span class="hljs-built_in">string</span>&gt; = {<span class="hljs-string">'('</span>: <span class="hljs-string">')'</span>,<span class="hljs-string">'{'</span>: <span class="hljs-string">'}'</span>,<span class="hljs-string">'['</span>: <span class="hljs-string">']'</span>,};
</code></pre>
<ul>
<li>Now that we’ve set up our variables, it’s time to loop through our input string with a good old for…of loop.</li>
</ul>
<pre><code class="lang-typescript"><span class="hljs-keyword">for</span> (<span class="hljs-keyword">let</span> char <span class="hljs-keyword">of</span> str) {}
</code></pre>
<ul>
<li>In each iteration, we check for possible scenarios. If the character is a key in our pairs object, it means it’s an opening bracket. For example: <code>char = "("</code> → <code>pairs["("]</code> exists and its value is <code>")"</code>, so we push it onto the stack.</li>
</ul>
<pre><code class="lang-typescript"><span class="hljs-keyword">if</span> (pairs[char]) {
    stack.push(char);
}
</code></pre>
<ul>
<li>Otherwise, it must be a closing bracket. We need to verify it matches our last stacked opening bracket. We <code>pop</code> the last opening bracket from the stack and check if the current character is its corresponding closing bracket. If not, we return <code>false</code> because the string is not balanced.</li>
</ul>
<pre><code class="lang-typescript"><span class="hljs-keyword">else</span> {
    <span class="hljs-keyword">const</span> last = stack.pop();
    <span class="hljs-keyword">if</span> (pairs[last!] !== char) {
        <span class="hljs-keyword">return</span> <span class="hljs-literal">false</span>;
    }
}
</code></pre>
<ul>
<li>Finally, if the <code>stack</code> is empty, it means the string is balanced; otherwise, it means some opening brackets don't have matching closing brackets. We simply return this evaluation.</li>
</ul>
<pre><code class="lang-typescript"><span class="hljs-keyword">return</span> stack.length === <span class="hljs-number">0</span>;
</code></pre>
<p>With this, we’ve solved the problem. Simple, right? You just need the right knowledge to tackle it effectively. Pay close attention to how the stack interacts with opening brackets to fully grasp the core functionality of this solution.</p>
<h3 id="heading-complete-typescript-implementation">Complete Typescript Implementation</h3>
<pre><code class="lang-tsx">function balancedString(str: string): boolean {
    const stack: string[] = [];
    const pairs: Record&lt;string, string&gt; = {
            '(': ')',
          '{': '}',
          '[': ']',
        };

    for (let char of str) {
        if (pairs[char]) {
                    stack.push(char);
                } else {
            const last = stack.pop();
                      if (pairs[last!] !== char) {
                        return false;
                      }
        }
    }

    return stack.length === 0;
}
</code></pre>
<h3 id="heading-final-thoughts">Final Thoughts</h3>
<p>Stacks and Queues are fundamental data structures that appear frequently in coding interviews. In upcoming posts, I’ll explore these concepts in greater depth to equip you with the knowledge to tackle similar challenges. As this exercise demonstrates, understanding key Data Structures and Algorithms (DSA) principles enables you to craft elegant, efficient solutions rather than relying on brute force approaches.</p>
<p>As always, you can find this solution along with other algorithm implementations in my GitHub repository: <a target="_blank" href="https://github.com/RubenOAlvarado/algorithms">https://github.com/RubenOAlvarado/algorithms</a><br />Until next time!</p>
]]></content:encoded></item><item><title><![CDATA[Unveiling the Magic of Hash Tables: Your Ultimate Guide to Efficient Data Lookup PT. 2]]></title><description><![CDATA[Photo belongs to Ján Jakub Naništa in Unsplash
Last week, we began exploring Hash Tables, a crucial data structure for software engineers. Today we’ll continue our review by adding usability features to our custom Hash Table class.
Join me as we dive...]]></description><link>https://blog.rubenoalvarado.com/unveiling-the-magic-of-hash-tables-your-ultimate-guide-to-efficient-data-lookup-pt-2-6ac63e6ccb69</link><guid isPermaLink="true">https://blog.rubenoalvarado.com/unveiling-the-magic-of-hash-tables-your-ultimate-guide-to-efficient-data-lookup-pt-2-6ac63e6ccb69</guid><category><![CDATA[data structures]]></category><category><![CDATA[algorithms]]></category><category><![CDATA[Algorithms Data Structures ]]></category><category><![CDATA[data structure and algorithms ]]></category><category><![CDATA[TypeScript]]></category><category><![CDATA[TypeScript Generics]]></category><dc:creator><![CDATA[Ruben O. Alvarado]]></dc:creator><pubDate>Tue, 19 Aug 2025 00:30:43 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1758816019900/ef83982b-9dfd-4b92-a758-3e6c61a2d509.jpeg" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>Photo belongs to <a target="_blank" href="https://unsplash.com/es/@janjakubnanista?utm_content=creditCopyText&amp;utm_medium=referral&amp;utm_source=unsplash">Ján Jakub Naništa</a> in <a target="_blank" href="https://unsplash.com/es/fotos/edificio-de-hormigon-blanco-y-azul-de-4-plantas-UHyrjKPsshk?utm_content=creditCopyText&amp;utm_medium=referral&amp;utm_source=unsplash">Unsplash</a></p>
<p>Last week, we began <a target="_blank" href="https://medium.com/@rubenosmaralvarado/unveiling-the-magic-of-hash-tables-your-ultimate-guide-to-efficient-data-lookup-pt-1-800ed3cb8f3f">exploring Hash Tables</a>, a crucial data structure for software engineers. Today we’ll continue our review by adding usability features to our custom Hash Table class.</p>
<p>Join me as we dive deeper into the magic of hash tables in this second installment.</p>
<h3 id="heading-starting-from-where-we-left">Starting from where we left</h3>
<p>Let’s make a quick recap of what we covered in our previous session: We began by constructing a custom <code>hash table</code> class that utilizes two generic types - one specifically for the key and another designated for the value. Subsequently, we established a table object designed to function as a container for our various buckets. Following this, we carefully defined a hash function implementing the well-known <code>DJB2 algorithm</code> to efficiently process our keys. This foundation provides us with the essential infrastructure to insert new buckets into our table structure and assign them a properly <code>hashed key</code>, ensuring optimal performance and data organization. These fundamental components form the backbone of our hash table implementation, allowing us to build more sophisticated features on top of this solid base. This leaves our class in the following state:</p>
<pre><code class="lang-tsx">export class HashTable&lt;K, V&gt; {
  private table: Array&lt;Array&lt;[K, V]&gt;&gt;;

  constructor(private size: number) {
      this.table = new Array(size).fill(null).map(() =&gt; []);
  }

  private hash(key: K): number {
    let hash = 5381;
    const strKey = String(key);

    for (let i = 0; i &lt; strKey.length; i++) {
        const char = strKey.charCodeAt(i);
        hash = (hash * 33) + char;
    }

    return Math.abs(hash) % this.size;
  }
}
</code></pre>
<h3 id="heading-adding-new-data">Adding New Data</h3>
<p>Let’s define our <code>set</code> function which will insert or update a new key-value pair in our table. It will receive two generic parameters: one of type <code>K</code> for the key and another of type <code>V</code> for the value. Since it won't return anything, the return type is void.</p>
<pre><code class="lang-typescript">set(key: K, value: V): <span class="hljs-built_in">void</span> {}
</code></pre>
<p>First, in the function body, we need to get the <code>index</code> by hashing the <code>key</code>. Once we have the <code>index</code>, we'll retrieve the corresponding <code>bucket</code> from our table. If no <code>bucket</code> exists at that <code>index</code>, our table initialization will have already created an empty array there.</p>
<pre><code class="lang-typescript"><span class="hljs-keyword">const</span> index = <span class="hljs-built_in">this</span>.hash(key);
<span class="hljs-keyword">const</span> bucket = <span class="hljs-built_in">this</span>.table[index];
</code></pre>
<p>Inside the <code>bucket</code>, we need to find the <code>key</code>. Remember the apartments analogy from the <a target="_blank" href="https://medium.com/@rubenosmaralvarado/unveiling-the-magic-of-hash-tables-your-ultimate-guide-to-efficient-data-lookup-pt-1-800ed3cb8f3f">previous post</a>? We have the building and the floor, now we need to locate the specific apartment number.</p>
<pre><code class="lang-typescript"><span class="hljs-keyword">const</span> existing = bucket.find(<span class="hljs-function">(<span class="hljs-params">[k]</span>) =&gt;</span> k === key);
</code></pre>
<p>If the apartment already has an occupant (data), we need to update it; if not, we will assign the value.</p>
<pre><code class="lang-typescript"><span class="hljs-keyword">if</span> (existing) {
    existing[<span class="hljs-number">1</span>] = value;
} <span class="hljs-keyword">else</span> {
    bucket.push([key, value])
}
</code></pre>
<h3 id="heading-retrieving-data-by-key">Retrieving Data by Key</h3>
<p>Next, let’s create our get method. This method accepts a <code>key</code> parameter of type <code>K</code> and returns a <code>value</code> of type <code>V</code>, giving us the following method signature:</p>
<pre><code class="lang-typescript">get(key: K): V | <span class="hljs-literal">undefined</span> {}
</code></pre>
<p>Notice the return type declaration includes both <code>V</code> and <code>undefined</code>. This is because the requested <code>key</code> might not exist in our hash table.</p>
<p>Similar to our <code>set</code> method, we first need to find the <code>index</code> and the <code>bucket</code> for the given key. Then we check if the <code>key</code> exists in that <code>bucket</code>. This two-step process is crucial, we first locate the index using our hash function, then search for the specific key within that bucket.</p>
<p>Using our <a target="_blank" href="https://medium.com/@rubenosmaralvarado/unveiling-the-magic-of-hash-tables-your-ultimate-guide-to-efficient-data-lookup-pt-1-800ed3cb8f3f">apartment analogy</a>: we first identify the building, then the floor, and finally check if the specific apartment exists on that floor.</p>
<pre><code class="lang-typescript"><span class="hljs-keyword">const</span> index = <span class="hljs-built_in">this</span>.hash(key);
<span class="hljs-keyword">const</span> bucket = <span class="hljs-built_in">this</span>.table[index];
<span class="hljs-keyword">const</span> entry = bucket.find(<span class="hljs-function">(<span class="hljs-params">[k]</span>) =&gt;</span> k === key);
</code></pre>
<p>Finally, if the <code>key</code> exists in the <code>bucket</code>, we return the associated value; otherwise, we return <code>undefined</code>. We can achieve this using a <a target="_blank" href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Conditional_operator">ternary operator</a>.</p>
<pre><code class="lang-typescript"><span class="hljs-keyword">return</span> entry ? entry[<span class="hljs-number">1</span>] : <span class="hljs-literal">undefined</span>;
</code></pre>
<h3 id="heading-checking-for-key-existence-in-our-hash-table">Checking for Key Existence in Our Hash Table</h3>
<p>Now let’s implement our <code>has</code> method, which checks whether a key exists in our hash table. This method operates similarly to the <code>get</code> method, but with one key difference. Let me walk you through it.</p>
<p>Here’s the method signature:</p>
<pre><code class="lang-typescript">has(key: K): <span class="hljs-built_in">boolean</span> {}
</code></pre>
<p>Similar to the <code>get</code> method, this will accept a <code>key</code> parameter of type <code>K</code>, but will return a <code>boolean</code> value that indicates whether the <code>key</code> exists in our hash table. Let's follow the same approach as our previous methods by first obtaining the <code>index</code> and the <code>bucket</code> for the <code>key</code>.</p>
<pre><code class="lang-typescript"><span class="hljs-keyword">const</span> index = <span class="hljs-built_in">this</span>.hash(key);
<span class="hljs-keyword">const</span> bucket = <span class="hljs-built_in">this</span>.table[index];
</code></pre>
<p>Here’s where things get interesting. After obtaining the <code>bucket</code>, we need to check if any entry in it contains our <code>key</code>. This is a perfect use case for the <code>JavaScript</code> <a target="_blank" href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/some">some method</a>, which tests whether at least one element in an array passes a given condition.</p>
<pre><code class="lang-typescript"><span class="hljs-keyword">return</span> bucket.some(<span class="hljs-function">(<span class="hljs-params">[k]</span>) =&gt;</span> k === key);
</code></pre>
<h3 id="heading-eliminating-data-by-key-from-our-hash-table">Eliminating Data by Key from our Hash Table</h3>
<p>Finally, let’s implement our <code>remove</code> method. This method takes a <code>key</code> parameter of type <code>K</code> and returns a <code>boolean</code> indicating whether the <code>key</code> was successfully removed from the table.</p>
<pre><code class="lang-typescript">remove(key: K): <span class="hljs-built_in">boolean</span> {}
</code></pre>
<p>Next, as you would expect, we’ll retrieve the <code>index</code> and the <code>bucket</code> using the same logic as our previous methods. Once we have the <code>bucket</code>, we need to find the position of the entry with our <code>key</code> so we can remove it from the array. To accomplish this, we'll use the <a target="_blank" href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/findIndex">findIndex</a> method to locate the entry and the <a target="_blank" href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/splice">splice</a> method to remove it.</p>
<p>After finding the <code>index</code> for the <code>key</code> in the <code>bucket</code> (continuing our apartments analogy), we need to check if the entry exists. The <code>findIndex</code> method returns <code>-1</code> if no match is found or the actual index position if the entry exists.</p>
<p>Let’s add a condition to check before removing the <code>key</code>.</p>
<pre><code class="lang-typescript"><span class="hljs-keyword">if</span> (entryIndex !== <span class="hljs-number">-1</span>)
</code></pre>
<p>If it’s not equal to <code>-1</code>, it means the <code>key</code> was found, so we can <code>splice</code> our array and return <code>true</code> because our value was successfully removed from the table; otherwise, we simply return <code>false</code>.</p>
<pre><code class="lang-typescript"><span class="hljs-keyword">if</span> (entryIndex !== <span class="hljs-number">-1</span>) {
    bucket.splice(entryIndex, <span class="hljs-number">1</span>);
    <span class="hljs-keyword">return</span> <span class="hljs-literal">true</span>;
}
<span class="hljs-keyword">return</span> <span class="hljs-literal">false</span>;
</code></pre>
<h3 id="heading-optimizing-our-implementation-a-dry-approach">Optimizing Our Implementation: A DRY Approach</h3>
<p>At this point, you might notice we’re repeating ourselves in each method, and a <code>pragmatic programmer</code> never repeats themselves. Let's create a private <code>getBucket</code> method to eliminate this redundancy, since retrieving the bucket is the first step in every operation we perform.</p>
<pre><code class="lang-typescript"><span class="hljs-keyword">private</span> getBucket(key: K): <span class="hljs-built_in">Array</span>&lt;[K, V]&gt; {
    <span class="hljs-keyword">const</span> index = <span class="hljs-built_in">this</span>.hash(key);
    <span class="hljs-keyword">return</span> <span class="hljs-built_in">this</span>.table[index];
}
</code></pre>
<p>This is a private method because it’s only for internal use within our class. It receives the <code>key</code> as a parameter and returns the corresponding <code>bucket</code> from our table.</p>
<p>And there you have it — a complete implementation of a simple <code>Hash Table</code> in <code>TypeScript</code>.</p>
<h3 id="heading-complete-hash-table-implementation-with-typescript">Complete Hash Table Implementation with TypeScript</h3>
<pre><code class="lang-tsx">export class HashTable&lt;K, V&gt; {
    private table: Array&lt;Array&lt;[K, V]&gt;&gt;;

    constructor(private size: number) {
        this.table = new Array(size).fill(null).map(() =&gt; []);
    }

    private hash(key: K): number {
        let hash = 5381;
        const strKey = String(key);

        for (let i = 0; i &lt; strKey.length; i++) {
            const char = strKey.charCodeAt(i);
            hash = (hash * 33) + char;
        }

        return Math.abs(hash) % this.size;
    }

    private getBucket(key: K): Array&lt;[K, V]&gt; {
        const index = this.hash(key);
        return this.table[index];
    }

    set(key: K, value: V): void {
        const bucket = this.getBucket(key);

        const existing = bucket.find(([k]) =&gt; k === key);
        if (existing) {
            existing[1] = value;
        } else {
            bucket.push([key, value])
        }
    }

    get(key: K): V | undefined {
        const bucket = this.getBucket(key);

        const entry = bucket.find(([k]) =&gt; k === key);
        return entry ? entry[1] : undefined;
    }

    has(key: K): boolean {
        const bucket = this.getBucket(key);

        return bucket.some(([k]) =&gt; k === key);
    }

    remove(key: K): boolean {
        const bucket = this.getBucket(key);

        const entryIndex = bucket.findIndex(([k]) =&gt; k === key);
        if (entryIndex !== -1) {
            bucket.splice(entryIndex, 1);
            return true;
        }
        return false;
    }
}
</code></pre>
<h3 id="heading-final-thoughts">Final Thoughts</h3>
<p>As you can see, <code>Data Structures</code> and <code>Algorithms</code> aren't rocket science once you grasp the core concepts. Creating your own implementations helps you understand why and how they work in practical applications.</p>
<p>Keep practicing — the only way to master something is through consistent practice and patience. As usual, you can review this and other <code>Data Structures</code> in my <code>Github</code> repository: <a target="_blank" href="https://github.com/RubenOAlvarado/data-structures">https://github.com/RubenOAlvarado/data-structures</a>.</p>
<p>See you next week!</p>
]]></content:encoded></item></channel></rss>