Safe Null Navigator

Difficulty: Medium · Topics: Null Safety, Edge Cases, Optional

Difficulty: Medium  |  Tags: Null Safety, Edge Cases, Optional

Description

Given a nested object and a dot-separated path string, safely navigate through the object and return the value at the path. If any part of the path is null or does not exist, return a default value without throwing an exception.

This mirrors the optional chaining operator (?.) in JavaScript/TypeScript.

Implement:

safeGet(object, path, defaultValue) → Object

Examples

Example 1:

Input:
  obj  = {"user": {"address": {"city": "NYC"}}}
  path = "user.address.city"
  default = "Unknown"

Output: "NYC"

Example 2 — Null in chain:

Input:
  obj  = {"user": {"address": null}}
  path = "user.address.city"
  default = "Unknown"

Output: "Unknown"

Example 3 — Missing key:

Input:
  obj  = {"user": {"name": "Alice"}}
  path = "user.address.city"
  default = "N/A"

Output: "N/A"

Example 4 — Root is null:

Input:
  obj  = null
  path = "any.path"
  default = 0

Output: 0

Example 5 — Empty path:

Input:
  obj  = {"a": 1}
  path = ""
  default = null

Output: {"a": 1}
Explanation: Empty path returns the root object itself.

Constraints

Hints

Hint 1

Split path on ., iterate through keys, checking for null/missing at each step.

Practice this problem

Related problems