Created
January 28, 2022 17:14
-
-
Save matfin/923c1dd9ce8af3b2fc2aecc7790421f4 to your computer and use it in GitHub Desktop.
Prioritise a nested array of items
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
// From: https://twitter.com/rauschma/status/1487086371760136195?s=20&t=z_0I28Cjhgn1igKt90qmrw | |
import assert from 'assert/strict'; | |
interface Character { | |
name: string; | |
} | |
interface PrioritisedItem { | |
name: string; | |
priority: number; | |
} | |
const prios: Character[][] = [ | |
[{ name: "Jane" }, { name: "Tarzan" }], | |
[{ name: "Cheetah" }], | |
]; | |
const prioResult: PrioritisedItem[] = [ | |
{ name: "Jane", priority: 1 }, | |
{ name: "Tarzan", priority: 1 }, | |
{ name: "Cheetah", priority: 2 }, | |
]; | |
const formatPrios = (data: Character[][]): PrioritisedItem[] => | |
data.reduce( | |
( | |
acc: PrioritisedItem[], | |
curr: Character[], | |
idx: number | |
): PrioritisedItem[] => { | |
const remapped: PrioritisedItem[] = curr.map( | |
(item: Character): PrioritisedItem => ({ ...item, priority: idx + 1 }) | |
); | |
return [...acc, ...remapped]; | |
}, | |
[] | |
); | |
assert.deepEqual( | |
prioResult, | |
formatPrios(prios) | |
); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment