-
Notifications
You must be signed in to change notification settings - Fork 32
/
space.html
545 lines (441 loc) · 13.6 KB
/
space.html
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
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
<html>
<head>
</head>
<body>
<script>
const SPACE = [
]
class Coordinates {
constructor(coord) {
if(typeof(coord)==="string") {
return Coordinates.parse(coord);
}
this._latitude = coord.latitude; // +/- 90
this._longitude = coord.longitude; // +/- 180
this._accuracy = coord.accuracy;
this._altitude = coord.altitude; // max 18000m
this._altitudeAccuracy = coord.altitudeAccuracy;
this._heading = coord.heading;
this._speed = coord.speed; // max 1,900 km/h
}
static parse(hash) {
const instance = Object.create(Coordinates.prototype),
numbers = hash.split(""),
coords = {latitude:"",longitude:"",altitude:""};
for(let i=0;i<13*3;i++) {
switch(i % 3) {
case 0:
coords.latitude += numbers[i]
break;
case 1:
coords.longitude += numbers[i]
break;
case 2:
coords.altitude += numbers[i]
break;
}
}
Object.keys(coords).forEach(key => coords[key] = parseInt(coords[key])/100000);
instance._latitude = parseFloat(((coords.latitude/(40075000*Math.cos(0)/360))-90).toFixed(5));
instance._longitude = parseFloat(((coords.longitude/(40075000*Math.cos(instance._latitude)/360))-180).toFixed(5));
instance._altitude = coords.altitude;
return instance;
}
static proximity(hash1,hash2) {
const altitude = {
hash1: "",
hash2: ""
};
let i = 0;
while(i<hash1.length) {
if(i % 3 === 2) {
altitude.hash1 += hash1[i];
altitude.hash2 += hash2[i];
} else if(hash1[i]!==hash2[i]) {
break;
}
i++;
}
Object.keys(altitude).forEach(key => altitude[key] = altitude[key].toString().padEnd(13));
return parseInt("100000000".substring(0,15-((i+3)/3)));
}
hash(precision) {
/*
Assuming that the Earth is a sphere of perimeter 40075 km.
Length in meters of 1deg of latitude = always 111320 m or 40075000 * cos(0) / 360
Length in meters of 1deg of longitude = 40075000 * cos(latitude) / 360
*/
const coords = {
latitude: ((this.latitude+90)*40075000*Math.cos(0)/360).toLocaleString("en-US",{style:"decimal",minimumIntegerDigits:8,minimumFractionDigits:5,useGrouping:false}).split("").filter(c => c!=="."),
longitude:((this.longitude+180)*40075000*Math.cos(this._latitude)/360).toLocaleString("en-US",{style:"decimal",minimumIntegerDigits:8,minimumFractionDigits:5,useGrouping:false}).split("").filter(c => c!=="."), // Math.absolute(Math.max(lats)-Math.min(lats)) distance in degrees
altitude: this.altitude.toLocaleString("en-US",{style:"decimal",minimumIntegerDigits:8,minimumFractionDigits:5,useGrouping:false}).split("").filter(c => c!==".")
};
let hash = "";
for(let i=0;i<13*3;i++) {
switch(i % 3) {
case 0:
hash += coords.latitude.shift();
break;
case 1:
hash += coords.longitude.shift();
break;
case 2:
hash += coords.altitude.shift();
break;
}
}
return hash;
}
get latitude() {
return this._latitude;
}
set latitude(latitude) {
return this._latitude = latitude;
}
get longitude() {
return this._longitude;
}
set longitude(longitude) {
return this._longitude = longitude;
}
get accuracy() {
return this._accuracy;
}
set accuracy(accuracy) {
return this._accuracy = accuracy;
}
get altitude() {
return this._altitude;
}
set altitude(altitude) {
return this._altitude = altitude;
}
get altitudeAccuracy() {
return this._altitudeAccuracy;
}
set altitudeAccuracy(altitudeAccuracy) {
return this._altitudeAccuracy = altitudeAccuracy;
}
get heading() {
return this._heading;
}
set heading(heading) {
return this._heading;
}
get speed() {
return this._speed;
}
set speed(speed) {
return this._speed = speed;
}
distance(coordinates) {
}
}
class Position {
constructor({coords,timestamp}) {
this._coords = coords;
this._timestamp = timestamp;
}
get coords() {
return this._coords;
}
set coords(coords) {
return this._coords = coords;
}
get timestamp() {
return this._timestamp;
}
set timestamp(timestamp) {
return this._timestamp = timestamp;
}
hash(precision) {
const toCentury = year => year.toString().substring(0,2),
toYear = year => year.toString().substring(2),
date = new Date(this._timestamp),
year = date.getUTCYear(),
coords = {
latitude: (this._coords.latitude+90).toLocaleString("en-US",{style:"decimal",minimumIntegerDigits:11,minimumFractionDigits:5,useGrouping:false}).split("").filter(c => c!=="."),
longitude: (this._coords.longitude+180).toLocaleString("en-US",{style:"decimal",minimumIntegerDigits:11,minimumFractionDigits:5,useGrouping:false}).split("").filter(c => c!=="."),
altitude: this._coords.altitude.toLocaleString("en-US",{style:"decimal",minimumIntegerDigits:11,minimumFractionDigits:5,useGrouping:false}).split("").filter(c => c!=="."),
time: [toCentury(year),toYear(year),date.getUTCMonth(),date.getUTCDate(),date.getUTCHour(),date.getUTCMinutes(),date.getUTCSeconds(),date.getUTCMilliseconds()]
};
let hash = "";
for(let i=0;i<16*4;i++) {
switch(i % 4) {
case 0:
hash += coords.latitude.shift();
break;
case 1:
hash += coords.longitude.shift();
break;
case 2:
hash += coords.altitude.shift();
break;
case 3:
hash += coords.time.shift();
break;
}
}
return hash;
}
}
/*export enum Precision {
// 1km precision and one month precision. Ancient historical use
Low = 12,
// 1m and minute precision. Historical use
Mid = 21,
// 1m and 100 ms precision. Aimed at general use
High = 24,
// picosecond and nonmeter precision
Exact = 30
}*/
const LatitudeRange = {
min: -90.0,
max: 90
};
const LongitudeRange = {
min: -180,
max: 180
};
const AltitudeStampRange = {
min: -15000 * 100, // KOla bore hol is 12,262 meters, use cm
max: 100 * 1000 * 100 // 100 km Karman line in meters, use cm
};
function getPrecision(a) {
if (!isFinite(a) || isNaN(a)) return 0;
const s = a + "",
d = s.indexOf('.') + 1;
return !d ? 0 : s.length - d;
}
/**
* Encode HashInput -> string.
* @param {HashInput} input
* @param {number|Precision} precision - Number of characters in resulting hash
* @returns string - the hash
*/
const encodeHash = ({latitude,longitude,altitude}, precision=Math.min(6,Math.max(getPrecision(latitude),getPrecision(longitude),getPrecision(altitude),2))*5) => {
const bitPrecision = Math.ceil((precision / 3) * 6);
altitude || (altitude = 0.000001); // altitude can't be zero
const latBits = _calculateBits(LatitudeRange, latitude, bitPrecision);
const longBits = _calculateBits(LongitudeRange, longitude, bitPrecision);
const altitudeBits = _calculateBits(AltitudeStampRange, altitude, bitPrecision);
let interleavedBits = '';
for ( let i=0; i<latBits.length; i++) {
interleavedBits += (latBits.charAt(i) + longBits.charAt(i) + altitudeBits.charAt(i));
}
const chunked = interleavedBits.match(/.{1,6}/g);
const ints = chunked.map(x => parseInt(x, 2));
const numbers = Uint8Array.from(ints); //.buffer
//const buff = new Buffer(numbers);
//const base64 = buff.toString('base64');
//return base64;
return btoa(numbers)+"."+precision;
};
/**
* Decode string -> HashOutput.
* @param {hash} string - A geotemporal hash string
* @returns {HashOutput}
*/
const decodeHash = (hash) => {
// const buf = atob(hash); //Buffer.from(hash, 'base64');
// const nums = Uint8Array.from(buf);
const [ints,precision=30] = hash.split(".");
const numbers = atob(ints).split(",");
const binaryString = numbers.reduce((sum, next) => {
for ( let i=5; i>= 0; i--) { sum += (next >> i) & 1 }
return sum
}, '');
let latBits = '';
let longBits = '';
let altitudeBits = '';
for (let i=0; i<binaryString.length; i++) {
switch ( i % 3 ) {
case 0: latBits += binaryString.charAt(i); break;
case 1: longBits += binaryString.charAt(i); break;
case 2: altitudeBits += binaryString.charAt(i); break;
}
}
const [latitude, latitudeError] = _decodeBinaryString(latBits, LatitudeRange);
const [longitude, longitudeError] = _decodeBinaryString(longBits, LongitudeRange);
const [altitude, altitudeError] = _decodeBinaryString(altitudeBits, AltitudeStampRange);
return {
latitude:parseFloat(latitude.toFixed(parseInt(precision)/5)), latitudeError,
longitude:parseFloat(longitude.toFixed(parseInt(precision)/5)), longitudeError,
altitude:parseFloat(altitude.toFixed(parseInt(precision)/5)), altitudeError
}
};
const _highOrLow = (min,max,value) => {
// Is it in the top or bottom half of the range
if ( value > ((min + max) / 2) ) { return 1; }
else { return 0; }
}
const _calculateBits = (range, value, precision) => {
let mutableRange = {...range};
let bits = '';
let i = 0;
while(i < precision) {
const result = _highOrLow(mutableRange.min, mutableRange.max, value);
if (result) {
mutableRange = {
min: (mutableRange.min + mutableRange.max) / 2,
max: mutableRange.max
}
} else {
mutableRange = {
min: mutableRange.min,
max: (mutableRange.min + mutableRange.max) / 2,
}
}
i++;
bits += result
}
return bits;
}
const _decodeBinaryString = (bits, range) => {
let mutableRange = {...range};
for (let i=0; i<bits.length; i++) {
const bit = bits.charAt(i);
if ( bit === '1') {
mutableRange = {
min: (mutableRange.min + mutableRange.max) / 2,
max: mutableRange.max
}
} else {
mutableRange = {
min: mutableRange.min,
max: (mutableRange.min + mutableRange.max) / 2
}
}
}
const error = (mutableRange.max - mutableRange.min) / 2;
return [mutableRange.min + error, error];
}
/*const h1 = encodeHash({
latitude: 28.5620,
longitude: -80.57721,
altitude: 0
});
console.log(h1);
console.log(decodeHash(h1));
const h2 = encodeHash({
latitude: 28.56201,
longitude: -80.57721,
altitude: 10000
});
console.log(h2);
console.log(decodeHash(h2));
const h3 = new Coordinates({
latitude: 28.5620,
longitude: -80.57721,
altitude: 0
});
console.log(h3.hash());
const h4 = new Coordinates({
latitude: 28.56201,
longitude: -80.57721,
altitude: 10000
});
console.log(h4.hash());
const h5 = new Coordinates({
latitude: -90,
longitude: -80.57721,
altitude: 0
});
console.log(h5.hash());*/
const c6 = new Coordinates({
latitude: 0,
longitude: -80.57721,
altitude: 10000
}),
h6 = c6.hash();
console.log(c6,h6,Coordinates.parse(h6),Coordinates.proximity(h6,h6));
(function() {
const _defineProperty = Object.defineProperty; // save original defineProperty
Object.defineProperty = function(target,name,desc={}) {
desc = Object.assign({},desc); // make copy so we don't change argument passed in
if(desc.private) {
if(desc.allow || desc.protected) {
throw new Error(`Specify only one of private, protected, or allow for ${name}`);
}
desc.allow = scope => {
return target.constructor === scope.constructor || scope === target;
}
} else if(desc.protected) {
if(desc.allow) {
throw new Error(`Specify only one of private, protected, or allow for ${name}`);
}
desc.allow = scope => {
return target.constructor === scope.constructor || scope === target || scope instanceof target.constructor;
}
} else if(Array.isArray(desc.allow)) {
const allow = desc.allow;
desc.allow = scope => {
return allow.some(friend => scope instanceof friend);
}
}
if(desc.allow) { // only need different behavior if allow is truthy
const get = desc.get;
let value = desc.value; // set initial value, the private storage
desc.get = function() { // create getter
if(desc.allow(this)) {
return get ? get.call(this) : value;
}
throw new TypeError(`${name} access denied`);
}
if(desc.writable) { // define value setter if writable
const set = desc.set;
desc.set = function(newValue) {
if(desc.allow(this)) {
if(set) {
return set.call(this,newValue);
}
return value = newValue;
}
throw new TypeError(`${name} access denied`);
}
} else { // otherwise define setter to throw access violation
desc.set = () => {
throw new TypeError(`${name} is read-only`);
}
}
delete desc.writable; // delete writable, can't have writable and get or set
delete desc.value; // delete value, can't have value and get or set
}
// "allowed" properties are never reconfigurable by defineProperty
if(!desc.allow || !Object.getOwnPropertyDescriptor(target,name)) {
_defineProperty(target,name,desc); // define property using original defineProperty
}
}
})();
// access-js
const Persons = new Set();
class Entity {
}
Object.defineProperty(Entity.prototype,"privateEntities",{private:true,value:[]});
Object.defineProperty(Entity.prototype,"protectedEntities",{protected:true,value:[]});
class Person extends Entity {
constructor() {
super();
Object.defineProperty(this,"born",{private:true,value:Date.now()});
Object.defineProperty(this,"name",{private:true,writable:true,enumerable:true});
Persons.add(this)
}
get age() {
Object.defineProperty(this,"age",{private:true,writable:true,enumerable:true});
}
set age(age) {
Object.defineProperty(this,"age",{private:true,writable:true,enumerable:true,value:age});
}
}
Object.defineProperty(Person.prototype,"others",{protected:true,get:() => Persons.values()});
const p1 = new Person(),
p2 = new Person();
p1.name = "joe";
console.log(p1);
p1.age = 27;
console.log(JSON.stringify(p1),p1.others,p2.others);
console.log(p1.protectedEntities);
console.log(p1.privateEntities);
</script>
</body>
</html>