code
stringlengths 24
2.07M
| docstring
stringlengths 25
85.3k
| func_name
stringlengths 1
92
| language
stringclasses 1
value | repo
stringlengths 5
64
| path
stringlengths 4
172
| url
stringlengths 44
218
| license
stringclasses 7
values |
---|---|---|---|---|---|---|---|
function createIdentity(entropy) {
var privateKey = createPrivateKey(entropy);
var wallet = new Wallet(privateKey);
var identity = {
privateKey: privateKey,
// remove trailing '0x04'
publicKey: stripHexPrefix(wallet.publicKey).slice(2),
address: wallet.address
};
return identity;
}
|
creates a new object with
private-, public-Key and address
@param {Buffer?} entropy if provided, will use that as single random-source
|
createIdentity
|
javascript
|
pubkey/eth-crypto
|
dist/es/create-identity.js
|
https://github.com/pubkey/eth-crypto/blob/master/dist/es/create-identity.js
|
MIT
|
function compress(hex) {
var base64 = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : false;
hex = removeLeading0x(hex);
// if base64:true, we use our own function because it results in a smaller output
if (base64 === true) return Buffer.from(hex, 'hex').toString('base64');
var string = '';
while (hex.length % 4 != 0) {
// we need it to be multiple of 4
hex = '0' + hex;
}
for (var i = 0; i < hex.length; i += 4) {
// get char from ascii code which goes from 0 to 65536
string += String.fromCharCode(parseInt(hex.substring(i, i + 4), 16));
}
return string;
}
|
compress/decompress hex-strings to utf16 or base64
thx @juvian
@link https://stackoverflow.com/a/40471908/3443137
|
compress
|
javascript
|
pubkey/eth-crypto
|
dist/es/hex.js
|
https://github.com/pubkey/eth-crypto/blob/master/dist/es/hex.js
|
MIT
|
function decompress(compressedString) {
var base64 = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : false;
// if base64:true, we use our own function because it results in a smaller output
if (base64 === true) {
var ret = Buffer.from(compressedString, 'base64').toString('hex');
return addLeading0x(ret);
}
var hex = '';
for (var i = 0; i < compressedString.length; i++) {
// get character ascii code and convert to hexa string, adding necessary 0s
hex += ((i == 0 ? '' : '000') + compressedString.charCodeAt(i).toString(16)).slice(-4);
}
hex = hex.toLowerCase();
return addLeading0x(hex);
}
|
compress/decompress hex-strings to utf16 or base64
thx @juvian
@link https://stackoverflow.com/a/40471908/3443137
|
decompress
|
javascript
|
pubkey/eth-crypto
|
dist/es/hex.js
|
https://github.com/pubkey/eth-crypto/blob/master/dist/es/hex.js
|
MIT
|
function publicKeyByPrivateKey(privateKey) {
privateKey = addLeading0x(privateKey);
var publicKeyBuffer = privateToPublic(toBuffer(privateKey));
return publicKeyBuffer.toString('hex');
}
|
Generate publicKey from the privateKey.
This creates the uncompressed publicKey,
where 04 has stripped from left
@returns {string}
|
publicKeyByPrivateKey
|
javascript
|
pubkey/eth-crypto
|
dist/es/public-key-by-private-key.js
|
https://github.com/pubkey/eth-crypto/blob/master/dist/es/public-key-by-private-key.js
|
MIT
|
function toAddress(publicKey) {
// normalize key
publicKey = decompress(publicKey);
var addressBuffer = pubToAddress(toBuffer(addLeading0x(publicKey)));
var checkSumAdress = toChecksumAddress(addLeading0x(addressBuffer.toString('hex')));
return checkSumAdress;
}
|
generates the ethereum-address of the publicKey
We create the checksum-address which is case-sensitive
@returns {string} address
|
toAddress
|
javascript
|
pubkey/eth-crypto
|
dist/es/public-key.js
|
https://github.com/pubkey/eth-crypto/blob/master/dist/es/public-key.js
|
MIT
|
function recoverPublicKey(signature, hash) {
signature = removeLeading0x(signature);
// split into v-value and sig
var sigOnly = signature.substring(0, signature.length - 2); // all but last 2 chars
var vValue = signature.slice(-2); // last 2 chars
var recoveryNumber = vValue === '1c' ? 1 : 0;
var pubKey = uint8ArrayToHex(ecdsaRecover(hexToUnit8Array(sigOnly), recoveryNumber, hexToUnit8Array(removeLeading0x(hash)), false));
// remove trailing '04'
pubKey = pubKey.slice(2);
return pubKey;
}
|
returns the publicKey for the privateKey with which the messageHash was signed
@param {string} signature
@param {string} hash
@return {string} publicKey
|
recoverPublicKey
|
javascript
|
pubkey/eth-crypto
|
dist/es/recover-public-key.js
|
https://github.com/pubkey/eth-crypto/blob/master/dist/es/recover-public-key.js
|
MIT
|
function recover(sigString, hash) {
var pubkey = recoverPublicKey(sigString, hash);
var address = addressByPublicKey(pubkey);
return address;
}
|
returns the address with which the messageHash was signed
@param {string} sigString
@param {string} hash
@return {string} address
|
recover
|
javascript
|
pubkey/eth-crypto
|
dist/es/recover.js
|
https://github.com/pubkey/eth-crypto/blob/master/dist/es/recover.js
|
MIT
|
function sign(privateKey, hash) {
hash = addLeading0x(hash);
if (hash.length !== 66) throw new Error('EthCrypto.sign(): Can only sign hashes, given: ' + hash);
var sigObj = secp256k1_sign(new Uint8Array(Buffer.from(removeLeading0x(hash), 'hex')), new Uint8Array(Buffer.from(removeLeading0x(privateKey), 'hex')));
var recoveryId = sigObj.recid === 1 ? '1c' : '1b';
var newSignature = '0x' + Buffer.from(sigObj.signature).toString('hex') + recoveryId;
return newSignature;
}
|
signs the given message
we do not use sign from eth-lib because the pure secp256k1-version is 90% faster
@param {string} privateKey
@param {string} hash
@return {string} hexString
|
sign
|
javascript
|
pubkey/eth-crypto
|
dist/es/sign.js
|
https://github.com/pubkey/eth-crypto/blob/master/dist/es/sign.js
|
MIT
|
function fromString(hexString) {
var arr = ethersUtils.splitSignature(hexString);
return {
// convert "v" to hex
v: "0x".concat(arr.v.toString(16)),
r: arr.r,
s: arr.s
};
}
|
split signature-hex into parts
@param {string} hexString
@return {{v: string, r: string, s: string}}
|
fromString
|
javascript
|
pubkey/eth-crypto
|
dist/es/vrs.js
|
https://github.com/pubkey/eth-crypto/blob/master/dist/es/vrs.js
|
MIT
|
function toString(sig) {
return ethersUtils.joinSignature(sig);
}
|
merge signature-parts to one string
@param {{v: string, r: string, s: string}} sig
@return {string} hexString
|
toString
|
javascript
|
pubkey/eth-crypto
|
dist/es/vrs.js
|
https://github.com/pubkey/eth-crypto/blob/master/dist/es/vrs.js
|
MIT
|
function createPrivateKey(entropy) {
if (entropy) {
if (!Buffer.isBuffer(entropy)) throw new Error('EthCrypto.createPrivateKey(): given entropy is no Buffer');
if (Buffer.byteLength(entropy, 'utf8') < MIN_ENTROPY_SIZE) throw new Error('EthCrypto.createPrivateKey(): Entropy-size must be at least ' + MIN_ENTROPY_SIZE);
var outerHex = keccak256(entropy);
return outerHex;
} else {
var innerHex = keccak256(_ethers.utils.concat([_ethers.utils.randomBytes(32), _ethers.utils.randomBytes(32)]));
var middleHex = _ethers.utils.concat([_ethers.utils.concat([_ethers.utils.randomBytes(32), innerHex]), _ethers.utils.randomBytes(32)]);
var _outerHex = keccak256(middleHex);
return _outerHex;
}
}
|
create a privateKey from the given entropy or a new one
@param {Buffer} entropy
@return {string}
|
createPrivateKey
|
javascript
|
pubkey/eth-crypto
|
dist/lib/create-identity.js
|
https://github.com/pubkey/eth-crypto/blob/master/dist/lib/create-identity.js
|
MIT
|
function createIdentity(entropy) {
var privateKey = createPrivateKey(entropy);
var wallet = new _ethers.Wallet(privateKey);
var identity = {
privateKey: privateKey,
// remove trailing '0x04'
publicKey: (0, _ethereumjsUtil.stripHexPrefix)(wallet.publicKey).slice(2),
address: wallet.address
};
return identity;
}
|
creates a new object with
private-, public-Key and address
@param {Buffer?} entropy if provided, will use that as single random-source
|
createIdentity
|
javascript
|
pubkey/eth-crypto
|
dist/lib/create-identity.js
|
https://github.com/pubkey/eth-crypto/blob/master/dist/lib/create-identity.js
|
MIT
|
function compress(hex) {
var base64 = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : false;
hex = (0, _util.removeLeading0x)(hex);
// if base64:true, we use our own function because it results in a smaller output
if (base64 === true) return Buffer.from(hex, 'hex').toString('base64');
var string = '';
while (hex.length % 4 != 0) {
// we need it to be multiple of 4
hex = '0' + hex;
}
for (var i = 0; i < hex.length; i += 4) {
// get char from ascii code which goes from 0 to 65536
string += String.fromCharCode(parseInt(hex.substring(i, i + 4), 16));
}
return string;
}
|
compress/decompress hex-strings to utf16 or base64
thx @juvian
@link https://stackoverflow.com/a/40471908/3443137
|
compress
|
javascript
|
pubkey/eth-crypto
|
dist/lib/hex.js
|
https://github.com/pubkey/eth-crypto/blob/master/dist/lib/hex.js
|
MIT
|
function decompress(compressedString) {
var base64 = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : false;
// if base64:true, we use our own function because it results in a smaller output
if (base64 === true) {
var ret = Buffer.from(compressedString, 'base64').toString('hex');
return (0, _util.addLeading0x)(ret);
}
var hex = '';
for (var i = 0; i < compressedString.length; i++) {
// get character ascii code and convert to hexa string, adding necessary 0s
hex += ((i == 0 ? '' : '000') + compressedString.charCodeAt(i).toString(16)).slice(-4);
}
hex = hex.toLowerCase();
return (0, _util.addLeading0x)(hex);
}
|
compress/decompress hex-strings to utf16 or base64
thx @juvian
@link https://stackoverflow.com/a/40471908/3443137
|
decompress
|
javascript
|
pubkey/eth-crypto
|
dist/lib/hex.js
|
https://github.com/pubkey/eth-crypto/blob/master/dist/lib/hex.js
|
MIT
|
function publicKeyByPrivateKey(privateKey) {
privateKey = (0, _util.addLeading0x)(privateKey);
var publicKeyBuffer = (0, _ethereumjsUtil.privateToPublic)((0, _ethereumjsUtil.toBuffer)(privateKey));
return publicKeyBuffer.toString('hex');
}
|
Generate publicKey from the privateKey.
This creates the uncompressed publicKey,
where 04 has stripped from left
@returns {string}
|
publicKeyByPrivateKey
|
javascript
|
pubkey/eth-crypto
|
dist/lib/public-key-by-private-key.js
|
https://github.com/pubkey/eth-crypto/blob/master/dist/lib/public-key-by-private-key.js
|
MIT
|
function toAddress(publicKey) {
// normalize key
publicKey = decompress(publicKey);
var addressBuffer = (0, _ethereumjsUtil.pubToAddress)((0, _ethereumjsUtil.toBuffer)((0, _util.addLeading0x)(publicKey)));
var checkSumAdress = (0, _ethereumjsUtil.toChecksumAddress)((0, _util.addLeading0x)(addressBuffer.toString('hex')));
return checkSumAdress;
}
|
generates the ethereum-address of the publicKey
We create the checksum-address which is case-sensitive
@returns {string} address
|
toAddress
|
javascript
|
pubkey/eth-crypto
|
dist/lib/public-key.js
|
https://github.com/pubkey/eth-crypto/blob/master/dist/lib/public-key.js
|
MIT
|
function recoverPublicKey(signature, hash) {
signature = (0, _util.removeLeading0x)(signature);
// split into v-value and sig
var sigOnly = signature.substring(0, signature.length - 2); // all but last 2 chars
var vValue = signature.slice(-2); // last 2 chars
var recoveryNumber = vValue === '1c' ? 1 : 0;
var pubKey = (0, _util.uint8ArrayToHex)((0, _secp256k.ecdsaRecover)((0, _util.hexToUnit8Array)(sigOnly), recoveryNumber, (0, _util.hexToUnit8Array)((0, _util.removeLeading0x)(hash)), false));
// remove trailing '04'
pubKey = pubKey.slice(2);
return pubKey;
}
|
returns the publicKey for the privateKey with which the messageHash was signed
@param {string} signature
@param {string} hash
@return {string} publicKey
|
recoverPublicKey
|
javascript
|
pubkey/eth-crypto
|
dist/lib/recover-public-key.js
|
https://github.com/pubkey/eth-crypto/blob/master/dist/lib/recover-public-key.js
|
MIT
|
function recover(sigString, hash) {
var pubkey = (0, _recoverPublicKey.recoverPublicKey)(sigString, hash);
var address = (0, _publicKey.toAddress)(pubkey);
return address;
}
|
returns the address with which the messageHash was signed
@param {string} sigString
@param {string} hash
@return {string} address
|
recover
|
javascript
|
pubkey/eth-crypto
|
dist/lib/recover.js
|
https://github.com/pubkey/eth-crypto/blob/master/dist/lib/recover.js
|
MIT
|
function sign(privateKey, hash) {
hash = (0, _util.addLeading0x)(hash);
if (hash.length !== 66) throw new Error('EthCrypto.sign(): Can only sign hashes, given: ' + hash);
var sigObj = (0, _secp256k.ecdsaSign)(new Uint8Array(Buffer.from((0, _util.removeLeading0x)(hash), 'hex')), new Uint8Array(Buffer.from((0, _util.removeLeading0x)(privateKey), 'hex')));
var recoveryId = sigObj.recid === 1 ? '1c' : '1b';
var newSignature = '0x' + Buffer.from(sigObj.signature).toString('hex') + recoveryId;
return newSignature;
}
|
signs the given message
we do not use sign from eth-lib because the pure secp256k1-version is 90% faster
@param {string} privateKey
@param {string} hash
@return {string} hexString
|
sign
|
javascript
|
pubkey/eth-crypto
|
dist/lib/sign.js
|
https://github.com/pubkey/eth-crypto/blob/master/dist/lib/sign.js
|
MIT
|
function fromString(hexString) {
var arr = _ethers.utils.splitSignature(hexString);
return {
// convert "v" to hex
v: "0x".concat(arr.v.toString(16)),
r: arr.r,
s: arr.s
};
}
|
split signature-hex into parts
@param {string} hexString
@return {{v: string, r: string, s: string}}
|
fromString
|
javascript
|
pubkey/eth-crypto
|
dist/lib/vrs.js
|
https://github.com/pubkey/eth-crypto/blob/master/dist/lib/vrs.js
|
MIT
|
function toString(sig) {
return _ethers.utils.joinSignature(sig);
}
|
merge signature-parts to one string
@param {{v: string, r: string, s: string}} sig
@return {string} hexString
|
toString
|
javascript
|
pubkey/eth-crypto
|
dist/lib/vrs.js
|
https://github.com/pubkey/eth-crypto/blob/master/dist/lib/vrs.js
|
MIT
|
function createPrivateKey(entropy) {
if (entropy) {
if (!Buffer.isBuffer(entropy))
throw new Error('EthCrypto.createPrivateKey(): given entropy is no Buffer');
if (Buffer.byteLength(entropy, 'utf8') < MIN_ENTROPY_SIZE)
throw new Error('EthCrypto.createPrivateKey(): Entropy-size must be at least ' + MIN_ENTROPY_SIZE);
const outerHex = keccak256(entropy);
return outerHex;
} else {
const innerHex = keccak256(ethersUtils.concat([ethersUtils.randomBytes(32), ethersUtils.randomBytes(32)]));
const middleHex = ethersUtils.concat([ethersUtils.concat([ethersUtils.randomBytes(32), innerHex]), ethersUtils.randomBytes(32)]);
const outerHex = keccak256(middleHex);
return outerHex;
}
}
|
create a privateKey from the given entropy or a new one
@param {Buffer} entropy
@return {string}
|
createPrivateKey
|
javascript
|
pubkey/eth-crypto
|
src/create-identity.js
|
https://github.com/pubkey/eth-crypto/blob/master/src/create-identity.js
|
MIT
|
function createIdentity(entropy) {
const privateKey = createPrivateKey(entropy);
const wallet = new Wallet(privateKey);
const identity = {
privateKey: privateKey,
// remove trailing '0x04'
publicKey: stripHexPrefix(wallet.publicKey).slice(2),
address: wallet.address,
};
return identity;
}
|
creates a new object with
private-, public-Key and address
@param {Buffer?} entropy if provided, will use that as single random-source
|
createIdentity
|
javascript
|
pubkey/eth-crypto
|
src/create-identity.js
|
https://github.com/pubkey/eth-crypto/blob/master/src/create-identity.js
|
MIT
|
function compress(hex, base64 = false) {
hex = removeLeading0x(hex);
// if base64:true, we use our own function because it results in a smaller output
if (base64 === true)
return Buffer.from(hex, 'hex').toString('base64');
let string = '';
while (hex.length % 4 != 0) { // we need it to be multiple of 4
hex = '0' + hex;
}
for (let i = 0; i < hex.length; i += 4) {
// get char from ascii code which goes from 0 to 65536
string += String.fromCharCode(parseInt(hex.substring(i, i + 4), 16));
}
return string;
}
|
compress/decompress hex-strings to utf16 or base64
thx @juvian
@link https://stackoverflow.com/a/40471908/3443137
|
compress
|
javascript
|
pubkey/eth-crypto
|
src/hex.js
|
https://github.com/pubkey/eth-crypto/blob/master/src/hex.js
|
MIT
|
function decompress(compressedString, base64 = false) {
// if base64:true, we use our own function because it results in a smaller output
if (base64 === true) {
const ret = Buffer.from(compressedString, 'base64').toString('hex');
return addLeading0x(ret);
}
let hex = '';
for (let i = 0; i < compressedString.length; i++) {
// get character ascii code and convert to hexa string, adding necessary 0s
hex += ((i == 0 ? '' : '000') + compressedString.charCodeAt(i).toString(16)).slice(-4);
}
hex = hex.toLowerCase();
return addLeading0x(hex);
}
|
compress/decompress hex-strings to utf16 or base64
thx @juvian
@link https://stackoverflow.com/a/40471908/3443137
|
decompress
|
javascript
|
pubkey/eth-crypto
|
src/hex.js
|
https://github.com/pubkey/eth-crypto/blob/master/src/hex.js
|
MIT
|
function publicKeyByPrivateKey(privateKey) {
privateKey = addLeading0x(privateKey);
const publicKeyBuffer = privateToPublic(toBuffer(privateKey));
return publicKeyBuffer.toString('hex');
}
|
Generate publicKey from the privateKey.
This creates the uncompressed publicKey,
where 04 has stripped from left
@returns {string}
|
publicKeyByPrivateKey
|
javascript
|
pubkey/eth-crypto
|
src/public-key-by-private-key.js
|
https://github.com/pubkey/eth-crypto/blob/master/src/public-key-by-private-key.js
|
MIT
|
function toAddress(publicKey) {
// normalize key
publicKey = decompress(publicKey);
const addressBuffer = pubToAddress(toBuffer(addLeading0x(publicKey)));
const checkSumAdress = toChecksumAddress(addLeading0x(addressBuffer.toString('hex')));
return checkSumAdress;
}
|
generates the ethereum-address of the publicKey
We create the checksum-address which is case-sensitive
@returns {string} address
|
toAddress
|
javascript
|
pubkey/eth-crypto
|
src/public-key.js
|
https://github.com/pubkey/eth-crypto/blob/master/src/public-key.js
|
MIT
|
function recoverPublicKey(signature, hash) {
signature = removeLeading0x(signature);
// split into v-value and sig
const sigOnly = signature.substring(0, signature.length - 2); // all but last 2 chars
const vValue = signature.slice(-2); // last 2 chars
const recoveryNumber = vValue === '1c' ? 1 : 0;
let pubKey = uint8ArrayToHex(ecdsaRecover(
hexToUnit8Array(sigOnly),
recoveryNumber,
hexToUnit8Array(removeLeading0x(hash)),
false
));
// remove trailing '04'
pubKey = pubKey.slice(2);
return pubKey;
}
|
returns the publicKey for the privateKey with which the messageHash was signed
@param {string} signature
@param {string} hash
@return {string} publicKey
|
recoverPublicKey
|
javascript
|
pubkey/eth-crypto
|
src/recover-public-key.js
|
https://github.com/pubkey/eth-crypto/blob/master/src/recover-public-key.js
|
MIT
|
function recover(sigString, hash) {
const pubkey = recoverPublicKey(sigString, hash);
const address = addressByPublicKey(pubkey);
return address;
}
|
returns the address with which the messageHash was signed
@param {string} sigString
@param {string} hash
@return {string} address
|
recover
|
javascript
|
pubkey/eth-crypto
|
src/recover.js
|
https://github.com/pubkey/eth-crypto/blob/master/src/recover.js
|
MIT
|
function sign(privateKey, hash) {
hash = addLeading0x(hash);
if (hash.length !== 66)
throw new Error('EthCrypto.sign(): Can only sign hashes, given: ' + hash);
const sigObj = secp256k1_sign(
new Uint8Array(Buffer.from(removeLeading0x(hash), 'hex')),
new Uint8Array(Buffer.from(removeLeading0x(privateKey), 'hex'))
);
const recoveryId = sigObj.recid === 1 ? '1c' : '1b';
const newSignature = '0x' + Buffer.from(sigObj.signature).toString('hex') + recoveryId;
return newSignature;
}
|
signs the given message
we do not use sign from eth-lib because the pure secp256k1-version is 90% faster
@param {string} privateKey
@param {string} hash
@return {string} hexString
|
sign
|
javascript
|
pubkey/eth-crypto
|
src/sign.js
|
https://github.com/pubkey/eth-crypto/blob/master/src/sign.js
|
MIT
|
function fromString(hexString) {
const arr = ethersUtils.splitSignature(hexString);
return {
// convert "v" to hex
v: `0x${arr.v.toString(16)}`,
r: arr.r,
s: arr.s,
};
}
|
split signature-hex into parts
@param {string} hexString
@return {{v: string, r: string, s: string}}
|
fromString
|
javascript
|
pubkey/eth-crypto
|
src/vrs.js
|
https://github.com/pubkey/eth-crypto/blob/master/src/vrs.js
|
MIT
|
function toString(sig) {
return ethersUtils.joinSignature(sig);
}
|
merge signature-parts to one string
@param {{v: string, r: string, s: string}} sig
@return {string} hexString
|
toString
|
javascript
|
pubkey/eth-crypto
|
src/vrs.js
|
https://github.com/pubkey/eth-crypto/blob/master/src/vrs.js
|
MIT
|
transpileCode = async (code) => {
const spawn = require('child-process-promise').spawn;
const stdout = [];
const stderr = [];
const promise = spawn('ts-node', [
'--compiler-options', '{"target":"es6", "strict": true}',
'-e', codeBase + '\n' + code
]);
const childProcess = promise.childProcess;
childProcess.stdout.on('data', data => stdout.push(data.toString()));
childProcess.stderr.on('data', data => stderr.push(data.toString()));
try {
await promise;
} catch (err) {
throw new Error(`could not run
# Error: ${err}
# Output: ${stdout}
# ErrOut: ${stderr}
`);
}
}
|
checks if the typings are correct
run via 'npm run test:typings'
|
transpileCode
|
javascript
|
pubkey/eth-crypto
|
test/typings.test.js
|
https://github.com/pubkey/eth-crypto/blob/master/test/typings.test.js
|
MIT
|
transpileCode = async (code) => {
const spawn = require('child-process-promise').spawn;
const stdout = [];
const stderr = [];
const promise = spawn('ts-node', [
'--compiler-options', '{"target":"es6", "strict": true}',
'-e', codeBase + '\n' + code
]);
const childProcess = promise.childProcess;
childProcess.stdout.on('data', data => stdout.push(data.toString()));
childProcess.stderr.on('data', data => stderr.push(data.toString()));
try {
await promise;
} catch (err) {
throw new Error(`could not run
# Error: ${err}
# Output: ${stdout}
# ErrOut: ${stderr}
`);
}
}
|
checks if the typings are correct
run via 'npm run test:typings'
|
transpileCode
|
javascript
|
pubkey/eth-crypto
|
test/typings.test.js
|
https://github.com/pubkey/eth-crypto/blob/master/test/typings.test.js
|
MIT
|
function createError(messages, errCode, meta) {
// The error value may be "undefined", so check if the argument was provided
const hasValue = meta && 'value' in meta;
// Throw a custom error type with the code attached
const err = new Error(
`${messages[errCode] || UNKNOWN_ERROR_MSG} (code: ${errCode}${
hasValue ? `, value: ${meta.value}` : ''
})`
);
// @ts-expect-error - TS doesn't like extending Error
err.code = errCode;
return err;
}
|
Create an error with an attached code
@private
@param {Record<number, string>} messages Map of code-to-messages to use
@param {number} errCode Numeric error code
@param {{value: unknown} | {}} [meta] Metadata with value to associate with the error
|
createError
|
javascript
|
uber/h3-js
|
lib/errors.js
|
https://github.com/uber/h3-js/blob/master/lib/errors.js
|
Apache-2.0
|
function H3LibraryError(errCode, value) {
// The error value may be "undefined", so check if the argument was provided
const meta = arguments.length === 2 ? {value} : {};
return createError(H3_ERROR_MSGS, errCode, meta);
}
|
Custom error for H3Error codes
@private
@param {number} errCode Error code from the H3 library
@param {unknown} [value] Value to associate with the error, if any
@returns {Error}
|
H3LibraryError
|
javascript
|
uber/h3-js
|
lib/errors.js
|
https://github.com/uber/h3-js/blob/master/lib/errors.js
|
Apache-2.0
|
function JSBindingError(errCode, value) {
// The error value may be "undefined", so check if the argument was provided
const meta = arguments.length === 2 ? {value} : {};
return createError(JS_ERROR_MESSAGES, errCode, meta);
}
|
Custom errors thrown from the JS bindings.
@private
@param {number} errCode Error code from the H3 library
@param {unknown} [value] Value to associate with the error, if any
@returns {Error}
|
JSBindingError
|
javascript
|
uber/h3-js
|
lib/errors.js
|
https://github.com/uber/h3-js/blob/master/lib/errors.js
|
Apache-2.0
|
function throwIfError(errCode) {
if (errCode !== 0) {
throw H3LibraryError(errCode);
}
}
|
Throw a JavaScript error if the C library return code is an error
@private
@param {number} errCode Error code from the H3 library
@throws {Error} Error if err is not E_SUCCESS (0)
|
throwIfError
|
javascript
|
uber/h3-js
|
lib/errors.js
|
https://github.com/uber/h3-js/blob/master/lib/errors.js
|
Apache-2.0
|
function polygonToCellsFlagsToNumber(flags) {
switch (flags) {
case POLYGON_TO_CELLS_FLAGS.containmentCenter:
return 0;
case POLYGON_TO_CELLS_FLAGS.containmentFull:
return 1;
case POLYGON_TO_CELLS_FLAGS.containmentOverlapping:
return 2;
case POLYGON_TO_CELLS_FLAGS.containmentOverlappingBbox:
return 3;
default:
throw JSBindingError(E_OPTION_INVALID, flags);
}
}
|
@private
@param {string} flags Value from POLYGON_TO_CELLS_FLAGS
@returns {number} Flag value
@throws {H3Error} If invalid
|
polygonToCellsFlagsToNumber
|
javascript
|
uber/h3-js
|
lib/h3core.js
|
https://github.com/uber/h3-js/blob/master/lib/h3core.js
|
Apache-2.0
|
function validateRes(res) {
if (typeof res !== 'number' || res < 0 || res > 15 || Math.floor(res) !== res) {
throw H3LibraryError(E_RES_DOMAIN, res);
}
return res;
}
|
Validate a resolution, throwing an error if invalid
@private
@param {unknown} res Value to validate
@return {number} Valid res
@throws {H3Error} If invalid
|
validateRes
|
javascript
|
uber/h3-js
|
lib/h3core.js
|
https://github.com/uber/h3-js/blob/master/lib/h3core.js
|
Apache-2.0
|
function validateH3Index(h3Index) {
if (!h3Index) throw JSBindingError(E_NULL_INDEX);
return h3Index;
}
|
Assert H3 index output, throwing an error if null
@private
@param {H3Index | null} h3Index Index to validate
@return {H3Index}
@throws {H3Error} If invalid
|
validateH3Index
|
javascript
|
uber/h3-js
|
lib/h3core.js
|
https://github.com/uber/h3-js/blob/master/lib/h3core.js
|
Apache-2.0
|
function validateArrayLength(length) {
if (length > MAX_JS_ARRAY_LENGTH) {
throw JSBindingError(E_ARRAY_LENGTH, length);
}
return length;
}
|
Validate an array length. JS will throw its own error if you try
to create an array larger than 2^32 - 1, but validating beforehand
allows us to exit early before we try to process large amounts
of data that won't even fit in an output array
@private
@param {number} length Length to validate
@return {number} Valid array length
@throws {H3Error} If invalid
|
validateArrayLength
|
javascript
|
uber/h3-js
|
lib/h3core.js
|
https://github.com/uber/h3-js/blob/master/lib/h3core.js
|
Apache-2.0
|
function h3IndexToSplitLong(h3Index) {
if (
Array.isArray(h3Index) &&
h3Index.length === 2 &&
Number.isInteger(h3Index[0]) &&
Number.isInteger(h3Index[1])
) {
return h3Index;
}
if (typeof h3Index !== 'string' || INVALID_HEXIDECIMAL_CHAR.test(h3Index)) {
return [0, 0];
}
const upper = parseInt(h3Index.substring(0, h3Index.length - 8), BASE_16);
const lower = parseInt(h3Index.substring(h3Index.length - 8), BASE_16);
return [lower, upper];
}
|
Convert an H3 index (64-bit hexidecimal string) into a "split long" - a pair of 32-bit ints
@param {H3IndexInput} h3Index H3 index to check
@return {SplitLong} A two-element array with 32 lower bits and 32 upper bits
|
h3IndexToSplitLong
|
javascript
|
uber/h3-js
|
lib/h3core.js
|
https://github.com/uber/h3-js/blob/master/lib/h3core.js
|
Apache-2.0
|
function hexFrom32Bit(num) {
if (num >= 0) {
return num.toString(BASE_16);
}
// Handle negative numbers
num = num & 0x7fffffff;
let tempStr = zeroPad(8, num.toString(BASE_16));
const topNum = (parseInt(tempStr[0], BASE_16) + 8).toString(BASE_16);
tempStr = topNum + tempStr.substring(1);
return tempStr;
}
|
Convert a 32-bit int to a hexdecimal string
@private
@param {number} num Integer to convert
@return {H3Index} Hexidecimal string
|
hexFrom32Bit
|
javascript
|
uber/h3-js
|
lib/h3core.js
|
https://github.com/uber/h3-js/blob/master/lib/h3core.js
|
Apache-2.0
|
function splitLongToH3Index(lower, upper) {
return hexFrom32Bit(upper) + zeroPad(8, hexFrom32Bit(lower));
}
|
Get a H3 index string from a split long (pair of 32-bit ints)
@param {number} lower Lower 32 bits
@param {number} upper Upper 32 bits
@return {H3Index} H3 index
|
splitLongToH3Index
|
javascript
|
uber/h3-js
|
lib/h3core.js
|
https://github.com/uber/h3-js/blob/master/lib/h3core.js
|
Apache-2.0
|
function zeroPad(fullLen, numStr) {
const numZeroes = fullLen - numStr.length;
let outStr = '';
for (let i = 0; i < numZeroes; i++) {
outStr += '0';
}
outStr = outStr + numStr;
return outStr;
}
|
Zero-pad a string to a given length
@private
@param {number} fullLen Target length
@param {string} numStr String to zero-pad
@return {string} Zero-padded string
|
zeroPad
|
javascript
|
uber/h3-js
|
lib/h3core.js
|
https://github.com/uber/h3-js/blob/master/lib/h3core.js
|
Apache-2.0
|
function numberToSplitLong(num) {
if (typeof num !== 'number') {
return [0, 0];
}
return [num | 0, (num / UPPER_BIT_DIVISOR) | 0];
}
|
Convert a JS double-precision floating point number to a split long
@private
@param {number} num Number to convert
@return {SplitLong} A two-element array with 32 lower bits and 32 upper bits
|
numberToSplitLong
|
javascript
|
uber/h3-js
|
lib/h3core.js
|
https://github.com/uber/h3-js/blob/master/lib/h3core.js
|
Apache-2.0
|
function polygonArrayToGeoLoop(polygonArray, geoLoop, isGeoJson) {
const numVerts = polygonArray.length;
const geoCoordArray = C._calloc(numVerts, SZ_LATLNG);
// Support [lng, lat] pairs if GeoJSON is specified
const latIndex = isGeoJson ? 1 : 0;
const lngIndex = isGeoJson ? 0 : 1;
for (let i = 0; i < numVerts * 2; i += 2) {
C.HEAPF64.set(
[polygonArray[i / 2][latIndex], polygonArray[i / 2][lngIndex]].map(degsToRads),
geoCoordArray / SZ_DBL + i
);
}
C.HEAPU32.set([numVerts, geoCoordArray], geoLoop / SZ_INT);
return geoLoop;
}
|
Populate a C-appropriate GeoLoop struct from a polygon array
@private
@param {number[][]} polygonArray Polygon, as an array of coordinate pairs
@param {number} geoLoop C pointer to a GeoLoop struct
@param {boolean} isGeoJson Whether coordinates are in [lng, lat] order per GeoJSON spec
@return {number} C pointer to populated GeoLoop struct
|
polygonArrayToGeoLoop
|
javascript
|
uber/h3-js
|
lib/h3core.js
|
https://github.com/uber/h3-js/blob/master/lib/h3core.js
|
Apache-2.0
|
function coordinatesToGeoPolygon(coordinates, isGeoJson) {
// Any loops beyond the first loop are holes
const numHoles = coordinates.length - 1;
const geoPolygon = C._calloc(SZ_GEOPOLYGON);
// Byte positions within the struct
const geoLoopOffset = 0;
const numHolesOffset = geoLoopOffset + SZ_GEOLOOP;
const holesOffset = numHolesOffset + SZ_INT;
// geoLoop is first part of struct
polygonArrayToGeoLoop(coordinates[0], geoPolygon + geoLoopOffset, isGeoJson);
let holes;
if (numHoles > 0) {
holes = C._calloc(numHoles, SZ_GEOLOOP);
for (let i = 0; i < numHoles; i++) {
polygonArrayToGeoLoop(coordinates[i + 1], holes + SZ_GEOLOOP * i, isGeoJson);
}
}
C.setValue(geoPolygon + numHolesOffset, numHoles, 'i32');
C.setValue(geoPolygon + holesOffset, holes, 'i32');
return geoPolygon;
}
|
Create a C-appropriate GeoPolygon struct from an array of polygons
@private
@param {number[][][]} coordinates Array of polygons, each an array of coordinate pairs
@param {boolean} isGeoJson Whether coordinates are in [lng, lat] order per GeoJSON spec
@return {number} C pointer to populated GeoPolygon struct
|
coordinatesToGeoPolygon
|
javascript
|
uber/h3-js
|
lib/h3core.js
|
https://github.com/uber/h3-js/blob/master/lib/h3core.js
|
Apache-2.0
|
function destroyGeoPolygon(geoPolygon) {
// Byte positions within the struct
const geoLoopOffset = 0;
const numHolesOffset = geoLoopOffset + SZ_GEOLOOP;
const holesOffset = numHolesOffset + SZ_INT;
// Offset of the geoLoop vertex array pointer within the GeoLoop struct
const geoLoopArrayOffset = SZ_INT;
// Free the outer vertex array
C._free(C.getValue(geoPolygon + geoLoopOffset + geoLoopArrayOffset, 'i8*'));
// Free the vertex array for the holes, if any
const numHoles = C.getValue(geoPolygon + numHolesOffset, 'i32');
if (numHoles > 0) {
const holes = C.getValue(geoPolygon + holesOffset, 'i32');
for (let i = 0; i < numHoles; i++) {
C._free(C.getValue(holes + SZ_GEOLOOP * i + geoLoopArrayOffset, 'i8*'));
}
C._free(holes);
}
C._free(geoPolygon);
}
|
Free memory allocated for a GeoPolygon struct. It is an error to access the struct
after passing it to this method.
@private
@param {number} geoPolygon C pointer to GeoPolygon struct
@return {void}
|
destroyGeoPolygon
|
javascript
|
uber/h3-js
|
lib/h3core.js
|
https://github.com/uber/h3-js/blob/master/lib/h3core.js
|
Apache-2.0
|
function readH3IndexFromPointer(cAddress, offset = 0) {
const lower = C.getValue(cAddress + SZ_H3INDEX * offset, 'i32');
const upper = C.getValue(cAddress + SZ_H3INDEX * offset + SZ_INT, 'i32');
// The lower bits are allowed to be 0s, but if the upper bits are 0
// this represents an invalid H3 index
return upper ? splitLongToH3Index(lower, upper) : null;
}
|
Read an H3 index from a pointer to C memory.
@private
@param {number} cAddress Pointer to allocated C memory
@param {number} offset Offset, in number of H3 indexes, in case we're
reading an array
@return {H3Index | null} H3 index, or null if index was invalid
|
readH3IndexFromPointer
|
javascript
|
uber/h3-js
|
lib/h3core.js
|
https://github.com/uber/h3-js/blob/master/lib/h3core.js
|
Apache-2.0
|
function readBooleanFromPointer(cAddress, offset = 0) {
const val = C.getValue(cAddress + SZ_INT * offset, 'i32');
return Boolean(val);
}
|
Read a boolean (32 bit) from a pointer to C memory.
@private
@param {number} cAddress Pointer to allocated C memory
@param {number} offset Offset, in number of booleans, in case we're
reading an array
@return {Boolean} Boolean value
|
readBooleanFromPointer
|
javascript
|
uber/h3-js
|
lib/h3core.js
|
https://github.com/uber/h3-js/blob/master/lib/h3core.js
|
Apache-2.0
|
function readDoubleFromPointer(cAddress, offset = 0) {
return C.getValue(cAddress + SZ_DBL * offset, 'double');
}
|
Read a double from a pointer to C memory.
@private
@param {number} cAddress Pointer to allocated C memory
@param {number} offset Offset, in number of doubles, in case we're
reading an array
@return {number} Double value
|
readDoubleFromPointer
|
javascript
|
uber/h3-js
|
lib/h3core.js
|
https://github.com/uber/h3-js/blob/master/lib/h3core.js
|
Apache-2.0
|
function readInt64AsDoubleFromPointer(cAddress) {
return H3.readInt64AsDoubleFromPointer(cAddress);
}
|
Read a 64-bit int from a pointer to C memory into a JS 64-bit float.
Note that this may lose precision if larger than MAX_SAFE_INTEGER
@private
@param {number} cAddress Pointer to allocated C memory
@return {number} Double value
|
readInt64AsDoubleFromPointer
|
javascript
|
uber/h3-js
|
lib/h3core.js
|
https://github.com/uber/h3-js/blob/master/lib/h3core.js
|
Apache-2.0
|
function storeH3Index(h3Index, cAddress, offset) {
// HEAPU32 is a typed array projection on the index space
// as unsigned 32-bit integers. This means the index needs
// to be divided by SZ_INT (4) to access correctly. Also,
// the H3 index is 64 bits, so we skip by twos as we're writing
// to 32-bit integers in the proper order.
C.HEAPU32.set(h3IndexToSplitLong(h3Index), cAddress / SZ_INT + 2 * offset);
}
|
Store an H3 index in C memory. Primarily used as an efficient way to
write sets of hexagons.
@private
@param {H3IndexInput} h3Index H3 index to store
@param {number} cAddress Pointer to allocated C memory
@param {number} offset Offset, in number of H3 indexes from beginning
of the current array
|
storeH3Index
|
javascript
|
uber/h3-js
|
lib/h3core.js
|
https://github.com/uber/h3-js/blob/master/lib/h3core.js
|
Apache-2.0
|
function readArrayOfH3Indexes(cAddress, maxCount) {
const out = [];
for (let i = 0; i < maxCount; i++) {
const h3Index = readH3IndexFromPointer(cAddress, i);
if (h3Index !== null) {
out.push(h3Index);
}
}
return out;
}
|
Read an array of 64-bit H3 indexes from C and convert to a JS array of
H3 index strings
@private
@param {number} cAddress Pointer to C ouput array
@param {number} maxCount Max number of hexagons in array. Hexagons with
the value 0 will be skipped, so this isn't
necessarily the length of the output array.
@return {H3Index[]} Array of H3 indexes
|
readArrayOfH3Indexes
|
javascript
|
uber/h3-js
|
lib/h3core.js
|
https://github.com/uber/h3-js/blob/master/lib/h3core.js
|
Apache-2.0
|
function storeArrayOfH3Indexes(cAddress, hexagons) {
// Assuming the cAddress points to an already appropriately
// allocated space
const count = hexagons.length;
for (let i = 0; i < count; i++) {
storeH3Index(hexagons[i], cAddress, i);
}
}
|
Store an array of H3 index strings as a C array of 64-bit integers.
@private
@param {number} cAddress Pointer to C input array
@param {H3IndexInput[]} hexagons H3 indexes to pass to the C lib
|
storeArrayOfH3Indexes
|
javascript
|
uber/h3-js
|
lib/h3core.js
|
https://github.com/uber/h3-js/blob/master/lib/h3core.js
|
Apache-2.0
|
function storeLatLng(lat, lng) {
const geoCoord = C._calloc(1, SZ_LATLNG);
C.HEAPF64.set([lat, lng].map(degsToRads), geoCoord / SZ_DBL);
return geoCoord;
}
|
Populate a C-appropriate LatLng struct from a [lat, lng] array
@private
@param {number} lat Coordinate latitude
@param {number} lng Coordinate longitude
@return {number} C pointer to populated LatLng struct
|
storeLatLng
|
javascript
|
uber/h3-js
|
lib/h3core.js
|
https://github.com/uber/h3-js/blob/master/lib/h3core.js
|
Apache-2.0
|
function readSingleCoord(cAddress) {
return radsToDegs(C.getValue(cAddress, 'double'));
}
|
Read a single lat or lng value
@private
@param {number} cAddress Pointer to C value
@return {number}
|
readSingleCoord
|
javascript
|
uber/h3-js
|
lib/h3core.js
|
https://github.com/uber/h3-js/blob/master/lib/h3core.js
|
Apache-2.0
|
function readLatLng(cAddress) {
return [readSingleCoord(cAddress), readSingleCoord(cAddress + SZ_DBL)];
}
|
Read a LatLng from C and return a [lat, lng] pair.
@private
@param {number} cAddress Pointer to C struct
@return {CoordPair} [lat, lng] pair
|
readLatLng
|
javascript
|
uber/h3-js
|
lib/h3core.js
|
https://github.com/uber/h3-js/blob/master/lib/h3core.js
|
Apache-2.0
|
function readLatLngGeoJson(cAddress) {
return [readSingleCoord(cAddress + SZ_DBL), readSingleCoord(cAddress)];
}
|
Read a LatLng from C and return a GeoJSON-style [lng, lat] pair.
@private
@param {number} cAddress Pointer to C struct
@return {CoordPair} [lng, lat] pair
|
readLatLngGeoJson
|
javascript
|
uber/h3-js
|
lib/h3core.js
|
https://github.com/uber/h3-js/blob/master/lib/h3core.js
|
Apache-2.0
|
function readCellBoundary(cellBoundary, geoJsonCoords, closedLoop) {
const numVerts = C.getValue(cellBoundary, 'i32');
// Note that though numVerts is an int, the coordinate doubles have to be
// aligned to 8 bytes, hence the 8-byte offset here
const vertsPos = cellBoundary + SZ_DBL;
const out = [];
// Support [lng, lat] pairs if GeoJSON is specified
const readCoord = geoJsonCoords ? readLatLngGeoJson : readLatLng;
for (let i = 0; i < numVerts * 2; i += 2) {
out.push(readCoord(vertsPos + SZ_DBL * i));
}
if (closedLoop) {
// Close loop if GeoJSON is specified
out.push(out[0]);
}
return out;
}
|
Read the CellBoundary structure into a list of geo coordinate pairs
@private
@param {number} cellBoundary C pointer to CellBoundary struct
@param {boolean} [geoJsonCoords] Whether to provide GeoJSON coordinate order: [lng, lat]
@param {boolean} [closedLoop] Whether to close the loop
@return {CoordPair[]} Array of geo coordinate pairs
|
readCellBoundary
|
javascript
|
uber/h3-js
|
lib/h3core.js
|
https://github.com/uber/h3-js/blob/master/lib/h3core.js
|
Apache-2.0
|
function readMultiPolygon(polygon, formatAsGeoJson) {
const output = [];
const readCoord = formatAsGeoJson ? readLatLngGeoJson : readLatLng;
let loops;
let loop;
let coords;
let coord;
// Loop through the linked structure, building the output
while (polygon) {
output.push((loops = []));
// Follow ->first pointer
loop = C.getValue(polygon, 'i8*');
while (loop) {
loops.push((coords = []));
// Follow ->first pointer
coord = C.getValue(loop, 'i8*');
while (coord) {
coords.push(readCoord(coord));
// Follow ->next pointer
coord = C.getValue(coord + SZ_DBL * 2, 'i8*');
}
if (formatAsGeoJson) {
// Close loop if GeoJSON is requested
coords.push(coords[0]);
}
// Follow ->next pointer
loop = C.getValue(loop + SZ_PTR * 2, 'i8*');
}
// Follow ->next pointer
polygon = C.getValue(polygon + SZ_PTR * 2, 'i8*');
}
return output;
}
|
Read the LinkedGeoPolygon structure into a nested array of MultiPolygon coordinates
@private
@param {number} polygon C pointer to LinkedGeoPolygon struct
@param {boolean} [formatAsGeoJson] Whether to provide GeoJSON output: [lng, lat], closed loops
@return {CoordPair[][][]} MultiPolygon-style output.
|
readMultiPolygon
|
javascript
|
uber/h3-js
|
lib/h3core.js
|
https://github.com/uber/h3-js/blob/master/lib/h3core.js
|
Apache-2.0
|
function readCoordIJ(cAddress) {
return {
i: C.getValue(cAddress, 'i32'),
j: C.getValue(cAddress + SZ_INT, 'i32')
};
}
|
Read a CoordIJ from C and return an {i, j} pair.
@private
@param {number} cAddress Pointer to C struct
@return {CoordIJ} {i, j} pair
|
readCoordIJ
|
javascript
|
uber/h3-js
|
lib/h3core.js
|
https://github.com/uber/h3-js/blob/master/lib/h3core.js
|
Apache-2.0
|
function storeCoordIJ(cAddress, {i, j}) {
C.setValue(cAddress, i, 'i32');
C.setValue(cAddress + SZ_INT, j, 'i32');
}
|
Store an {i, j} pair to a C CoordIJ struct.
@private
@param {number} cAddress Pointer to C memory
@param {CoordIJ} ij {i,j} pair to store
@return {void}
|
storeCoordIJ
|
javascript
|
uber/h3-js
|
lib/h3core.js
|
https://github.com/uber/h3-js/blob/master/lib/h3core.js
|
Apache-2.0
|
function readArrayOfPositiveIntegers(cAddress, count) {
const out = [];
for (let i = 0; i < count; i++) {
const int = C.getValue(cAddress + SZ_INT * i, 'i32');
if (int >= 0) {
out.push(int);
}
}
return out;
}
|
Read an array of positive integers array from C. Negative
values are considered invalid and ignored in output.
@private
@param {number} cAddress Pointer to C array
@param {number} count Length of C array
@return {number[]} Javascript integer array
|
readArrayOfPositiveIntegers
|
javascript
|
uber/h3-js
|
lib/h3core.js
|
https://github.com/uber/h3-js/blob/master/lib/h3core.js
|
Apache-2.0
|
function isValidCell(h3Index) {
const [lower, upper] = h3IndexToSplitLong(h3Index);
return Boolean(H3.isValidCell(lower, upper));
}
|
Whether a given string represents a valid H3 index
@static
@param {H3IndexInput} h3Index H3 index to check
@return {boolean} Whether the index is valid
|
isValidCell
|
javascript
|
uber/h3-js
|
lib/h3core.js
|
https://github.com/uber/h3-js/blob/master/lib/h3core.js
|
Apache-2.0
|
function isPentagon(h3Index) {
const [lower, upper] = h3IndexToSplitLong(h3Index);
return Boolean(H3.isPentagon(lower, upper));
}
|
Whether the given H3 index is a pentagon
@static
@param {H3IndexInput} h3Index H3 index to check
@return {boolean} isPentagon
|
isPentagon
|
javascript
|
uber/h3-js
|
lib/h3core.js
|
https://github.com/uber/h3-js/blob/master/lib/h3core.js
|
Apache-2.0
|
function isResClassIII(h3Index) {
const [lower, upper] = h3IndexToSplitLong(h3Index);
return Boolean(H3.isResClassIII(lower, upper));
}
|
Whether the given H3 index is in a Class III resolution (rotated versus
the icosahedron and subject to shape distortion adding extra points on
icosahedron edges, making them not true hexagons).
@static
@param {H3IndexInput} h3Index H3 index to check
@return {boolean} isResClassIII
|
isResClassIII
|
javascript
|
uber/h3-js
|
lib/h3core.js
|
https://github.com/uber/h3-js/blob/master/lib/h3core.js
|
Apache-2.0
|
function getBaseCellNumber(h3Index) {
const [lower, upper] = h3IndexToSplitLong(h3Index);
return H3.getBaseCellNumber(lower, upper);
}
|
Get the number of the base cell for a given H3 index
@static
@param {H3IndexInput} h3Index H3 index to get the base cell for
@return {number} Index of the base cell (0-121)
|
getBaseCellNumber
|
javascript
|
uber/h3-js
|
lib/h3core.js
|
https://github.com/uber/h3-js/blob/master/lib/h3core.js
|
Apache-2.0
|
function getIcosahedronFaces(h3Index) {
const [lower, upper] = h3IndexToSplitLong(h3Index);
const countPtr = C._malloc(SZ_INT);
try {
throwIfError(H3.maxFaceCount(lower, upper, countPtr));
const count = C.getValue(countPtr, 'i32');
const faces = C._malloc(SZ_INT * count);
try {
throwIfError(H3.getIcosahedronFaces(lower, upper, faces));
return readArrayOfPositiveIntegers(faces, count);
} finally {
C._free(faces);
}
} finally {
C._free(countPtr);
}
}
|
Get the indices of all icosahedron faces intersected by a given H3 index
@static
@param {H3IndexInput} h3Index H3 index to get faces for
@return {number[]} Indices (0-19) of all intersected faces
@throws {H3Error} If input is invalid
|
getIcosahedronFaces
|
javascript
|
uber/h3-js
|
lib/h3core.js
|
https://github.com/uber/h3-js/blob/master/lib/h3core.js
|
Apache-2.0
|
function getResolution(h3Index) {
const [lower, upper] = h3IndexToSplitLong(h3Index);
if (!H3.isValidCell(lower, upper)) {
// Compatability with stated API
return -1;
}
return H3.getResolution(lower, upper);
}
|
Returns the resolution of an H3 index
@static
@param {H3IndexInput} h3Index H3 index to get resolution
@return {number} The number (0-15) resolution, or -1 if invalid
|
getResolution
|
javascript
|
uber/h3-js
|
lib/h3core.js
|
https://github.com/uber/h3-js/blob/master/lib/h3core.js
|
Apache-2.0
|
function latLngToCell(lat, lng, res) {
const latLng = C._malloc(SZ_LATLNG);
// Slightly more efficient way to set the memory
C.HEAPF64.set([lat, lng].map(degsToRads), latLng / SZ_DBL);
// Read value as a split long
const h3Index = C._malloc(SZ_H3INDEX);
try {
throwIfError(H3.latLngToCell(latLng, res, h3Index));
return validateH3Index(readH3IndexFromPointer(h3Index));
} finally {
C._free(h3Index);
C._free(latLng);
}
}
|
Get the hexagon containing a lat,lon point
@static
@param {number} lat Latitude of point
@param {number} lng Longtitude of point
@param {number} res Resolution of hexagons to return
@return {H3Index} H3 index
@throws {H3Error} If input is invalid
|
latLngToCell
|
javascript
|
uber/h3-js
|
lib/h3core.js
|
https://github.com/uber/h3-js/blob/master/lib/h3core.js
|
Apache-2.0
|
function cellToLatLng(h3Index) {
const latLng = C._malloc(SZ_LATLNG);
const [lower, upper] = h3IndexToSplitLong(h3Index);
try {
throwIfError(H3.cellToLatLng(lower, upper, latLng));
return readLatLng(latLng);
} finally {
C._free(latLng);
}
}
|
Get the lat,lon center of a given hexagon
@static
@param {H3IndexInput} h3Index H3 index
@return {CoordPair} Point as a [lat, lng] pair
@throws {H3Error} If input is invalid
|
cellToLatLng
|
javascript
|
uber/h3-js
|
lib/h3core.js
|
https://github.com/uber/h3-js/blob/master/lib/h3core.js
|
Apache-2.0
|
function cellToBoundary(h3Index, formatAsGeoJson) {
const cellBoundary = C._malloc(SZ_CELLBOUNDARY);
const [lower, upper] = h3IndexToSplitLong(h3Index);
try {
throwIfError(H3.cellToBoundary(lower, upper, cellBoundary));
return readCellBoundary(cellBoundary, formatAsGeoJson, formatAsGeoJson);
} finally {
C._free(cellBoundary);
}
}
|
Get the vertices of a given hexagon (or pentagon), as an array of [lat, lng]
points. For pentagons and hexagons on the edge of an icosahedron face, this
function may return up to 10 vertices.
@static
@param {H3IndexInput} h3Index H3 index
@param {boolean} [formatAsGeoJson] Whether to provide GeoJSON output: [lng, lat], closed loops
@return {CoordPair[]} Array of [lat, lng] pairs
@throws {H3Error} If input is invalid
|
cellToBoundary
|
javascript
|
uber/h3-js
|
lib/h3core.js
|
https://github.com/uber/h3-js/blob/master/lib/h3core.js
|
Apache-2.0
|
function cellToParent(h3Index, res) {
const [lower, upper] = h3IndexToSplitLong(h3Index);
const parent = C._malloc(SZ_H3INDEX);
try {
throwIfError(H3.cellToParent(lower, upper, res, parent));
return validateH3Index(readH3IndexFromPointer(parent));
} finally {
C._free(parent);
}
}
|
Get the parent of the given hexagon at a particular resolution
@static
@param {H3IndexInput} h3Index H3 index to get parent for
@param {number} res Resolution of hexagon to return
@return {H3Index} H3 index of parent, or null for invalid input
@throws {H3Error} If input is invalid
|
cellToParent
|
javascript
|
uber/h3-js
|
lib/h3core.js
|
https://github.com/uber/h3-js/blob/master/lib/h3core.js
|
Apache-2.0
|
function cellToChildren(h3Index, res) {
// Bad input in this case can potentially result in high computation volume
// using the current C algorithm. Validate and return an empty array on failure.
if (!isValidCell(h3Index)) {
return [];
}
const [lower, upper] = h3IndexToSplitLong(h3Index);
const count = validateArrayLength(cellToChildrenSize(h3Index, res));
const hexagons = C._calloc(count, SZ_H3INDEX);
try {
throwIfError(H3.cellToChildren(lower, upper, res, hexagons));
return readArrayOfH3Indexes(hexagons, count);
} finally {
C._free(hexagons);
}
}
|
Get the children/descendents of the given hexagon at a particular resolution
@static
@param {H3IndexInput} h3Index H3 index to get children for
@param {number} res Resolution of hexagons to return
@return {H3Index[]} H3 indexes of children, or empty array for invalid input
@throws {H3Error} If resolution is invalid or output is too large for JS
|
cellToChildren
|
javascript
|
uber/h3-js
|
lib/h3core.js
|
https://github.com/uber/h3-js/blob/master/lib/h3core.js
|
Apache-2.0
|
function cellToChildrenSize(h3Index, res) {
if (!isValidCell(h3Index)) {
throw H3LibraryError(E_CELL_INVALID);
}
const [lower, upper] = h3IndexToSplitLong(h3Index);
const countPtr = C._malloc(SZ_INT64);
try {
throwIfError(H3.cellToChildrenSize(lower, upper, res, countPtr));
return readInt64AsDoubleFromPointer(countPtr);
} finally {
C._free(countPtr);
}
}
|
Get the number of children for a cell at a given resolution
@static
@param {H3IndexInput} h3Index H3 index to get child count for
@param {number} res Child resolution
@return {number} Number of children at res for the given cell
@throws {H3Error} If cell or parentRes are invalid
|
cellToChildrenSize
|
javascript
|
uber/h3-js
|
lib/h3core.js
|
https://github.com/uber/h3-js/blob/master/lib/h3core.js
|
Apache-2.0
|
function cellToCenterChild(h3Index, res) {
const [lower, upper] = h3IndexToSplitLong(h3Index);
const centerChild = C._malloc(SZ_H3INDEX);
try {
throwIfError(H3.cellToCenterChild(lower, upper, res, centerChild));
return validateH3Index(readH3IndexFromPointer(centerChild));
} finally {
C._free(centerChild);
}
}
|
Get the center child of the given hexagon at a particular resolution
@static
@param {H3IndexInput} h3Index H3 index to get center child for
@param {number} res Resolution of cell to return
@return {H3Index} H3 index of child, or null for invalid input
@throws {H3Error} If resolution is invalid
|
cellToCenterChild
|
javascript
|
uber/h3-js
|
lib/h3core.js
|
https://github.com/uber/h3-js/blob/master/lib/h3core.js
|
Apache-2.0
|
function cellToChildPos(h3Index, parentRes) {
const [lower, upper] = h3IndexToSplitLong(h3Index);
const childPos = C._malloc(SZ_INT64);
try {
throwIfError(H3.cellToChildPos(lower, upper, parentRes, childPos));
return readInt64AsDoubleFromPointer(childPos);
} finally {
C._free(childPos);
}
}
|
Get the position of the cell within an ordered list of all children of the
cell's parent at the specified resolution.
@static
@param {H3IndexInput} h3Index H3 index to get child pos for
@param {number} parentRes Resolution of reference parent
@return {number} Position of child within parent at parentRes
@throws {H3Error} If cell or parentRes are invalid
|
cellToChildPos
|
javascript
|
uber/h3-js
|
lib/h3core.js
|
https://github.com/uber/h3-js/blob/master/lib/h3core.js
|
Apache-2.0
|
function childPosToCell(childPos, h3Index, childRes) {
const [cpLower, cpUpper] = numberToSplitLong(childPos);
const [lower, upper] = h3IndexToSplitLong(h3Index);
const child = C._malloc(SZ_H3INDEX);
try {
throwIfError(H3.childPosToCell(cpLower, cpUpper, lower, upper, childRes, child));
return validateH3Index(readH3IndexFromPointer(child));
} finally {
C._free(child);
}
}
|
Get the child cell at a given position within an ordered list of all children
at the specified resolution
@static
@param {number} childPos Position of the child cell to get
@param {H3IndexInput} h3Index H3 index of the parent cell
@param {number} childRes Resolution of child cell to return
@return {H3Index} H3 index of child
@throws {H3Error} If input is invalid
|
childPosToCell
|
javascript
|
uber/h3-js
|
lib/h3core.js
|
https://github.com/uber/h3-js/blob/master/lib/h3core.js
|
Apache-2.0
|
function gridDisk(h3Index, ringSize) {
const [lower, upper] = h3IndexToSplitLong(h3Index);
const countPtr = C._malloc(SZ_INT64);
try {
throwIfError(H3.maxGridDiskSize(ringSize, countPtr));
const count = validateArrayLength(readInt64AsDoubleFromPointer(countPtr));
const hexagons = C._calloc(count, SZ_H3INDEX);
try {
throwIfError(H3.gridDisk(lower, upper, ringSize, hexagons));
return readArrayOfH3Indexes(hexagons, count);
} finally {
C._free(hexagons);
}
} finally {
C._free(countPtr);
}
}
|
Get all hexagons in a k-ring around a given center. The order of the hexagons is undefined.
@static
@param {H3IndexInput} h3Index H3 index of center hexagon
@param {number} ringSize Radius of k-ring
@return {H3Index[]} H3 indexes for all hexagons in ring
@throws {H3Error} If input is invalid or output is too large for JS
|
gridDisk
|
javascript
|
uber/h3-js
|
lib/h3core.js
|
https://github.com/uber/h3-js/blob/master/lib/h3core.js
|
Apache-2.0
|
function gridDiskDistances(h3Index, ringSize) {
const [lower, upper] = h3IndexToSplitLong(h3Index);
const countPtr = C._malloc(SZ_INT64);
try {
throwIfError(H3.maxGridDiskSize(ringSize, countPtr));
const count = validateArrayLength(readInt64AsDoubleFromPointer(countPtr));
const kRings = C._calloc(count, SZ_H3INDEX);
const distances = C._calloc(count, SZ_INT);
try {
throwIfError(H3.gridDiskDistances(lower, upper, ringSize, kRings, distances));
/**
* An array of empty arrays to hold the output
* @type {string[][]}
* @private
*/
const out = [];
for (let i = 0; i < ringSize + 1; i++) {
out.push([]);
}
// Read the array of hexagons, putting them into the appropriate rings
for (let i = 0; i < count; i++) {
const cell = readH3IndexFromPointer(kRings, i);
const index = C.getValue(distances + SZ_INT * i, 'i32');
// eslint-disable-next-line max-depth
if (cell !== null) {
out[index].push(cell);
}
}
return out;
} finally {
C._free(kRings);
C._free(distances);
}
} finally {
C._free(countPtr);
}
}
|
Get all hexagons in a k-ring around a given center, in an array of arrays
ordered by distance from the origin. The order of the hexagons within each ring is undefined.
@static
@param {H3IndexInput} h3Index H3 index of center hexagon
@param {number} ringSize Radius of k-ring
@return {H3Index[][]} Array of arrays with H3 indexes for all hexagons each ring
@throws {H3Error} If input is invalid or output is too large for JS
|
gridDiskDistances
|
javascript
|
uber/h3-js
|
lib/h3core.js
|
https://github.com/uber/h3-js/blob/master/lib/h3core.js
|
Apache-2.0
|
function gridRingUnsafe(h3Index, ringSize) {
const maxCount = ringSize === 0 ? 1 : 6 * ringSize;
const hexagons = C._calloc(maxCount, SZ_H3INDEX);
try {
throwIfError(H3.gridRingUnsafe(...h3IndexToSplitLong(h3Index), ringSize, hexagons));
return readArrayOfH3Indexes(hexagons, maxCount);
} finally {
C._free(hexagons);
}
}
|
Get all hexagons in a hollow hexagonal ring centered at origin with sides of a given length.
Unlike gridDisk, this function will throw an error if there is a pentagon anywhere in the ring.
@static
@param {H3IndexInput} h3Index H3 index of center hexagon
@param {number} ringSize Radius of ring
@return {H3Index[]} H3 indexes for all hexagons in ring
@throws {Error} If the algorithm could not calculate the ring
@throws {H3Error} If input is invalid
|
gridRingUnsafe
|
javascript
|
uber/h3-js
|
lib/h3core.js
|
https://github.com/uber/h3-js/blob/master/lib/h3core.js
|
Apache-2.0
|
function polygonToCells(coordinates, res, isGeoJson) {
validateRes(res);
isGeoJson = Boolean(isGeoJson);
// Guard against empty input
if (coordinates.length === 0 || coordinates[0].length === 0) {
return [];
}
// Wrap to expected format if a single loop is provided
const polygon = typeof coordinates[0][0] === 'number' ? [coordinates] : coordinates;
const geoPolygon = coordinatesToGeoPolygon(
// @ts-expect-error - There's no way to convince TS that polygon is now number[][][]
polygon,
isGeoJson
);
const countPtr = C._malloc(SZ_INT64);
try {
throwIfError(H3.maxPolygonToCellsSize(geoPolygon, res, 0, countPtr));
const count = validateArrayLength(readInt64AsDoubleFromPointer(countPtr));
const hexagons = C._calloc(count, SZ_H3INDEX);
try {
throwIfError(H3.polygonToCells(geoPolygon, res, 0, hexagons));
return readArrayOfH3Indexes(hexagons, count);
} finally {
C._free(hexagons);
}
} finally {
C._free(countPtr);
destroyGeoPolygon(geoPolygon);
}
}
|
Get all hexagons with centers contained in a given polygon. The polygon
is specified with GeoJson semantics as an array of loops. Each loop is
an array of [lat, lng] pairs (or [lng, lat] if isGeoJson is specified).
The first loop is the perimeter of the polygon, and subsequent loops are
expected to be holes.
@static
@param {number[][] | number[][][]} coordinates
Array of loops, or a single loop
@param {number} res Resolution of hexagons to return
@param {boolean} [isGeoJson] Whether to expect GeoJson-style [lng, lat]
pairs instead of [lat, lng]
@return {H3Index[]} H3 indexes for all hexagons in polygon
@throws {H3Error} If input is invalid or output is too large for JS
|
polygonToCells
|
javascript
|
uber/h3-js
|
lib/h3core.js
|
https://github.com/uber/h3-js/blob/master/lib/h3core.js
|
Apache-2.0
|
function polygonToCellsExperimental(coordinates, res, flags, isGeoJson) {
validateRes(res);
isGeoJson = Boolean(isGeoJson);
const flagsInt = polygonToCellsFlagsToNumber(flags);
// Guard against empty input
if (coordinates.length === 0 || coordinates[0].length === 0) {
return [];
}
// Wrap to expected format if a single loop is provided
const polygon = typeof coordinates[0][0] === 'number' ? [coordinates] : coordinates;
const geoPolygon = coordinatesToGeoPolygon(
// @ts-expect-error - There's no way to convince TS that polygon is now number[][][]
polygon,
isGeoJson
);
const countPtr = C._malloc(SZ_INT64);
try {
throwIfError(H3.maxPolygonToCellsSizeExperimental(geoPolygon, res, flagsInt, countPtr));
const count = validateArrayLength(readInt64AsDoubleFromPointer(countPtr));
const hexagons = C._calloc(count, SZ_H3INDEX);
try {
throwIfError(
H3.polygonToCellsExperimental(
geoPolygon,
res,
flagsInt,
count,
UNUSED_UPPER_32_BITS,
hexagons
)
);
return readArrayOfH3Indexes(hexagons, count);
} finally {
C._free(hexagons);
}
} finally {
C._free(countPtr);
destroyGeoPolygon(geoPolygon);
}
}
|
Get all hexagons with centers contained in a given polygon. The polygon
is specified with GeoJson semantics as an array of loops. Each loop is
an array of [lat, lng] pairs (or [lng, lat] if isGeoJson is specified).
The first loop is the perimeter of the polygon, and subsequent loops are
expected to be holes.
@static
@param {number[][] | number[][][]} coordinates
Array of loops, or a single loop
@param {number} res Resolution of hexagons to return
@param {string} flags Value from POLYGON_TO_CELLS_FLAGS
@param {boolean} [isGeoJson] Whether to expect GeoJson-style [lng, lat]
pairs instead of [lat, lng]
@return {H3Index[]} H3 indexes for all hexagons in polygon
@throws {H3Error} If input is invalid or output is too large for JS
|
polygonToCellsExperimental
|
javascript
|
uber/h3-js
|
lib/h3core.js
|
https://github.com/uber/h3-js/blob/master/lib/h3core.js
|
Apache-2.0
|
function cellsToMultiPolygon(h3Indexes, formatAsGeoJson) {
// Early exit on empty input
if (!h3Indexes || !h3Indexes.length) {
return [];
}
// Set up input set
const indexCount = h3Indexes.length;
const set = C._calloc(indexCount, SZ_H3INDEX);
storeArrayOfH3Indexes(set, h3Indexes);
// Allocate memory for output linked polygon
const polygon = C._calloc(SZ_LINKED_GEOPOLYGON);
try {
throwIfError(H3.cellsToLinkedMultiPolygon(set, indexCount, polygon));
return readMultiPolygon(polygon, formatAsGeoJson);
} finally {
// Clean up
H3.destroyLinkedMultiPolygon(polygon);
C._free(polygon);
C._free(set);
}
}
|
Get the outlines of a set of H3 hexagons, returned in GeoJSON MultiPolygon
format (an array of polygons, each with an array of loops, each an array of
coordinates). Coordinates are returned as [lat, lng] pairs unless GeoJSON
is requested.
It is the responsibility of the caller to ensure that all hexagons in the
set have the same resolution and that the set contains no duplicates. Behavior
is undefined if duplicates or multiple resolutions are present, and the
algorithm may produce unexpected or invalid polygons.
@static
@param {H3IndexInput[]} h3Indexes H3 indexes to get outlines for
@param {boolean} [formatAsGeoJson] Whether to provide GeoJSON output: [lng, lat], closed loops
@return {CoordPair[][][]} MultiPolygon-style output.
@throws {H3Error} If input is invalid
|
cellsToMultiPolygon
|
javascript
|
uber/h3-js
|
lib/h3core.js
|
https://github.com/uber/h3-js/blob/master/lib/h3core.js
|
Apache-2.0
|
function compactCells(h3Set) {
if (!h3Set || !h3Set.length) {
return [];
}
// Set up input set
const count = h3Set.length;
const set = C._calloc(count, SZ_H3INDEX);
storeArrayOfH3Indexes(set, h3Set);
// Allocate memory for compacted hexagons, worst-case is no compaction
const compactedSet = C._calloc(count, SZ_H3INDEX);
try {
throwIfError(H3.compactCells(set, compactedSet, count, UNUSED_UPPER_32_BITS));
return readArrayOfH3Indexes(compactedSet, count);
} finally {
C._free(set);
C._free(compactedSet);
}
}
|
Compact a set of hexagons of the same resolution into a set of hexagons across
multiple levels that represents the same area.
@static
@param {H3IndexInput[]} h3Set H3 indexes to compact
@return {H3Index[]} Compacted H3 indexes
@throws {H3Error} If the input is invalid (e.g. duplicate hexagons)
|
compactCells
|
javascript
|
uber/h3-js
|
lib/h3core.js
|
https://github.com/uber/h3-js/blob/master/lib/h3core.js
|
Apache-2.0
|
function uncompactCells(compactedSet, res) {
validateRes(res);
if (!compactedSet || !compactedSet.length) {
return [];
}
// Set up input set
const count = compactedSet.length;
const set = C._calloc(count, SZ_H3INDEX);
storeArrayOfH3Indexes(set, compactedSet);
// Estimate how many hexagons we need (always overestimates if in error)
const uncompactCellSizePtr = C._malloc(SZ_INT64);
try {
throwIfError(
H3.uncompactCellsSize(set, count, UNUSED_UPPER_32_BITS, res, uncompactCellSizePtr)
);
const uncompactCellSize = validateArrayLength(
readInt64AsDoubleFromPointer(uncompactCellSizePtr)
);
// Allocate memory for uncompacted hexagons
const uncompactedSet = C._calloc(uncompactCellSize, SZ_H3INDEX);
try {
throwIfError(
H3.uncompactCells(
set,
count,
UNUSED_UPPER_32_BITS,
uncompactedSet,
uncompactCellSize,
UNUSED_UPPER_32_BITS,
res
)
);
return readArrayOfH3Indexes(uncompactedSet, uncompactCellSize);
} finally {
C._free(set);
C._free(uncompactedSet);
}
} finally {
C._free(uncompactCellSizePtr);
}
}
|
Uncompact a compacted set of hexagons to hexagons of the same resolution
@static
@param {H3IndexInput[]} compactedSet H3 indexes to uncompact
@param {number} res The resolution to uncompact to
@return {H3Index[]} The uncompacted H3 indexes
@throws {H3Error} If the input is invalid (e.g. invalid resolution)
|
uncompactCells
|
javascript
|
uber/h3-js
|
lib/h3core.js
|
https://github.com/uber/h3-js/blob/master/lib/h3core.js
|
Apache-2.0
|
function areNeighborCells(origin, destination) {
const [oLower, oUpper] = h3IndexToSplitLong(origin);
const [dLower, dUpper] = h3IndexToSplitLong(destination);
const out = C._malloc(SZ_INT);
try {
throwIfError(H3.areNeighborCells(oLower, oUpper, dLower, dUpper, out));
return readBooleanFromPointer(out);
} finally {
C._free(out);
}
}
|
Whether two H3 indexes are neighbors (share an edge)
@static
@param {H3IndexInput} origin Origin hexagon index
@param {H3IndexInput} destination Destination hexagon index
@return {boolean} Whether the hexagons share an edge
@throws {H3Error} If the input is invalid
|
areNeighborCells
|
javascript
|
uber/h3-js
|
lib/h3core.js
|
https://github.com/uber/h3-js/blob/master/lib/h3core.js
|
Apache-2.0
|
function cellsToDirectedEdge(origin, destination) {
const [oLower, oUpper] = h3IndexToSplitLong(origin);
const [dLower, dUpper] = h3IndexToSplitLong(destination);
const h3Index = C._malloc(SZ_H3INDEX);
try {
throwIfError(H3.cellsToDirectedEdge(oLower, oUpper, dLower, dUpper, h3Index));
return validateH3Index(readH3IndexFromPointer(h3Index));
} finally {
C._free(h3Index);
}
}
|
Get an H3 index representing a unidirectional edge for a given origin and destination
@static
@param {H3IndexInput} origin Origin hexagon index
@param {H3IndexInput} destination Destination hexagon index
@return {H3Index} H3 index of the edge, or null if no edge is shared
@throws {H3Error} If the input is invalid
|
cellsToDirectedEdge
|
javascript
|
uber/h3-js
|
lib/h3core.js
|
https://github.com/uber/h3-js/blob/master/lib/h3core.js
|
Apache-2.0
|
function getDirectedEdgeOrigin(edgeIndex) {
const [lower, upper] = h3IndexToSplitLong(edgeIndex);
const h3Index = C._malloc(SZ_H3INDEX);
try {
throwIfError(H3.getDirectedEdgeOrigin(lower, upper, h3Index));
return validateH3Index(readH3IndexFromPointer(h3Index));
} finally {
C._free(h3Index);
}
}
|
Get the origin hexagon from an H3 index representing a unidirectional edge
@static
@param {H3IndexInput} edgeIndex H3 index of the edge
@return {H3Index} H3 index of the edge origin
@throws {H3Error} If the input is invalid
|
getDirectedEdgeOrigin
|
javascript
|
uber/h3-js
|
lib/h3core.js
|
https://github.com/uber/h3-js/blob/master/lib/h3core.js
|
Apache-2.0
|
function getDirectedEdgeDestination(edgeIndex) {
const [lower, upper] = h3IndexToSplitLong(edgeIndex);
const h3Index = C._malloc(SZ_H3INDEX);
try {
throwIfError(H3.getDirectedEdgeDestination(lower, upper, h3Index));
return validateH3Index(readH3IndexFromPointer(h3Index));
} finally {
C._free(h3Index);
}
}
|
Get the destination hexagon from an H3 index representing a unidirectional edge
@static
@param {H3IndexInput} edgeIndex H3 index of the edge
@return {H3Index} H3 index of the edge destination
@throws {H3Error} If the input is invalid
|
getDirectedEdgeDestination
|
javascript
|
uber/h3-js
|
lib/h3core.js
|
https://github.com/uber/h3-js/blob/master/lib/h3core.js
|
Apache-2.0
|
function isValidDirectedEdge(edgeIndex) {
const [lower, upper] = h3IndexToSplitLong(edgeIndex);
return Boolean(H3.isValidDirectedEdge(lower, upper));
}
|
Whether the input is a valid unidirectional edge
@static
@param {H3IndexInput} edgeIndex H3 index of the edge
@return {boolean} Whether the index is valid
|
isValidDirectedEdge
|
javascript
|
uber/h3-js
|
lib/h3core.js
|
https://github.com/uber/h3-js/blob/master/lib/h3core.js
|
Apache-2.0
|
function directedEdgeToCells(edgeIndex) {
const [lower, upper] = h3IndexToSplitLong(edgeIndex);
const count = 2;
const hexagons = C._calloc(count, SZ_H3INDEX);
try {
throwIfError(H3.directedEdgeToCells(lower, upper, hexagons));
return readArrayOfH3Indexes(hexagons, count);
} finally {
C._free(hexagons);
}
}
|
Get the [origin, destination] pair represented by a unidirectional edge
@static
@param {H3IndexInput} edgeIndex H3 index of the edge
@return {H3Index[]} [origin, destination] pair as H3 indexes
@throws {H3Error} If the input is invalid
|
directedEdgeToCells
|
javascript
|
uber/h3-js
|
lib/h3core.js
|
https://github.com/uber/h3-js/blob/master/lib/h3core.js
|
Apache-2.0
|
function originToDirectedEdges(h3Index) {
const [lower, upper] = h3IndexToSplitLong(h3Index);
const count = 6;
const edges = C._calloc(count, SZ_H3INDEX);
try {
throwIfError(H3.originToDirectedEdges(lower, upper, edges));
return readArrayOfH3Indexes(edges, count);
} finally {
C._free(edges);
}
}
|
Get all of the unidirectional edges with the given H3 index as the origin (i.e. an edge to
every neighbor)
@static
@param {H3IndexInput} h3Index H3 index of the origin hexagon
@return {H3Index[]} List of unidirectional edges
@throws {H3Error} If the input is invalid
|
originToDirectedEdges
|
javascript
|
uber/h3-js
|
lib/h3core.js
|
https://github.com/uber/h3-js/blob/master/lib/h3core.js
|
Apache-2.0
|
function directedEdgeToBoundary(edgeIndex, formatAsGeoJson) {
const cellBoundary = C._malloc(SZ_CELLBOUNDARY);
const [lower, upper] = h3IndexToSplitLong(edgeIndex);
try {
throwIfError(H3.directedEdgeToBoundary(lower, upper, cellBoundary));
return readCellBoundary(cellBoundary, formatAsGeoJson);
} finally {
C._free(cellBoundary);
}
}
|
Get the vertices of a given edge as an array of [lat, lng] points. Note that for edges that
cross the edge of an icosahedron face, this may return 3 coordinates.
@static
@param {H3IndexInput} edgeIndex H3 index of the edge
@param {boolean} [formatAsGeoJson] Whether to provide GeoJSON output: [lng, lat]
@return {CoordPair[]} Array of geo coordinate pairs
@throws {H3Error} If the input is invalid
|
directedEdgeToBoundary
|
javascript
|
uber/h3-js
|
lib/h3core.js
|
https://github.com/uber/h3-js/blob/master/lib/h3core.js
|
Apache-2.0
|
function gridDistance(origin, destination) {
const [oLower, oUpper] = h3IndexToSplitLong(origin);
const [dLower, dUpper] = h3IndexToSplitLong(destination);
const countPtr = C._malloc(SZ_INT64);
try {
throwIfError(H3.gridDistance(oLower, oUpper, dLower, dUpper, countPtr));
return readInt64AsDoubleFromPointer(countPtr);
} finally {
C._free(countPtr);
}
}
|
Get the grid distance between two hex indexes. This function may fail
to find the distance between two indexes if they are very far apart or
on opposite sides of a pentagon.
@static
@param {H3IndexInput} origin Origin hexagon index
@param {H3IndexInput} destination Destination hexagon index
@return {number} Distance between hexagons
@throws {H3Error} If input is invalid or the distance could not be calculated
|
gridDistance
|
javascript
|
uber/h3-js
|
lib/h3core.js
|
https://github.com/uber/h3-js/blob/master/lib/h3core.js
|
Apache-2.0
|
function gridPathCells(origin, destination) {
const [oLower, oUpper] = h3IndexToSplitLong(origin);
const [dLower, dUpper] = h3IndexToSplitLong(destination);
const countPtr = C._malloc(SZ_INT64);
try {
throwIfError(H3.gridPathCellsSize(oLower, oUpper, dLower, dUpper, countPtr));
const count = validateArrayLength(readInt64AsDoubleFromPointer(countPtr));
const hexagons = C._calloc(count, SZ_H3INDEX);
try {
H3.gridPathCells(oLower, oUpper, dLower, dUpper, hexagons);
return readArrayOfH3Indexes(hexagons, count);
} finally {
C._free(hexagons);
}
} finally {
C._free(countPtr);
}
}
|
Given two H3 indexes, return the line of indexes between them (inclusive).
This function may fail to find the line between two indexes, for
example if they are very far apart. It may also fail when finding
distances for indexes on opposite sides of a pentagon.
Notes:
- The specific output of this function should not be considered stable
across library versions. The only guarantees the library provides are
that the line length will be `h3Distance(start, end) + 1` and that
every index in the line will be a neighbor of the preceding index.
- Lines are drawn in grid space, and may not correspond exactly to either
Cartesian lines or great arcs.
@static
@param {H3IndexInput} origin Origin hexagon index
@param {H3IndexInput} destination Destination hexagon index
@return {H3Index[]} H3 indexes connecting origin and destination
@throws {H3Error} If input is invalid or the line cannot be calculated
|
gridPathCells
|
javascript
|
uber/h3-js
|
lib/h3core.js
|
https://github.com/uber/h3-js/blob/master/lib/h3core.js
|
Apache-2.0
|
function cellToLocalIj(origin, destination) {
const ij = C._malloc(SZ_COORDIJ);
try {
throwIfError(
H3.cellToLocalIj(
...h3IndexToSplitLong(origin),
...h3IndexToSplitLong(destination),
LOCAL_IJ_DEFAULT_MODE,
ij
)
);
return readCoordIJ(ij);
} finally {
C._free(ij);
}
}
|
Produces IJ coordinates for an H3 index anchored by an origin.
- The coordinate space used by this function may have deleted
regions or warping due to pentagonal distortion.
- Coordinates are only comparable if they come from the same
origin index.
- Failure may occur if the index is too far away from the origin
or if the index is on the other side of a pentagon.
- This function is experimental, and its output is not guaranteed
to be compatible across different versions of H3.
@static
@param {H3IndexInput} origin Origin H3 index
@param {H3IndexInput} destination H3 index for which to find relative coordinates
@return {CoordIJ} Coordinates as an `{i, j}` pair
@throws {H3Error} If the IJ coordinates cannot be calculated
|
cellToLocalIj
|
javascript
|
uber/h3-js
|
lib/h3core.js
|
https://github.com/uber/h3-js/blob/master/lib/h3core.js
|
Apache-2.0
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.