Created
April 4, 2021 10:02
-
-
Save sobstel/f5a698b0c2379d5fadca23a702ca6426 to your computer and use it in GitHub Desktop.
Remeda mapDuplicates
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import mapDuplicates from "./mapDuplicates"; | |
describe("mapDuplicates", () => { | |
it("addresses duplicate surnames", () => { | |
const surnames = ["González", "González", "Martínez", "González"]; | |
expect( | |
mapDuplicates(surnames, (name, index) => `${name} ${index}`) | |
).toEqual(["González 0", "González 1", "Martínez", "González 3"]); | |
}); | |
}); |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* eslint-disable @typescript-eslint/no-use-before-define */ | |
/* eslint-disable @typescript-eslint/no-explicit-any */ | |
/* eslint-disable prefer-rest-params */ | |
import * as R from "remeda"; | |
type Fn = (name: string, index: number) => string; | |
export function mapDuplicates(shortNames: string[], fn: Fn): string[]; // data-first | |
export function mapDuplicates(fn: Fn): (shortNames: string[]) => string[]; // data-last | |
export function mapDuplicates(): any { | |
return R.purry(_mapDuplicates, arguments); | |
} | |
function _mapDuplicates(shortNames: string[], fn: Fn): string[] { | |
const counts = R.reduce( | |
shortNames, | |
(acc, name) => { | |
acc[name] = (acc[name] || 0) + 1; | |
return acc; | |
}, | |
{} as Record<string, number> | |
); | |
return R.map.indexed(shortNames, (name, index) => { | |
return counts[name] > 1 ? fn(name, index) : name; | |
}); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment