Last active
April 28, 2021 12:56
-
-
Save VaskillerDev/ff6c757ab5a52d0d65898016268ad5f4 to your computer and use it in GitHub Desktop.
groupBy(arr, func) on typescript
This file contains 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
type FunctionTypeAsKey = number | string; | |
type ClusterFuncSignature<T> = (e: T) => FunctionTypeAsKey; | |
type Group<T> = { | |
[k in FunctionTypeAsKey] : Array<T> | |
} | |
function groupBy<T> (arr : Array<T>, func : ClusterFuncSignature<T>) { | |
const result = Object.create(null) as Group<T>; | |
arr.forEach(elem => { | |
let key : FunctionTypeAsKey = func(elem); | |
const val : T = elem; | |
key = (key === "__proto__" ? "_proto_" : key); | |
(result[key] = result[key] || []).push(val); | |
}) | |
Object.keys(result).forEach(key => result[key] === undefined ? delete result[key] : {}); // del all undefined props | |
return {...result} | |
} | |
{ | |
const calcResult = groupBy([1.2, 1.1, 2.3, 0.4], Math.floor); | |
const result = { | |
"0": [0.4], | |
"1": [1.2, 1.1], | |
"2": [2.3], | |
}; | |
console.log("eq first test: ", JSON.stringify(calcResult) === JSON.stringify(result)); | |
} | |
{ | |
const calcResult = groupBy(["one", "two", "three"], (el) => el.length); | |
let result = { | |
"3": ["one", "two"], | |
"5": ["three"], | |
}; | |
console.log("eq second test: ", JSON.stringify(calcResult) === JSON.stringify(result)); | |
} | |
{ | |
enum Gender { | |
Male, | |
Female, | |
} | |
const calcResult = groupBy( | |
[ | |
{ g: Gender.Male, n: "A" }, | |
{ g: Gender.Female, n: "B" }, | |
{ g: Gender.Female, n: "C" }, | |
], | |
(el) => el.g | |
); | |
let result = { | |
[Gender.Male]: [{ g: Gender.Male, n: "A" }], | |
[Gender.Female]: [ | |
{ g: Gender.Female, n: "B" }, | |
{ g: Gender.Female, n: "C" }, | |
], | |
}; | |
console.log("eq third test: ", JSON.stringify(calcResult) === JSON.stringify(result)); | |
} | |
{ | |
const calcResult = groupBy([1,2,3], () => 'toString'); | |
let result = { | |
"toString": [1,2,3] | |
} | |
console.log("eq fourth test: ", JSON.stringify(calcResult) === JSON.stringify(result)); | |
} | |
{ | |
const calcResult = groupBy([1,2,3], () => '__proto__'); | |
let result = { | |
"_proto_": [1,2,3] | |
} | |
console.log("eq fifth test: ", JSON.stringify(calcResult) === JSON.stringify(result)); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment