Create mapToArray util (#1742)
This is a fairly simple helper function that allows transforming a Map into an Array using a provided transformer function. It's really an alias for `Array.from(map.entries()).map(f)`, which is nice because that invocation is somewhat tedious to write. Test plan: The method is very simple; we've added some correspondingly simple test. Also, grepping for `Array\.from(.*\.entries())\.map` should return no hits (i.e. we've converted existing usage). Paired with @decentralion
This commit is contained in:
parent
b3d68546c9
commit
890222279a
|
@ -778,7 +778,8 @@ export class Mirror {
|
|||
])
|
||||
);
|
||||
}),
|
||||
Array.from(connectionsByObject.entries()).map(
|
||||
MapUtil.mapToArray(
|
||||
connectionsByObject,
|
||||
([id, {typename, connections}], i) => {
|
||||
const name = `${_FIELD_PREFIXES.NODE_CONNECTIONS}${i}`;
|
||||
return b.alias(
|
||||
|
|
|
@ -161,3 +161,14 @@ export function pushValue<K, V>(map: Map<K, V[]>, key: K, value: V): V[] {
|
|||
arr.push(value);
|
||||
return arr;
|
||||
}
|
||||
|
||||
/**
|
||||
* Given a Map, transform its entries into an Array using a
|
||||
* provided transformer function.
|
||||
*/
|
||||
export function mapToArray<K, V, R>(
|
||||
map: Map<K, V>,
|
||||
fn: (pair: [K, V], index: number) => R
|
||||
): R[] {
|
||||
return Array.from(map.entries()).map(fn);
|
||||
}
|
||||
|
|
|
@ -1,6 +1,7 @@
|
|||
// @flow
|
||||
|
||||
import * as MapUtil from "./map";
|
||||
import {mapToArray} from "./map";
|
||||
|
||||
describe("util/map", () => {
|
||||
describe("toObject", () => {
|
||||
|
@ -327,4 +328,43 @@ describe("util/map", () => {
|
|||
expect(result).toBe(arr);
|
||||
});
|
||||
});
|
||||
|
||||
describe("mapToArray", () => {
|
||||
const fn = ([key, val]) => ({key, val});
|
||||
|
||||
it("works for an empty map", () => {
|
||||
const map = new Map();
|
||||
|
||||
expect(mapToArray(map, fn)).toEqual([]);
|
||||
});
|
||||
|
||||
it("works for simple use case", () => {
|
||||
const map = new Map([
|
||||
["foo", 1],
|
||||
["bar", 2],
|
||||
]);
|
||||
|
||||
const expected = [
|
||||
{
|
||||
key: "foo",
|
||||
val: 1,
|
||||
},
|
||||
{
|
||||
key: "bar",
|
||||
val: 2,
|
||||
},
|
||||
];
|
||||
expect(mapToArray(map, fn)).toEqual(expected);
|
||||
});
|
||||
|
||||
it("should provide the index to the function", () => {
|
||||
const map = new Map([
|
||||
["foo", 1],
|
||||
["bar", 99],
|
||||
]);
|
||||
|
||||
const expected = [0, 1];
|
||||
expect(mapToArray(map, (_, i) => i)).toEqual(expected);
|
||||
});
|
||||
});
|
||||
});
|
||||
|
|
Loading…
Reference in New Issue