An extension of the Map class with more Array-like features.

Overview

BetterMap

An extension of the Map class with more Array-like features.

Installation

There ain't no installation. It's a Deno module.

Usage

import { BetterMap } from "https://deno.land/x/bettermap/mod.ts";

const b = new BetterMap<string, unknown>();

class BetterMap<K, V> extends Map<K, V>

constructor(name?: string)

Create a new BetterMap

Param: name: string - A friendly name for the BetterMap

Returns: Array of items in the map

array(keys: boolean): K[]

array(keys): K[] | V[]

Convert the map into an array of values / keys

b.array();
// Array of values

at(pos: number): V | undefined

Return the nth element of the map.

Param: pos: number - Position to get data.

Returns: {V} - Item at specified index.

b.at(-9);
{ name: "Spectrier", tier: "normal", id: 897 }

every(fn: (v: V, k: K) => boolean): boolean

Array#every but for a Map

Param: fn - Function to run on every element.

Returns: {boolean} - True or false

b.every((x) => x.tier === "mythic");
false;

filter(fn: (v: V, k: K) => boolean): BetterMap<K, V>

Filter elements that do not pass the condition.

Param: fn - Function to be passed.

Returns: {BetterMap} - BetterMap with elements that passed.

b.filter((x) => x.tier === "mythic");
Map {
  "Mew" => { name: "Mew", tier: "mythic", id: 151 },
  "Celebi" => { name: "Celebi", tier: "mythic", id: 251 },
  "Jirachi" => { name: "Jirachi", tier: "mythic", id: 385 },
  "Deoxys" => { name: "Deoxys", tier: "mythic", id: 386 },
  "Phione" => { name: "Phione", tier: "mythic", id: 489 },
  "Manaphy" => { name: "Manaphy", tier: "mythic", id: 490 },
  "Darkrai" => { name: "Darkrai", tier: "mythic", id: 491 },
  "Shaymin" => { name: "Shaymin", tier: "mythic", id: 492 },
  "Arceus" => { name: "Arceus", tier: "mythic", id: 493 },
  "Victini" => { name: "Victini", tier: "mythic", id: 494 },
  "Keldeo" => { name: "Keldeo", tier: "mythic", id: 647 },
  "Meloetta" => { name: "Meloetta", tier: "mythic", id: 648 },
  "Genesect" => { name: "Genesect", tier: "mythic", id: 649 },
  "Diancie" => { name: "Diancie", tier: "mythic", id: 719 },
  "Hoopa" => { name: "Hoopa", tier: "mythic", id: 720 },
  "Volcanion" => { name: "Volcanion", tier: "mythic", id: 721 },
  "Magearna" => { name: "Magearna", tier: "mythic", id: 801 },
  "Marshadow" => { name: "Marshadow", tier: "mythic", id: 802 },
  "Zeraora" => { name: "Zeraora", tier: "mythic", id: 807 },
  "Meltan" => { name: "Meltan", tier: "mythic", id: 808 },
  "Melmetal" => { name: "Melmetal", tier: "mythic", id: 809 },
  "Zarude" => { name: "Zarude", tier: "mythic", id: 893 }
}

find(fn: (v: V, k: K) => boolean): V | undefined

Param: fn - Function to be passed.

Returns: A value from the map. If none found, returns undefined.

b.find((x) => x.tier === "mythic");
{ name: "Mew", tier: "mythic", id: 151 }

findKey(fn: (v: V, k: K) => boolean): K | undefined

Param: fn - Function to be passed.

Returns: A key from the map. If none found, returns undefined.

b.findKey((x) => x.tier === "mythic");
"Mew";

first(): V | undefined

first(n: number): V[]

first(n?: number): V | V[] | undefined

Get the first element(s) from the map.

Param: n: number - Number of elements to fetch.

Returns: The first element / undefined.

b.first();
{ name: "Bulbasaur", tier: "normal", id: 1 }

firstKey(): K | undefined

Get the first (n) element's key from the map.

Param: n: number - Number of elements to fetch.

Returns: The first element's key / undefined.

b.first();
"Bulbasaur";

json(): Record<string, V>

Convert the key-value pairs into key-value pairs... I mean a JavaScript object.

