init at work

This commit is contained in:
Mathias Schneider
2026-03-27 12:58:01 +01:00
parent 352c352056
commit 8d40597732
60 changed files with 16498 additions and 0 deletions
+29
View File
@@ -0,0 +1,29 @@
# TypeScript Learning Index (Python -> TypeScript)
## Foundations
- `01-function-declaration-syntax.md`
- `02-const-and-assignment.md`
- `03-dot-access-and-method-calls.md`
- `04-array-find-and-arrow-functions.md`
- `05-strict-equality-operator.md`
- `06-optional-chaining-operator.md`
- `07-nullish-coalescing-operator.md`
- `08-string-literals.md`
- `09-template-literals.md`
- `10-semicolons.md`
- `11-robust-formatting-style.md`
- `12-python-to-typescript-mini-map.md`
## Date/Interval Logic from your code
- `13-optional-params-and-default-values.md`
- `14-return-type-array-strings.md`
- `15-array-slice-and-indexing.md`
- `16-timestamps-with-gettime.md`
- `17-guard-clauses-and-range-validation.md`
- `18-flatmap-filter-and-map-pattern.md`
- `19-iso-strings-and-template-literals.md`
- `20-alignedstarts-concept.md`
Recommended order: start at `01`, then jump to `13-20` while reading `jsonDownload.ts`.
+28
View File
@@ -0,0 +1,28 @@
# Function Declaration Syntax in TypeScript
A function declaration defines a reusable block of logic with typed inputs and output.
## Basic Shape
```ts
function greet(name: string): string {
return `Hello, ${name}`;
}
```
## Parts Explained
- `function`: keyword to declare a function.
- `greet`: function name.
- `(name: string)`: parameter list with a type annotation.
- `: string`: return type annotation.
- `{ ... }`: function body.
## Python Comparison
```py
def greet(name: str) -> str:
return f"Hello, {name}"
```
TypeScript puts type annotations after variable names as `name: string`, similar to Python type hints.
+31
View File
@@ -0,0 +1,31 @@
# `const` and Assignment
TypeScript uses `const`, `let`, and `var` for variable declarations. Modern code usually prefers `const` and `let`.
## `const`
```ts
const apiBase = 'https://example.com';
```
- `const` means the binding cannot be reassigned.
- You can still mutate object contents unless frozen.
```ts
const config = { retries: 2 };
config.retries = 3; // allowed
// config = {}; // not allowed
```
## Assignment Operator `=`
```ts
let count = 0;
count = count + 1;
```
- `=` assigns a new value to a variable.
## Python Comparison
Python has no enforced `const`; TypeScript enforces no-reassign when `const` is used.
+31
View File
@@ -0,0 +1,31 @@
# Dot Access and Method Calls
Dot notation accesses properties and methods on objects.
## Property Access
```ts
const user = { name: 'Mathias', age: 30 };
console.log(user.name); // 'Mathias'
```
## Method Call
```ts
const text = 'hello';
console.log(text.toUpperCase()); // 'HELLO'
```
In your code:
```ts
backendPeriodLabelFormatter.formatToParts(date)
```
- `backendPeriodLabelFormatter` is an object.
- `formatToParts` is a method.
- `(date)` passes the argument.
## Python Comparison
Equivalent idea to `obj.attr` and `obj.method(arg)`.
+36
View File
@@ -0,0 +1,36 @@
# Array `find` and Arrow Functions
`Array.prototype.find` returns the first element that matches a condition.
## Example
```ts
const parts = [
{ type: 'year', value: '2026' },
{ type: 'month', value: '03' },
{ type: 'day', value: '24' },
];
const yearPart = parts.find((part) => part.type === 'year');
console.log(yearPart); // { type: 'year', value: '2026' }
```
## Arrow Function Syntax
```ts
(part) => part.type === 'year'
```
- `(part)`: parameter.
- `=>`: arrow token.
- `part.type === 'year'`: expression result (`true` or `false`).
If no item matches, `find` returns `undefined`.
## Python Comparison
Similar to:
```py
year_part = next((p for p in parts if p['type'] == 'year'), None)
```
+23
View File
@@ -0,0 +1,23 @@
# Strict Equality Operator `===`
TypeScript/JavaScript have both `==` and `===`.
Use `===` for predictable behavior.
## Examples
```ts
1 === 1; // true
1 === '1'; // false
0 === false; // false
```
`===` compares both value and type, and avoids implicit coercion.
## Why it matters
Using `===` prevents subtle bugs caused by automatic conversions.
## Python Comparison
Closest to Python `==`, which does not coerce strings/numbers the JavaScript way.
+29
View File
@@ -0,0 +1,29 @@
# Optional Chaining Operator `?.`
Optional chaining safely accesses properties/methods when a value might be `null` or `undefined`.
## Property Access
```ts
const user: { profile?: { city?: string } } = {};
const city = user.profile?.city;
console.log(city); // undefined
```
## Method Call
```ts
const maybeFn: undefined | (() => string) = undefined;
const value = maybeFn?.();
console.log(value); // undefined
```
Without `?.`, these would throw runtime errors.
## Python Comparison
Similar intent to:
```py
city = user.profile.city if user and user.profile else None
```
+23
View File
@@ -0,0 +1,23 @@
# Nullish Coalescing Operator `??`
`??` provides a fallback only when the left side is `null` or `undefined`.
## Example
```ts
const maybeName: string | undefined = undefined;
const name = maybeName ?? 'anonymous';
console.log(name); // 'anonymous'
```
## Difference from `||`
```ts
'' || 'fallback'; // 'fallback'
'' ?? 'fallback'; // ''
```
- `||` treats many falsy values as missing (`''`, `0`, `false`).
- `??` treats only `null` and `undefined` as missing.
In your formatter code, `?? ''` is used as a safe fallback.
+23
View File
@@ -0,0 +1,23 @@
# String Literals
String literals are text values written directly in code.
## Examples
```ts
const a = 'year';
const b = "month";
const c = '';
```
`''` is an empty string.
## Typical Uses
- Labels and constants.
- Comparisons.
- Fallback values.
## Good Practice
Keep quote style consistent with project conventions.
+28
View File
@@ -0,0 +1,28 @@
# Template Literals
Template literals are strings enclosed by backticks and support interpolation.
## Syntax
```ts
const year = '2026';
const month = '03';
const day = '24';
const label = `${year}-${month}-${day}`;
console.log(label); // '2026-03-24'
```
## Why use them
- Easier than concatenation.
- More readable for multi-part strings.
- Supports multiline text.
## Python Comparison
Equivalent concept to Python f-strings:
```py
label = f"{year}-{month}-{day}"
```
+17
View File
@@ -0,0 +1,17 @@
# Semicolons in TypeScript
Semicolons terminate statements.
## Example
```ts
const x = 1;
const y = 2;
const z = x + y;
```
JavaScript has automatic semicolon insertion, but many teams still use explicit semicolons for consistency and fewer edge-case surprises.
## Recommendation
Follow the style already used in your repository.
+23
View File
@@ -0,0 +1,23 @@
# Why This Formatting Pattern Is Robust
The pattern in your code combines `find`, `?.`, and `??`:
```ts
const year = parts.find((part) => part.type === 'year')?.value ?? '';
```
## Why this is robust
- `find(...)` may return `undefined`.
- `?.value` prevents a crash when no part exists.
- `?? ''` guarantees a string fallback.
This keeps `formatPeriodStartLabel(...)` stable even when input parts are incomplete.
## End-to-End Example
```ts
function safePart(parts: Intl.DateTimeFormatPart[], wanted: string): string {
return parts.find((p) => p.type === wanted)?.value ?? '';
}
```
+56
View File
@@ -0,0 +1,56 @@
# Python to TypeScript Mini Map
Quick syntax map for common constructs.
## Function typing
```py
def fn(x: int) -> str:
return str(x)
```
```ts
function fn(x: number): string {
return String(x);
}
```
## Lambda / Arrow
```py
lambda x: x + 1
```
```ts
(x) => x + 1
```
## Fallback for missing values
```py
value = x if x is not None else 'fallback'
```
```ts
const value = x ?? 'fallback';
```
## String interpolation
```py
f"{year}-{month}-{day}"
```
```ts
`${year}-${month}-${day}`
```
## Searching first match
```py
next((p for p in parts if p['type'] == 'year'), None)
```
```ts
parts.find((p) => p.type === 'year')
```
+32
View File
@@ -0,0 +1,32 @@
# Optional Parameters and Default Values in TypeScript
In TypeScript, a function parameter can be optional and can also have a default value.
## Example from your code
```ts
function buildWeeklyDownloadPeriods(
dateRange?: DownloadDateRange,
now = new Date(),
): string[] {
// ...
}
```
## What this means
- `dateRange?`:
- The `?` means this argument is optional.
- The caller can omit it.
- `now = new Date()`:
- If caller does not pass `now`, TypeScript uses `new Date()`.
## Python comparison
```py
def build_weekly_download_periods(date_range=None, now=None):
if now is None:
now = datetime.now()
```
TypeScript default parameters are cleaner because the default is declared directly in the signature.
+27
View File
@@ -0,0 +1,27 @@
# Return Type `string[]`
TypeScript can declare exactly what a function returns.
## Example
```ts
function buildWeeklyDownloadPeriods(...): string[] {
return ['2026-03-23T23:00:00.000Z/2026-03-30T22:00:00.000Z'];
}
```
## Meaning
- `string[]` means "array of strings".
- Each array item must be a `string`.
## Python comparison
```py
from typing import List
def build_weekly_download_periods(...) -> List[str]:
return ['a/b']
```
TypeScript enforces this statically, so returning non-strings will be flagged by the type checker.
+30
View File
@@ -0,0 +1,30 @@
# Array `slice` and Indexing
Your snippet uses `slice` and index-based access to create weekly intervals.
## `slice(0, -1)`
```ts
const periodStarts = alignedStarts.slice(0, -1);
```
- Start at index `0`.
- Stop before the last item (`-1` means from the end).
- Useful when each `start` needs a following `end` item.
## Index access
```ts
const end = alignedStarts[index + 1];
```
- Gets the next boundary after the current `start`.
## Python comparison
```py
period_starts = aligned_starts[:-1]
end = aligned_starts[index + 1]
```
This is the same concept as Python slicing and list indexing.
+28
View File
@@ -0,0 +1,28 @@
# Timestamps with `getTime()`
`Date.getTime()` returns a timestamp in milliseconds since Unix epoch.
## Example
```ts
const startTime = start.getTime();
```
## Why this is useful
Numeric timestamps are easy to compare:
```ts
startTime >= rangeStart
startTime <= rangeEnd
```
Comparing numbers is usually simpler and safer than comparing date strings directly.
## Python comparison
```py
start_ts_ms = int(start_dt.timestamp() * 1000)
```
Both represent an absolute moment in time.
+30
View File
@@ -0,0 +1,30 @@
# Guard Clauses and Range Validation
A guard clause exits early when input is invalid.
## Example from your snippet
```ts
if (rangeStart !== undefined && rangeEnd !== undefined && rangeStart > rangeEnd) {
return [];
}
```
## Why this is good
- Fails fast.
- Prevents harder-to-debug logic later.
- Keeps the main flow cleaner.
## Operator notes
- `!==`: strict "not equal" comparison.
- `&&`: logical AND (all conditions must be true).
- `>`: greater-than comparison.
## Python comparison
```py
if range_start is not None and range_end is not None and range_start > range_end:
return []
```
+38
View File
@@ -0,0 +1,38 @@
# `flatMap` as Filter + Map Pattern
`flatMap` can both remove items and transform remaining items.
## Pattern in your snippet
```ts
return periodStarts.flatMap((start, index) => {
if (!matchesRange) {
return [];
}
return `${start.toISOString()}/${end.toISOString()}`;
});
```
## How it works
- Return `[]` to drop an element.
- Return a value to keep/transform it.
- `flatMap` flattens one level automatically.
## Equivalent with `filter` + `map`
```ts
return periodStarts
.filter((start) => isInRange(start))
.map((start, index) => makeInterval(start, index));
```
## Python comparison
Usually done as separate steps:
```py
filtered = [s for s in period_starts if in_range(s)]
result = [make_interval(s, i) for i, s in enumerate(filtered)]
```
+23
View File
@@ -0,0 +1,23 @@
# ISO Strings and Template Literals
Your code builds interval strings using `toISOString()` and a template literal.
## Example
```ts
const interval = `${start.toISOString()}/${end.toISOString()}`;
```
## Why this format is good
- ISO format is unambiguous.
- Easy for backend APIs to parse.
- Includes timezone info (`Z` for UTC).
Example value:
```text
2026-03-23T23:00:00.000Z/2026-03-30T22:00:00.000Z
```
This describes one weekly period as `start/end`.
+26
View File
@@ -0,0 +1,26 @@
# Understanding `alignedStarts`
`alignedStarts` is an array of date boundaries that match your backend schedule rule.
## Concept
```ts
const alignedStarts: Date[] = [];
```
Each item is a valid period boundary (for example Monday 00:00 in backend-local schedule terms).
Later, you form intervals by pairing adjacent items:
```ts
const start = alignedStarts[index];
const end = alignedStarts[index + 1];
```
So if `alignedStarts` has `N` items, you can make up to `N-1` intervals.
## Why this is useful
- Keeps schedule boundaries consistent.
- Makes interval generation deterministic.
- Handles DST-safe boundaries when generated correctly.