GithubHelp home page GithubHelp logo

hashmap's Introduction

HashMap Class for JavaScript

Installation

NPM

Using npm:

$ npm install hashmap

Using bower:

$ bower install hashmap

You can download the last stable version from the releases page.

If you like risk, you can download the latest master version, it's usually stable.

To run the tests:

$ npm test

Description

This project provides a HashMap class that works both on Node.js and the browser. HashMap instances store key/value pairs allowing keys of any type.

Unlike regular objects, keys will not be stringified. For example numbers and strings won't be mixed, you can pass Date's, RegExp's, DOM Elements, anything! (even null and undefined)

HashMap constructor overloads

  • new HashMap() creates an empty hashmap
  • new HashMap(map:HashMap) creates a hashmap with the key-value pairs of map
  • new HashMap(arr:Array) creates a hashmap from the 2D key-value array arr, e.g. [['key1','val1'], ['key2','val2']]
  • new HashMap(key:*, value:*, key2:*, value2:*, ...) creates a hashmap with several key-value pairs

HashMap methods

  • get(key:*) : * returns the value stored for that key.
  • set(key:*, value:*) : HashMap stores a key-value pair
  • multi(key:*, value:*, key2:*, value2:*, ...) : HashMap stores several key-value pairs
  • copy(other:HashMap) : HashMap copies all key-value pairs from other to this instance
  • has(key:*) : Boolean returns whether a key is set on the hashmap
  • search(value:*) : * returns key under which given value is stored (null if not found)
  • delete(key:*) : HashMap deletes a key-value pair by key
  • remove(key:*) : HashMap Alias for delete(key:*) (deprecated)
  • type(key:*) : String returns the data type of the provided key (used internally)
  • keys() : Array<*> returns an array with all the registered keys
  • values() : Array<*> returns an array with all the values
  • entries() : Array<[*,*]> returns an array with [key,value] pairs
  • size : Number the amount of key-value pairs
  • count() : Number returns the amount of key-value pairs (deprecated)
  • clear() : HashMap deletes all the key-value pairs on the hashmap
  • clone() : HashMap creates a new hashmap with all the key-value pairs of the original
  • hash(key:*) : String returns the stringified version of a key (used internally)
  • forEach(function(value, key)) : HashMap iterates the pairs and calls the function for each one

Method chaining

All methods that don't return something, will return the HashMap instance to enable chaining.

Examples

Assume this for all examples below

var map = new HashMap();

If you're using this within Node, you first need to import the class

var HashMap = require('hashmap');

Basic use case

map.set("some_key", "some value");
map.get("some_key"); // --> "some value"

Map size / number of elements

var map = new HashMap();
map.set("key1", "val1");
map.set("key2", "val2");
map.size; // -> 2

Deleting key-value pairs

map.set("some_key", "some value");
map.delete("some_key");
map.get("some_key"); // --> undefined

No stringification

map.set("1", "string one");
map.set(1, "number one");
map.get("1"); // --> "string one"

A regular Object used as a map would yield "number one"

Objects as keys

var key = {};
var key2 = {};
map.set(key, 123);
map.set(key2, 321);
map.get(key); // --> 123

A regular Object used as a map would yield 321

Iterating

map.set(1, "test 1");
map.set(2, "test 2");
map.set(3, "test 3");

map.forEach(function(value, key) {
    console.log(key + " : " + value);
});
// ES6 Iterators version
for (const pair of map) {
    console.log(`${pair.key} : ${pair.value}`)
}

Method chaining

map
  .set(1, "test 1")
  .set(2, "test 2")
  .set(3, "test 3")
  .forEach(function(value, key) {
      console.log(key + " : " + value);
  });

LICENSE

The MIT License (MIT)

Copyright (c) 2012 Ariel Flesler

Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF

To-Do

  • (?) Allow extending the hashing function in a AOP way or by passing a service
  • Make tests work on the browser

hashmap's People

Contributors

flesler avatar devoncrouse avatar thefourtheye avatar rafalwrzeszcz avatar ulikoehler avatar freddiecoleman avatar nathanjang avatar mvayngrib avatar psionski avatar fresheneesz avatar khrome avatar qbolec avatar

Stargazers

