EasyJavaScriptTypeScript

Generics — Identity, Constraint & Default

TypeScriptGenericsTypes

Implement three generic utilities:

1. `identity<T>(value: T): T` — returns the value as-is.
2. `first<T>(arr: T[]): T | null` — returns the first element, or null for empty arrays.
3. `merge<A, B>(a: A, b: B): A & B` — shallow-merges two objects.

Then implement solve(fn, ...args) that dispatches to the right function.

Examples

  • identity(42)42
  • first([1, 2, 3])1
  • first([])null
  • merge({ a: 1 }, { b: 2 }){ a: 1, b: 2 }

Sample tests

Test #1first — empty array returns undefined
Input: ["first",[]]
Output: null
Test #2merge — two objects
Input: ["merge",{"a":1},{"b":2}]
Output: {"a":1,"b":2}
Test #3identity — number
Input: ["identity",42]
Output: 42
Test #4identity — string
Input: ["identity","hello"]
Output: "hello"
Test #5first — non-empty array
Input: ["first",[1,2,3]]
Output: 1