record.ts 1.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344
  1. /**
  2. * Converts an array of key-value tuples (for e.g ["key", "value"]), into a record.
  3. * (for eg. output -> { "key": "value" })
  4. * NOTE: This function will discard duplicate key occurances and only keep the last occurance. If you do not want that behaviour,
  5. * use `tupleWithSamesKeysToRecord`.
  6. * @param tuples Array of tuples ([key, value])
  7. * @returns A record with value corresponding to the last occurance of that key
  8. */
  9. export const tupleToRecord = <
  10. KeyType extends string | number | symbol,
  11. ValueType
  12. >(
  13. tuples: [KeyType, ValueType][]
  14. ): Record<KeyType, ValueType> =>
  15. tuples.length > 0
  16. ? (Object.assign as any)(...tuples.map(([key, val]) => ({ [key]: val }))) // This is technically valid, but we have no way of telling TypeScript it is valid. Hence the assertion
  17. : {}
  18. /**
  19. * Converts an array of key-value tuples (for e.g ["key", "value"]), into a record.
  20. * (for eg. output -> { "key": ["value"] })
  21. * NOTE: If you do not want the array as values (because of duplicate keys) and want to instead get the last occurance, use `tupleToRecord`
  22. * @param tuples Array of tuples ([key, value])
  23. * @returns A Record with values being arrays corresponding to each key occurance
  24. */
  25. export const tupleWithSameKeysToRecord = <
  26. KeyType extends string | number | symbol,
  27. ValueType
  28. >(
  29. tuples: [KeyType, ValueType][]
  30. ): Record<KeyType, ValueType[]> => {
  31. // By the end of the function we do ensure this typing, this can't be infered now though, hence the assertion
  32. const out = {} as Record<KeyType, ValueType[]>
  33. for (const [key, value] of tuples) {
  34. if (!out[key]) {
  35. out[key] = [value]
  36. } else {
  37. out[key].push(value)
  38. }
  39. }
  40. return out
  41. }