Adeline Wen avatar RyuYeonKyoung avatar  avatar  avatar  avatar Fugui avatar Tuan Duc Tran avatar Miroslav Bekyarov avatar aboutdev avatar Fariol Blondeau avatar Ersoy Filinte avatar pagepan avatar Logan Lindquist Land avatar  avatar Jason Carr  avatar masx200 avatar Ryan E avatar Todo avatar Samuel avatar Faded Weiss avatar  avatar Trần Quốc Thiện avatar x avatar Logan King (DarkComet) avatar  avatar Sam Chang avatar leez avatar  avatar Derek Martin avatar  avatar Peter Jones avatar Hoang Phan avatar Nadeem Ramsing avatar Future Infinity avatar Saad Shahd avatar Muhammad Rafly Indrawan avatar Enzo Robaina avatar Luis Marroquin avatar Dilip avatar  avatar chairui avatar Adam Refaey avatar Katie avatar Shon Chan avatar snowdream avatar  avatar John Serrao avatar  avatar Branden Pinney avatar dhdh416 avatar Hari Pachuveetil avatar Mashiro avatar 陈天寒 avatar Dima Pristupa avatar  avatar  avatar sunny avatar Youmu avatar Guilliano Molaire avatar Guilherme Pressutto avatar André Santos avatar  avatar Charles avatar  avatar  avatar Vishnu S Krish avatar Daniel Szprengiel avatar C avatar Ruben avatar Jon avatar Cogmeta avatar xlitter avatar yjs avatar zuber avatar Albert Tavares de Almeida avatar Zo-Hasina Rasatavohary avatar Gagandeep Singh (Gagan) avatar Jon Repp avatar Paul avatar Jun Liu avatar Vlad Levitskii avatar Zeljko Antic avatar  avatar  avatar Pierry Borges avatar 哈哈哈蜜瓜 avatar Soufiane avatar Ming avatar Hamit Tokay avatar  avatar Akash Singh avatar Jeren avatar xhw1 avatar Yi Sun avatar Deepak Donde avatar Dustin Bachrach avatar enpeng avatar luolin avatar Jayn Lau avatar Mohammad Rajabloo avatar

Watchers

 avatar AgBorkowski avatar  avatar Andrew Yang avatar S. M. AMRAN avatar fanxiaolong avatar  avatar Mouldi Nouri avatar liuxua01 avatar CTO国龙剑桥博士哈牛桥智能科技CEO于红红哈佛博士 avatar  avatar

hashmap's Issues

Remove and clear all not working.

shinchan@kg:~$ nodejs                                                           
> var hashmap = require('hashmap');                                             
undefined                                                                       
> var h = new hashmap()                                                         
undefined                                                                       
> h[5]=6                                                                        
6                                                                               
> h                                                                             
{ '5': 6, _data: {}, _count: 0 }                                                
> h.remove(5)                                                                   
{ '5': 6, _data: {}, _count: 0 }                                                
> h[5]                                                                          
6                                                                               
> h.clear()                                                                     
{ '5': 6, _data: {}, _count: 0 }                                                
> h[5]                                                                          
6                                                                               
> shinchan@kg:~$ exit                                                           

Neither the remove nor the clear function seems to be working. Node version is 0.10.25

Doesn't count as hashmap

You're not mapping value passed into [ ] to number, that is hash in a way, that pointers align. Therefore this is not a hash-map.

Hashmap breaks when minified

I've noticed that when hashmap is minified, this.type doesn't work correctly. The reason is the automatic chaining which does the followin check:

if (fn.toString().indexOf('return ') === -1) {
    proto[method] = chain(fn);
}

In minified code, it seems type is transformed into this:

type: function(t) {var e = Object.prototype.toString.call(t), n = e.slice(8, -1).toLowerCase();return"domwindow" !== n || t ? n : t + ""}

Because there's no space between return and "domwindow", the check causes type to be chained, returning this instead of the correct return value.

I propose that you explicitly list the names of the methods you want to chain instead of doing checks based on the structure of the function. But why did you have the space after return in that string to check anyway?

Fallback to object

Hi, is there a way to turn the HashMap-instance into a regular object (if the keys are valid, of course)?

Feature Request: forEach break

