feat: adds types and tests for lexicographic-integer (#41025)

Signed-off-by: Carson Farmer <carson.farmer@gmail.com>
This commit is contained in:
Carson Farmer
2019-12-18 10:49:57 -08:00
committed by Daniel Rosenwasser
parent a46d1c7671
commit 729be11faf
4 changed files with 67 additions and 0 deletions
+16
View File
@@ -0,0 +1,16 @@
// Type definitions for lexicographic-integer 1.1
// Project: https://github.com/substack/lexicographic-integer
// Definitions by: Carson Farmer <https://github.com/me>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
/**
* Return an array of byte values or a lexicographic hex string for an input integer.
* @param n The input integer as a javascript number.
* @param enc The encoding to use. Can be one of 'array' (default) or 'hex'.
*/
export function pack<T extends 'hex' | 'array' = 'array'>(n: number, enc?: T): T extends 'hex' ? string : T extends 'array' ? number[] : never;
/**
* Convert an array of bytes returned by .pack() back into the original javascript number.
* @param xs An array of bytes or a hex string.
*/
export function unpack(xs: number[] | string): number;
@@ -0,0 +1,26 @@
import { pack, unpack } from 'lexicographic-integer';
const a = 1e55;
const b = 1.0000000000001e55;
const ha = pack(a, 'hex');
const hb = pack(b, 'hex');
console.log(ha, hb);
const num = 555;
const encoded = pack(num, 'hex');
const decoded1: number = unpack(encoded);
console.log(decoded1);
let prev: string | number[] = pack(0);
let n: number;
let skip = 1;
for (n = 1; n < Number.MAX_VALUE; n += skip) {
const cur = pack(n, 'hex');
if (cur <= prev.toString()) break;
prev = cur;
skip = 1 + Math.pow(245, Math.ceil(Math.log(n) / Math.log(256)));
}
console.log(n === Infinity);
const decoded2: number = unpack(prev);
console.log(decoded2);
+24
View File
@@ -0,0 +1,24 @@
{
"compilerOptions": {
"module": "commonjs",
"lib": [
"es6",
"dom"
],
"noImplicitAny": true,
"noImplicitThis": true,
"strictFunctionTypes": true,
"strictNullChecks": true,
"baseUrl": "../",
"typeRoots": [
"../"
],
"types": [],
"noEmit": true,
"forceConsistentCasingInFileNames": true
},
"files": [
"index.d.ts",
"lexicographic-integer-tests.ts"
]
}
+1
View File
@@ -0,0 +1 @@
{ "extends": "dtslint/dt.json" }