Move value compaction to its own function.
Process element keys in sorted order when expanding.
Update flatten implementation to come more inline with spec.