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
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)
new HashMap()creates an empty hashmapnew HashMap(map:HashMap)creates a hashmap with the key-value pairs ofmapnew HashMap(arr:Array)creates a hashmap from the 2D key-value arrayarr, e.g.[['key1','val1'], ['key2','val2']]new HashMap(key:*, value:*, key2:*, value2:*, ...)creates a hashmap with several key-value pairs
get(key:*) : *returns the value stored for that key.set(key:*, value:*) : HashMapstores a key-value pairmulti(key:*, value:*, key2:*, value2:*, ...) : HashMapstores several key-value pairscopy(other:HashMap) : HashMapcopies all key-value pairs from other to this instancehas(key:*) : Booleanreturns whether a key is set on the hashmapsearch(value:*) : *returns key under which given value is stored (nullif not found)delete(key:*) : HashMapdeletes a key-value pair by keyremove(key:*) : HashMapAlias fordelete(key:*)(deprecated)type(key:*) : Stringreturns the data type of the provided key (used internally)keys() : Array<*>returns an array with all the registered keysvalues() : Array<*>returns an array with all the valuesentries() : Array<[*,*]>returns an array with [key,value] pairssize : Numberthe amount of key-value pairscount() : Numberreturns the amount of key-value pairs (deprecated)clear() : HashMapdeletes all the key-value pairs on the hashmapclone() : HashMapcreates a new hashmap with all the key-value pairs of the originalhash(key:*) : Stringreturns the stringified version of a key (used internally)forEach(function(value, key)) : HashMapiterates the pairs and calls the function for each one
All methods that don't return something, will return the HashMap instance to enable chaining.
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');map.set("some_key", "some value");
map.get("some_key"); // --> "some value"
var map = new HashMap();
map.set("key1", "val1");
map.set("key2", "val2");
map.size; // -> 2
map.set("some_key", "some value");
map.delete("some_key");
map.get("some_key"); // --> undefined
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"
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
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}`)
}
map
.set(1, "test 1")
.set(2, "test 2")
.set(3, "test 3")
.forEach(function(value, key) {
console.log(key + " : " + value);
});
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
- (?) Allow extending the hashing function in a AOP way or by passing a service
- Make tests work on the browser
hashmap's People
Forkers
shindoh alexbirkett ilife5 oliverroick hemant19cse theosis sreejadas khrome rafalwrzeszcz foomango zhhb xcx ghatchue fresheneesz astralpeople mvayngrib renyaoxiang mrrychter wakermahmud ravidi psionski amsalt rkravi123 thefourtheye qbolec richiewang4528 gabrielpeart jeantimex snbqt charliexp tixit teakong flyer5200 pjki100 pvgnd freddiecoleman kurtaqui viphuangwei haha174 ulikoehler evaluation-alex nicholi nathanjang zld406504302 songdun ycllz workbgm blockchainb shivangpatel pillarwallet soufianerafik muhammadumairghufran plutod-cmyk yuhonghong7035 rasata vmolsa max19931 alannarisse tangtaoshadows riosj titanus007123 lipeidcc ajunlonglive vikingdadmedic mexicanito alenlym mdshohaanhashmap'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?
Add time coplexity of each operation
Can you add time complexity of each operation in the Readme file? That would be really helpful.
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
Could you elaborate on the runtimes of the operations, basically get, set, multi and has?
Hi, I'm curious to know the run-time of each of the operations, get, set, multi and has.
I wouldn't mind knowing the runtimes of the other functions. But mainly these.
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
])
Export as javascript array with key:pair value
How to export the hashmap into single javascript array to be passed on to server side?
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
HashMap Support with React Native
Does it provide support with react native?
I want to implement hashmap in react native please help me with this?
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.
Why does `multi` exist?
Is there some performance gain to using it? If not, it seems kinds superfluous
Recommend Projects
-
React
A declarative, efficient, and flexible JavaScript library for building user interfaces.
-
Vue.js
🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
-
Typescript
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
-
OpenClaw
Personal AI Assistant
-
Django
The Web framework for perfectionists with deadlines.
-
Laravel
A PHP framework for web artisans
-
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.
-
Visualization
Some thing interesting about visualization, use data art
-
Game
Some thing interesting about game, make everyone happy.
Recommend Org
-
Facebook
We are working to build community through open source technology. NB: members must have two-factor auth.
-
Microsoft
Open source projects and samples from Microsoft.
-
Google
Google ❤️ Open Source for everyone.
-
Alibaba
Alibaba Open Source for everyone
-
D3
Data-Driven Documents codes.
-
Tencent
China tencent open source team.
