Exercise 6: Parse Integer Safely (with radix)

Problem Statement

Create a function `parseIntSafe(str, radix=10)` that converts a string to integer. Return null for invalid input. Support radix parameter. Example: - parseIntSafe("123") → 123 - parseIntSafe("0xFF", 16) → 255 - parseIntSafe("abc") → null

Sample Output:

parseIntSafe("123") => 123
parseIntSafe("0xFF", 16) => 255
parseIntSafe("1010", 2) => 10
parseIntSafe("abc") => null

Solution

const parseIntSafe = (str, radix = 10) => {
  const s = String(str ?? "").trim();
  if (!s) return null;
  const n = parseInt(s, radix);
  return Number.isNaN(n) ? null : n;
};

Explanation

Overall Goal:

  • String ko integer me convert karna with radix support (binary, hex, etc.).
  • Invalid input handle karna safely.

Line 1: Function header

  • const parseIntSafe = (str, radix = 10) => {
  • radix = 10 → default decimal (10-based number system).
  • Radix options: 2 (binary), 8 (octal), 10 (decimal), 16 (hexadecimal).

Line 2: Normalize string

  • const s = String(str ?? "").trim();
  • str ?? "" → nullish coalescing: null/undefined ho to empty string.
  • .trim() → leading/trailing spaces remove.

Line 3: Empty check

  • if (!s) return null;
  • Empty string ho to early return (invalid).

Line 4: Parse with radix

  • const n = parseInt(s, radix);
  • parseInt() → string ko integer me convert karta hai.
  • radix → number system specify karta hai:
  • parseInt("FF", 16) → 255 (hexadecimal).
  • parseInt("1010", 2) → 10 (binary).
  • parseInt("123", 10) → 123 (decimal).

Line 5: Validate result

  • return Number.isNaN(n) ? null : n;
  • parseInt("abc")NaN (invalid).
  • Number.isNaN(n) → check karta hai ki result NaN hai ya nahi.
  • Valid ho to n return, warna null.

Real world:

  • URL parsing: query parameters ko number me convert.
  • Color codes: hex colors (#FF0000) ko RGB me convert.
  • Form inputs: user input ko safely integer me convert.