It would be nice for there to be some way to break from a forEach, say by returning false or HashMap.break or something. I suppose you can already do a continue just by returning undefined (or anything currently).

Cant install on Linux

npm ERR! err.code.match is not a function

Seems like the package is not compatible with latest nodejs on Linux anymore.

Since its also not updated anymore: here is my warning donr use it.

double quote

Hi Ariel,

HashMap works very nicely, thank you

The only thing I noticed, when looking at map._data, all my keys (which are strings) had a double quote character inserted

e.g. converting a string like: ‘some_key:some value’ became { ‘”some_key’: ‘some value’ }

Is there any way to drop the double quote?

Better hashing of keys

I believe a better hashing is needed. Try this out:

var HashMap = require('hashmap')

var a = new HashMap();

a.set(['a', 'b', 'c'], 1)
a.set(['a', 'b', 'c'], 2)
a.set(['a', 'b⁞♠c'], 3)

console.log(a)

I'm able to generate two values with a collision for the keys when using array.

Wrong behaviour?

Hello,

I've gone through your Readme and noticed the following issue:

Objects as keys
var key = {};
var key2 = {};
map.set(key, 123);
map.set(key2, 321);
map.get(key); // --> 123
A regular Object used as a map would yield 321

Shouldn't map.get(key) return 321? Because hash(key) should be equal to hash(key2) here as far as both objects has the same set of properties (basically, both have no own properties and the only difference is different placement in memory). But in your example it behaves like it just compares references.

intigrating it into angualr application

hi i am trying to addthis library into my angualr applciation but thorwing error

import { HashMap } from 'hashmap';

Could not find a declaration file for module 'hashmap'. 'c:/Users/z49445/Desktop/CrrCrewTkcUi/node_modules/hashmap/hashmap.js' implicitly has an 'any' type.
Try npm install @types/hashmap if it exists or add a new declaration (.d.ts) file containing declare module 'hashmap';

is there a way to solve this
thank you in advance

Module boilerplate doesn't work as expected in webpack

The boilerplate at the top:

if (typeof define === 'function' && define.amd) {
        // AMD. Register as an anonymous module.
        define([], factory);
} else ...

is triggered for webpack for some reason. This would work in the same way, except that you're not defining the AMD module in the same way as the commonJS module. The commonJS module is an object with a HashMap key set to the HashMap object, while the AMD one is directly set to the HashMap object.

Could you make these more consistent by setting module.exports to factory() rather than exports.HashMap?

Initializer argument in constructor

It would be nice to be able to write an initializer/immediate with the constructor like this:

new hashmap([
  [key, value],
  [key2, value2],
  etc
])

Get the size of the map

Hi !

Do you know how i can get the hashmap size ?
Best regards

Edit: Ah lol x) i have don't see the count() method srry

Incorrect Key Quoting

Hi,

after adding entries to a map I can see there's an error in the quoting of the keys:

{  
   "_data":{  
      "\"797d3f59-6644-4c9b-abb2-cd3082ef8ce4":[  
         "797d3f59-6644-4c9b-abb2-cd3082ef8ce4",
         {  
            "uuid":"797d3f59-6644-4c9b-abb2-cd3082ef8ce4",
            "name":"Item 0"
         }
      ]
   }
}

I've created a simple Plunk that illustrates the problem.

Regards,
Andi

Clarify readme

Please, clarify in the readme that it is impossible with this library to get the same value using another object as a key that is structurally identical to the first key object. Because this is what HashMap is usually used for.
For example:

const key1 = { k: 'v' }
const key2 = { k: 'v' }
map.set(key1, 'val1')
map.set(key2, 'val2')
// actual behavior is that key1 and key2 have different hashes, so:
map.get(key1) // --> 'val1'
map.get(key2) // --> 'val2'
// expected behavior (same hashes):
map.get(key1) // --> 'val2'
map.get(key2) // --> 'val2'

The numbering inside "_data" object does not reset

This might not be an issue, but possibly might cause problems in the long run.
I have a node+express REST API server which uses this HashMap library. I have noticed that the _hmuid_ variable is not resetting. For every new request my server receives, the response has an incremented _hmuid_. Its no problem right now, but will it affect performance in the long run? following snippet shows first few lines of the hashmap:

