U rock
U rock

Reputation: 775

Reverse mapping using array from

I have a set of Map data which I need to use both ways; here is an example:

const mapping: Map<string, string> = new Map<string, string>([
    ['one', '1'],
    ['two', '2'],
    ['three', '3'],
    ['four', '4'],
]);

// I should eliminate this; I want to write it with single-line syntax
const reverseMapping: Map<string, string> = new Map<string, string>([
    ['1', 'one'],
    ['2', 'two'],
    ['3', 'three'],
    ['4', 'four'],
]);

const data = Array.from(mapping).map(e => e.reverse());

const reverseMap: Map<string, string> = new Map<string, string>([data])

I can't figure out syntax-wise how to do this; how would I do this?

https://stackblitz.com/edit/typescript-d7jocb

Upvotes: 1

Views: 107

Answers (1)

jcalz
jcalz

Reputation: 330161

A one-liner that works at both runtime and with the compiler is this:

const flipMap = <K, V>(m: Map<K, V>) => new Map(Array.from(m, ([k, v]) => [v, k]));
// const flipMap: <K, V>(m: Map<K, V>) => Map<V, K>

For your particular map you could do this:

const reverseMapping = new Map(Array.from(mapping, ([k, v]) => [v, k])); 
// const reverseMapping: Map<string, string>

Let's test it:

console.log(mapping); // Map(4) { one → "1", two → "2", three → "3", four → "4" }
console.log(reverseMapping); // { 1 → "one", 2 → "two", 3 → "three", 4 → "four" }

Looks good to me. Hope that helps; good luck!

Playground link to code

Upvotes: 4

Related Questions