Compilation of different programming
projects I amuse myself with.
Monday, 1 March 2021
Implementing ToDictionary in Typescript
In this article I will present some code I just did in my SimpleTsLinq library, which you can easily install using Npm.
The library is here on Npmjs.com :
The ToDictionary method looks like this:
if (!Array.prototype.ToDictionary) {
Array.prototype.ToDictionary = function <T>(keySelector: (arg: T) =>any): any {
let hash = {};
this.map(item => {
let key = keySelector(item);
if (!(key in hash)) {
hash[key] = item;
}
else {
if (!(Array.isArray(hash[key]))) {
hash[key] = [hash[key]];
}
hash[key].push(item);
}
});
return hash;
}
}
Npm runkit link:
ReplyDeletehttps://npm.runkit.com/simpletslinq