-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathgeohash_map.js
59 lines (51 loc) · 1.62 KB
/
geohash_map.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
class GeohashMap {
constructor () {
this.hash = {};
}
add (geohash, object) {
for (let i = geohash.length; i > 0; i--) {
const fragment = geohash.substr(0, i);
if (!this.hash[fragment]) {
this.hash[fragment] = [];
}
this.hash[fragment].push(object);
}
};
remove (geohash, object) {
for (let i = geohash.length; i > 0; i--) {
const fragment = geohash.substr(0, i);
if (this.hash[fragment]) {
const index = this.hash[fragment].indexOf(object);
if (index !== -1) {
this.hash[fragment].splice(index, 1);
}
}
}
};
nearest (geohash, limit) {
const found = [];
for (let i = geohash.length; i > 0; i--) {
const fragment = geohash.substr(0, i);
if (this.hash[fragment]) {
let j = this.hash[fragment].length - 1;
while (j >= 0 && found.length < limit) {
if (found.indexOf(this.hash[fragment][j]) === -1) {
found.push(this.hash[fragment][j]);
}
j--;
}
}
}
return found;
};
}
// const g = new GeohashMap();
// g.add('gcw234fg', 'finn');
// g.add('gcw234fm', 'mike');
// g.add('gcw295ab', 'dave');
// g.add('gcx295ab', 'steve');
// console.log(g.nearest('gcw234fg', 5));
// console.log(g.nearest('gcw234fg', 3));
// console.log(g.nearest('gcw234fg', 2));
// console.log(g.nearest('gcw234fg', 1));
module.exports = GeohashMap;