Returns: {Record<string, V>} - keyAt(pos: number): K | undefined` Return the nth key of the map.

Param: pos: number - Position to get data.

Returns: {K} - Key at specified index.

last(): V | undefined

last(n: number): V[]

last(n?: number): V | V[] | undefined

Get last value(s) in the Map.

b.last();
{ name: "Enamorus", tier: "normal", id: 905 }

lastKey(): K | undefined

lastKey(n: number): K[]

lastKey(n?: number): K | K[] | undefined

Get last key(s) in the Map.

b.first();
"Enamorus";

map(fn: (v: V, k: K) => T): T[] | []

Map the Map into an Array.

Param: fn - Function for mapping.

Returns: {T[]} - Array.

b.map((x) => x.id);

random(): V | undefined

random(count: number): V[]

random(count?: number): V | undefined | V[]

Get a random element from the BetterMap.

Returns: {boolean} - True or false

b.random();
b.random(5);

randomKey(): K | undefined

Get a random key from the BetterMap.

Returns: {boolean} - True or false

randomKey(count: number): K[]

randomKey(count?: number): K | undefined | K[]

reduce(fn: (acc: T, val: [K, V]) => T, first: T): T

Reduce data in the map.

Param: fn - Reducer function.

Returns: {T} - Reduced data.

b.randomKey();
b.randomKey(5);

some(fn: (val: V, key: K) => boolean): boolean

Check if at least one entry from the Map passes the function.

Param: fn - Function to run on every element.

Returns: {boolean} - True or false

b.some((x) => x.tier === "mythic");
true;

sort(fn: (v1: V, v2: V, k1: K, k2: K) => number): BetterMap<K, V>

Sort elements in the better map.

Param: fn - Function to use for sorting.

Returns: {BetterMap<K, V>} - sorted BetterMap.

b.sort((a, b) => a.name.toLowerCase().localeCompare(b.name.toLowerCase()));
Map {
  "Abomasnow" => { name: "Abomasnow", tier: "normal", id: 460 },
  "Abra" => { name: "Abra", tier: "normal", id: 63 },
  "Absol" => { name: "Absol", tier: "normal", id: 359 },
  "Accelgor" => { name: "Accelgor", tier: "normal", id: 617 },
  "Aegislash" => { name: "Aegislash", tier: "normal", id: 681 },
  "Aerodactyl" => { name: "Aerodactyl", tier: "normal", id: 142 },
  "Aggron" => { name: "Aggron", tier: "normal", id: 306 },
  "Aipom" => { name: "Aipom", tier: "normal", id: 190 },
  "Alakazam" => { name: "Alakazam", tier: "normal", id: 65 },
  "Alcremie" => { name: "Alcremie", tier: "normal", id: 869 },
  "Alomomola" => { name: "Alomomola", tier: "normal", id: 594 },
  ...
}

toString(): string

Stringify the map.

toJSON(): Record<string, V>

Duplicate of BetterMap#json

Returns: {Record<string, V>} -

transform(fn: (v: V, k: K) => T): BetterMap<K, T>

Transform values of the map. Similar to map() but returns a BetterMap instead.

Param: fn - Function for mapping.

Returns: BetterMap<K, T>

static from(data: Map<K1, V1> | [K1, V1][]): BetterMap<K1, V1>

Create a new map from an existing Map or an array of key-value pairs

Param: data - Existing Map / Array of Key-Value pairs.

Returns: {BetterMap<K1, V1>}

const obj = {
  "Mew": { name: "Mew", tier: "mythic", id: 151 },
  "Celebi": { name: "Celebi", tier: "mythic", id: 251 },
  "Jirachi": { name: "Jirachi", tier: "mythic", id: 385 },
};

BetterMap.from(Object.entries(obj))
Map {
  "Mew" => { name: "Mew", tier: "mythic", id: 151 },
  "Celebi" => { name: "Celebi", tier: "mythic", id: 251 },
  "Jirachi" => { name: "Jirachi", tier: "mythic", id: 385 },
}

Support

Do open a new issue or pr regarding bugs or improvements.

Join our Discord server!

You might also like...

Fundamentos, estruturas, função, objeto, array e etc...

JavaScript Fundamentos, estruturas, função, array e etc... Atividades praticas detalhadas e comentadas para todo mundo entender cada tag, bons estudos

Feb 27, 2022

Complete JavaScipt Array methods Cheatsheet 🚀

Complete JavaScipt Array methods Cheatsheet 🚀

Javascript Array Cheatsheet 👾 Click to download ☝ Important 🚨 There is no way this is perfect or include all the methods. I'll try to fix/add more m

Dec 7, 2022

Draft specification for a proposed Array.fromAsync method in JavaScript.

Array.fromAsync for JavaScript ECMAScript Stage-1 Proposal. J. S. Choi, 2021. Specification available Polyfill available Why an Array.fromAsync method

Dec 14, 2022

Analisador de números utilizando Array JavaScript com Html 5 e CSS 3

Olá pessal, tudo bem? :D Esse site foi desenvolvido para analisar números armazenados em um array chamado "dados[]". Temos dois botões um input e uma

Jan 6, 2022

Hierarchical Converter for Array of Objects

Conversor Hierárquico para Array de Objetos - Hierarchical Converter to Array of Objects Docker-compose Cria a interface network e containers indicado

Jan 27, 2022

A simple module to get porperties of an array

A simple module to get statistical porperties of an array. Currently the possible properties are mean, stdev and variance.

Nov 29, 2022

Useful for managing a wrapping index for an array of items.

use-wrapping-index Useful for managing a wrapping index for an array of items. Usage import useWrappingIndex from "@alexcarpenter/use-wrapping-index";

Dec 9, 2022

Converts an iterable, iterable of Promises, or async iterable into a Promise of an Array.

iterate-all A utility function that converts any of these: IterableT IterablePromiseT AsyncIterableT AsyncIterablePromiseT Into this: Prom

Jun 7, 2022

Práctica sobre métodos de array

Práctica de Arrays Este es el repositorio de acompañamiento de este stream. Si querés saber más sobre Arrays podes visitar la MDN en su artículo de pr

Dec 28, 2022
Comments
  • Dev

    Dev

    Describe your PR:

    • Add split() method to segregate items in the map.
    • Add union and intersect static methods to create a new map using multiple existing maps.
    opened by retraigo 0
Releases(v1.3.0)
  • v1.3.0(Sep 3, 2022)

    What's Changed

    • Dev by @retraigo in https://github.com/retraigo/bettermap/pull/6
    • feat: Add JSDoc examples and documentation link in README by @retraigo in https://github.com/retraigo/bettermap/pull/7

    Full Changelog: https://github.com/retraigo/bettermap/compare/v1.2.1...v1.3.0

    Source code(tar.gz)
    Source code(zip)
  • v1.2.0(Jul 4, 2022)

    What's Changed

    • feat: more methods by @retraigo in https://github.com/nekooftheabyss/bettermap/pull/4

    Full Changelog: https://github.com/nekooftheabyss/bettermap/compare/v1.1.1...v1.2.0

    Source code(tar.gz)
    Source code(zip)
  • v1.1.1(Jun 20, 2022)

    What's Changed

    • fix json() by @retraigo in https://github.com/nekooftheabyss/bettermap/pull/3

    Full Changelog: https://github.com/nekooftheabyss/bettermap/compare/v1.1.0...v1.1.1

    Source code(tar.gz)
    Source code(zip)
  • v1.1.0(Jun 15, 2022)

    What's Changed

    • feat: add at() method. by @retraigo in https://github.com/nekooftheabyss/bettermap/pull/2

    Full Changelog: https://github.com/nekooftheabyss/bettermap/compare/v1.0.2...v1.1.0

    Source code(tar.gz)
    Source code(zip)
  • v1.0.2(Jun 11, 2022)

    What's Changed

    • patch: better typings by @retraigo in https://github.com/retraigo/bettermap/pull/1

    New Contributors

    • @retraigo made their first contribution in https://github.com/retraigo/bettermap/pull/1

    Full Changelog: https://github.com/retraigo/bettermap/compare/v1.0.1...v1.0.2

    Source code(tar.gz)
    Source code(zip)
  • v1.0.1(Jun 4, 2022)

  • v1.0.0(May 28, 2022)

Owner
Neko Of The Abyss
Maintaining random open-source TypeScript and JavaScript projects, created by @retraigo.
Neko Of The Abyss
🎲 Extract one or more random elements from a weighted array (aka loot table or gacha)

wrand Extract one or more random elements from a weighted array. const items = [ { original: "Bronze", weight: 20 }, { original: "Silver", weight:

Leonardo Montini 14 Dec 2, 2022
🧰 Javascript array-like containers for multithreading

بسم الله الرحمن الرحيم Struct Vec ?? Javascript array-like containers for multithreading Efficiently communicating between js workers is a pain becaus

Mostafa Elbannan 19 Jun 23, 2022
we learn the whole concept of JS including Basics like Object, Functions, Array etc. And Advance JS - Understanding DOMs, JQuery, Ajax, Prototypes etc.

JavaScript-for-Complete-Web Development. we learn the whole concept of JS including Basics like Object, Functions, Array etc. And Advance JS - Underst

prasam jain 2 Jul 22, 2022
Very tiny function that checks if an object/array/value is shaped like another, with TypeScript type refining.

@suchipi/has-shape Very tiny (~200B before minification/compression) function that checks if an object/array/value is shaped like another, with TypeSc

Lily Skye 7 Aug 13, 2022
VSCode extension to paste text as a string array

VSCode extension to paste text as a string array. This is useful when copying command line into launch.json args

Shady Boukhary 4 Dec 28, 2022
A set of utilities and additional features for my creative coding class aiming to help students while introducing the algorithmic thinking.

p5.utils A set of utilities and additional features for my creative coding class aiming to help students while introducing the algorithmic thinking. T

alp tuğan 15 Dec 25, 2022
Cross-browser plugin to remove addictive features on YouTube like thumbnails, comments, previews and more...

ZenTube Installation Features Remove some (more) elements from Youtube to make it less addictive. Mix and match between the following options: Hide or

inversepolarity 57 Dec 17, 2022
A JavaScript lib with more functions for the normal Date class.

A JavaScript lib with more functions for the normal Date class.

Ícaro Gabriel 4 Jan 26, 2022
Explore Alveus Sanctuary with an interactive map and find out more about the different buildings on the property.

Alveus Sanctuary Interactive Map Explore Alveus Sanctuary with an interactive map and find out more about the different buildings on the property. htt

Matt Cowley 3 Aug 16, 2022
A work-in-progress HTML sanitizer that strives for: performance like window.Sanitizer, readiness like DOMPurify, and ability to run in a WebWorker like neither of those.

Amuchina A work-in-progress HTML sanitizer that strives for: performance like window.Sanitizer, readiness like DOMPurify, and ability to run in a WebW

Fabio Spampinato 9 Sep 17, 2022