{
    "_data": {
        "♦3": [
            "5b814a2322236100142ac9f6",
            [
                {
                    ...,
                    ...,
                    ...
                }

the ♦3 is not resetting back to ♦1, so I think it is probably using some of my memory. Or is there something I'm doing wrong?

TypeError: HashMap is not a constructor

I'm trying to use hashmap with requireJS + nodeJS?
I've tried adding it to my module like this:

define([ 'hashmap' ], function( HashMap) {
var map = new HashMap();
});

Unfortunately I get "TypeError: HashMap is not a constructor".
Any idea where I've gone wrong?

Thanks

Not a hashmap

I just read the code, and you are literally just using a string as a key to an object property as your storage, your hash function doesn't even return a hash, it returns a string.

Where are the buckets?
Where is the correct hashing algorithm?

Getting issues to load hashmap.js with IE8

For some not so strange issue IE8, when running files from my machine works fine, but once I deploy it in Sharepoint it says that:

User Agent: Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 6.1; Trident/4.0; SLCC2; .NET CLR 2.0.50727; .NET CLR 3.5.30729; .NET CLR 3.0.30729; .NET4.0C; .NET4.0E)
Time Stamp: Tue, 5 Mar 2013 17:26:09 UTC

Message: Identifier, sequence or number expected
Line: 86
Character: 2
Code: 0
URI: /js/hashmap.js

Message: 'HashMap' is notdefined
Line: 223
Character: 4
Code: 0
URI: /webapp/index.html

On Chrome no issues. Any clues?

Examples of search function

I have been facing issues with hashmap when used with protractor for search function. Can you please post examples of search function of hashMap?

Question: object as keys

[bad English]
I have a project where i use class types for my objects.
e.g.
There is a UserId class wrapper that saves the id as a string
UserId{value:string}

The thing is that i create this userid multiple times. e.g when i retrieve the value from the db i create a new object with the string value i get from the db.Essentially i create a new UserId object.

Based on how this library works,i cant i set my UserId class as a key to a hashmap because the hash is reset every time i create a new instance.

the result i'm trying to achieve is
let users:HashMap<UserId,User> = new HashMap<>();
users.set(new UserId("123"),user1);

let userId:UserId = new UserId("123");

let userIdSame:UserId = new UserId("123");

users.get(userId); //expect to be user1
users.get(userIdSame); //expect to be user1

Are there any plans to support such case? Thanks

EDIT:
Followup question: Shouldn't the hashing of an object depend only on the values of the instance? For example in Java two different instances with the same values, would have the same hashcode

Best way to sort by key or value?

Howdy -

Any recommendations on the best way to sort these hashmaps by key or value?

I've seen tuple-based approaches, basically breaking the hashmap into two distinct arrays, sorting by key or value and then recombining them into the hashmap.

Just wondering whether there's some other pattern that I'm missing. Btw, thanks for the hashmap!

Uncaught RangeError: Maximum call stack size exceeded

Hi,

I keep getting this error from the hashmap module. What I am doing is saving objects based on the unique hash key. If there are no earlier entries I am adding a new object. Otherwise I am modifying the existing object pertaining to the key and then setting it against the key. This works for about 2200 odd entries, but as soon as the items reach 2500 or so, it bombs out with this issue.

"Uncaught RangeError: Maximum call stack size exceeded", source: C:\Users\New Owner\Desktop\APP\src\node_modules\hashmap\hashmap.js (27)

I have also tried replacing the modified object by first removing the existing object from the map.

Any help will be appreciated.

Collisions for distinct values are trivial to generate

... and thus not guaranteed to not happen accidentally e.g.:

  • [ "foo", "bar", "baz" ] -> '["foo|"bar|"baz'
  • [ "foo", 'bar|"baz' ] -> '["foo|"bar|"baz'

A JSON-style representation would at least be unambiguous e.g. hash strings with JSON.stringify, arrays as [ *, ... ], and objects as { "...": *, ... } (with sorted keys) e.g.:

  • [ "foo", "bar", "baz" ] -> '["foo","bar","baz"]'
  • [ "foo", 'bar|"baz' ] -> '["foo","bar|\\"baz"]'

See here for more details.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.