Map one of tuple elements

Viewed 61

Is it possible to map one of elements of a tuple simply in typescript? I'm looking for a gentle abstraction over the following operation

const arr: [string, string][] = [['a', 'b'], ['c', 'd'], ['e', 'f']]

const f = (str: string): number => str.length

arr.map((row) => [row[0], f(row[1])])

my first attempt was to implement it like

function mapSnd<A, B, C>(arr: [A, B][], f: (B) => C): [A, C][] {
    return arr.map((row) => [row[0], f(row[1])])
}

but it doesn't scale up well (for three elements tuple i would need to define new set of functions and so on), so I'm looking for a generic solution

3 Answers

You typed great function but there is a little problem simple - you used B as a parameter name, not type. Use this:

const arr: [string, string][] = [['a', 'b'], ['c', 'd'], ['e', 'f']]
function mapSnd<A, B, C>(arr: [A, B][], f: (second: B) => C): [A, C][] {
    return arr.map(row => [row[0], f(row[1])]);
}
const res = mapSnd(arr, second => second.length); // [string, number][]

And for more like mapThrd without separate, there is no way, sorry.

Here is a solution that will allow an arbitrary n-tuple to be used:

const arr: [string, string, string][] = [['a', 'bb', 'zzz'], ['c', 'ddd', 'qqqq'], ['e', 'ffff', 'rrrrr']]

const f = (str: string[]): number[] => str.map(s=>s.length);

const map = new Map();

arr.forEach(row => map.set(row.shift(), f(row)));

for (let [key, value] of map.entries()) {
  console.log(key + ' = ' + value)
}

I found the solution! But some changes appeared to your array.

const arr = [['a', 'b'], ['c', 'd'], ['e', 'f']]

function map<A extends any[], I extends number, C>(index: I, array: A[], f: (el: A[I]) => C) {
    return array.map(row => {
        const newRow = [...row];
        row[index] = f(row[index]);
        return newRow as A & Record<I, C>;
    })
}

const string = map(0, arr, str => str.length)[0][1];
const number = map(0, arr, str => str.length)[0][0];
Related