Type Coercion Comparator
Difficulty: Medium · Topics: Edge Cases, Comparison, Type System
Difficulty: Medium | Tags: Edge Cases, Comparison, Type System
Description
Implement a comparator that can meaningfully compare values of different types. This is useful when comparing JSON values where numbers might come as strings, booleans as "true"/"false" strings, etc.
Implement:
flexibleEquals(value1, value2) → boolean
flexibleCompare(value1, value2) → int // -1, 0, 1
Coercion rules (in priority order):
null equals null, but null ≠ anything else.Examples
Example 1:
Input: flexibleEquals(42, "42")
Output: true
Example 2:
Input: flexibleEquals(true, "TRUE")
Output: true
Example 3:
Input: flexibleEquals(1.0, 1)
Output: true
Example 4:
Input: flexibleEquals(null, "null")
Output: false
Explanation: null only equals null, not the string "null".
Example 5:
Input: flexibleCompare("10", 9)
Output: 1 (10 > 9)
Example 6:
Input: flexibleEquals("abc", 123)
Output: false
Explanation: String "abc" can't be parsed as number → not equal.
Constraints
- Supported types: String, Integer, Long, Float, Double, Boolean, null.
- String-to-number parsing failure → values are not equal.
- Comparison is symmetric:
compare(a, b)must be consistent withcompare(b, a).
---
## Concurrency