ℹ️ Select 'Choose Exercise', or randomize 'Next Random Exercise' in selected language.

Choose Exercise:
Timer 00:00
WPM --
Score --
Acc --
Correct chars --

Simple JSON Transformer with Nested Structures

Ruby

Goal -- WPM

Ready
Exercise Algorithm Area
1require 'json'
2
3# Transforms a nested JSON structure recursively.
4# Applies a given transformation block to non-hash/array values.
5# Handles empty structures and ensures deep copying.
6#
7# Args:
8# data: The JSON-like Ruby Hash or Array to transform.
9# transformation_block: A block that takes a value and returns its transformed version.
10#
11# Returns:
12# A new Hash or Array with the transformation applied.
13def deep_transform_json(data, &transformation_block)
14case data
15when Hash
16# Recursively transform each value in the hash.
17# Use `each_with_object` for efficient building of the new hash.
18data.each_with_object({}) do |(key, value), new_hash|
19new_hash[key] = deep_transform_json(value, &transformation_block)
20end
21when Array
22# Recursively transform each element in the array.
23# Use `map` to create a new array with transformed elements.
24data.map do |element|
25deep_transform_json(element, &transformation_block)
26end
27else
28# Apply the transformation block to leaf nodes (non-hash/array).
29# This includes strings, numbers, booleans, nil.
30transformation_block.call(data)
31end
32end
33
34# Helper function to create a sample nested JSON structure.
35def create_sample_json
36{
37"user" => {
38"id" => 123,
39"name" => "Alice",
40"details" => {
41"email" => "alice@example.com",
42"active" => true,
43"settings" => {
44"theme" => "dark",
45"notifications" => {
46"email" => true,
47"sms" => false
48}
49}
50},
51"roles" => ["admin", "editor"],
52"metadata" => {},
53"empty_array" => []
54},
55"system" => {
56"version" => "1.0.0",
57"config" => nil
58}
59}
60end
61
62# Example transformation: Convert all strings to uppercase.
63# transformed_data = deep_transform_json(create_sample_json) do |value|
64# value.is_a?(String) ? value.upcase : value
65# end
66# puts JSON.pretty_generate(transformed_data)
67
68# Example transformation: Add a prefix to all string values.
69# transformed_data_prefix = deep_transform_json(create_sample_json) do |value|
70# value.is_a?(String) ? "PRE_#{value}" : value
71# end
72# puts JSON.pretty_generate(transformed_data_prefix)
Algorithm description viewbox

Simple JSON Transformer with Nested Structures

Algorithm description:

This Ruby code provides a `deep_transform_json` method for recursively transforming nested JSON-like data structures. It's designed to apply a given transformation block to all non-container elements (like strings, numbers, booleans) while preserving the structure of nested hashes and arrays. This is useful for tasks like data sanitization, normalization, or applying consistent formatting across complex configurations.

Algorithm explanation:

The `deep_transform_json` method uses recursion to traverse the input data. If the data is a Hash, it iterates through its key-value pairs, recursively calling itself on each value and building a new hash. If the data is an Array, it maps over its elements, recursively calling itself on each element to produce a new array. For any other data type (leaf nodes), it applies the provided `transformation_block`. This ensures that the transformation penetrates all levels of the nested structure. The base cases for the recursion are non-container types. Time complexity is O(N), where N is the total number of nodes (keys and values) in the JSON structure, as each node is visited once. Space complexity is also O(N) in the worst case due to the recursion depth and the creation of a new transformed structure.

Pseudocode:

Function deep_transform_json(data, transformation_block):
  If data is a Hash:
    Create an empty new_hash.
    For each key, value in data:
      new_hash[key] = deep_transform_json(value, transformation_block).
    Return new_hash.
  Else if data is an Array:
    Create an empty new_array.
    For each element in data:
      new_array.push(deep_transform_json(element, transformation_block)).
    Return new_array.
  Else (leaf node):
    Return transformation_block(data).

Function create_sample_json():
  Return a predefined nested Hash representing JSON.