Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
228 views
in Technique[技术] by (71.8m points)

javascript - Map one of tuple elements

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

question from:https://stackoverflow.com/questions/65862559/map-one-of-tuple-elements

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...