Skip to content

Commit 1003054

Browse files
committed
Remove custom JSON formatting functions, use Prettier for all formatting
1 parent cc13f13 commit 1003054

File tree

2 files changed

+4
-157
lines changed

2 files changed

+4
-157
lines changed

scripts/normalize_book_sets.py

Lines changed: 0 additions & 83 deletions
Original file line numberDiff line numberDiff line change
@@ -13,93 +13,10 @@
1313
import json
1414
import os
1515
import argparse
16-
import re
1716
import subprocess
1817
from pathlib import Path
1918

2019

21-
def compact_json_arrays(json_str: str, max_line_length: int = 150) -> str:
22-
"""
23-
Compact number arrays in JSON string to have multiple numbers per line.
24-
25-
Args:
26-
json_str: JSON string with arrays formatted one number per line
27-
max_line_length: Maximum characters per line (default: 150)
28-
29-
Returns:
30-
Compacted JSON string
31-
"""
32-
lines = json_str.split("\n")
33-
result = []
34-
i = 0
35-
36-
while i < len(lines):
37-
line = lines[i]
38-
39-
# Check if this line starts an array of numbers
40-
# Pattern: some indentation, "key": [
41-
array_start_match = re.match(r'^(\s*)"[^"]+": \[$', line)
42-
43-
if array_start_match:
44-
indent = array_start_match.group(1)
45-
result.append(line)
46-
i += 1
47-
48-
# Collect all numbers from subsequent lines
49-
numbers = []
50-
while i < len(lines):
51-
num_line = lines[i].strip()
52-
53-
# Check if it's a closing bracket
54-
if num_line == "]" or num_line == "],":
55-
# Format numbers compactly
56-
if numbers:
57-
# Group numbers to fit within max_line_length
58-
number_indent = indent + " "
59-
current_line = number_indent
60-
61-
for idx, num in enumerate(numbers):
62-
num_str = str(num)
63-
# Add comma if not the last number
64-
if idx < len(numbers) - 1:
65-
num_str += ", "
66-
67-
# Check if adding this number would exceed max length
68-
if (
69-
len(current_line + num_str) > max_line_length
70-
and current_line != number_indent
71-
):
72-
result.append(current_line.rstrip())
73-
current_line = number_indent + num_str
74-
else:
75-
current_line += num_str
76-
77-
# Add the last line
78-
if current_line.strip():
79-
result.append(current_line.rstrip())
80-
81-
# Add closing bracket
82-
result.append(indent + num_line)
83-
i += 1
84-
break
85-
86-
# Check if it's a number (with optional comma)
87-
num_match = re.match(r"^(\d+),?$", num_line)
88-
if num_match:
89-
numbers.append(int(num_match.group(1)))
90-
i += 1
91-
else:
92-
# Not a number array, just add the line as-is
93-
result.append(lines[i])
94-
i += 1
95-
break
96-
else:
97-
result.append(line)
98-
i += 1
99-
100-
return "\n".join(result)
101-
102-
10320
def check_solution_exists(problem_number: int, solutions_dir: Path) -> bool:
10421
"""Check if solution exists for a problem number."""
10522
solution_path = solutions_dir / str(problem_number) / "01.py"

scripts/normalize_json.py

Lines changed: 4 additions & 74 deletions
Original file line numberDiff line numberDiff line change
@@ -2,9 +2,8 @@
22

33
"""
44
Reads a JSON file, sorts its top-level keys numerically,
5-
and writes the sorted data to a new JSON file following Prettier style.
6-
7-
Prettier config: printWidth=150, tabWidth=2, useTabs=false, trailingComma=es5, bracketSpacing=false
5+
and writes the sorted data to a new JSON file.
6+
Prettier will format the output according to .prettierrc config.
87
98
python scripts/normalize_json.py data/leetcode-problems.json
109
"""
@@ -15,66 +14,6 @@
1514
from collections import OrderedDict
1615

1716

18-
def format_json_value(value, indent_level=0, print_width=150):
19-
"""Format a JSON value with custom formatting following Prettier style."""
20-
indent = " " * indent_level
21-
next_indent = " " * (indent_level + 1)
22-
23-
if isinstance(value, dict):
24-
if not value:
25-
return "{}"
26-
items = []
27-
for k, v in sorted(value.items()):
28-
formatted_key = json.dumps(k, ensure_ascii=False)
29-
formatted_value = format_json_value(v, indent_level + 1, print_width)
30-
items.append(f"{next_indent}{formatted_key}: {formatted_value}")
31-
return "{\n" + ",\n".join(items) + "\n" + indent + "}"
32-
elif isinstance(value, list):
33-
if not value:
34-
return "[]"
35-
# Check if it's a list of numbers (for problems arrays) - format multiple per line
36-
if value and isinstance(value[0], (int, float)):
37-
# Calculate available width (print_width minus indentation and brackets)
38-
available_width = print_width - len(next_indent) - 2
39-
lines = []
40-
current_line = []
41-
current_length = 0
42-
43-
for i, item in enumerate(value):
44-
item_str = str(item)
45-
# Add comma and space length (2) if not first item on line
46-
item_length = len(item_str) + (2 if current_line else 0)
47-
48-
if current_length + item_length > available_width and current_line:
49-
# Start a new line
50-
lines.append(", ".join(str(x) for x in current_line))
51-
current_line = [item]
52-
current_length = len(item_str)
53-
else:
54-
current_line.append(item)
55-
current_length += item_length
56-
57-
if current_line:
58-
lines.append(", ".join(str(x) for x in current_line))
59-
60-
# Format with proper indentation
61-
formatted_lines = [f"{next_indent}{line}" for line in lines]
62-
return "[\n" + ",\n".join(formatted_lines) + "\n" + indent + "]"
63-
else:
64-
# Format other arrays - check if they fit on one line
65-
formatted_items = [format_json_value(item, indent_level + 1, print_width) for item in value]
66-
total_length = sum(len(str(item)) for item in formatted_items)
67-
if total_length < 100 and len(value) <= 5:
68-
# Short arrays on one line
69-
return "[" + ", ".join(str(item).replace("\n", " ") for item in formatted_items) + "]"
70-
else:
71-
# Long arrays with line breaks
72-
items = [f"{next_indent}{item}" for item in formatted_items]
73-
return "[\n" + ",\n".join(items) + "\n" + indent + "]"
74-
else:
75-
return json.dumps(value, ensure_ascii=False)
76-
77-
7817
def sort_json_by_numeric_keys(input_file, output_file):
7918
"""
8019
Sort JSON file by numeric keys and format according to Prettier style.
@@ -94,18 +33,9 @@ def sort_json_by_numeric_keys(input_file, output_file):
9433
sorted_items = sorted(data.items(), key=lambda item: int(item[0]))
9534
sorted_data = OrderedDict(sorted_items)
9635

97-
# Format the JSON with custom formatting following Prettier style
98-
lines = ["{"]
99-
items = []
100-
for key, value in sorted_data.items():
101-
formatted_key = json.dumps(key, ensure_ascii=False)
102-
formatted_value = format_json_value(value, 1, print_width=150)
103-
items.append(f' {formatted_key}: {formatted_value}')
104-
lines.append(",\n".join(items))
105-
lines.append("}")
106-
36+
# Write JSON (Prettier will format it)
10737
with open(output_file, "w", encoding="utf-8") as f:
108-
f.write("\n".join(lines) + "\n")
38+
json.dump(sorted_data, f, ensure_ascii=False)
10939

11040
# Format with prettier
11141
try:

0 commit comments

Comments
 (0)