tweb/src/lib/polyfill.ts

78 lines
2.2 KiB
TypeScript
Raw Normal View History

import { bytesToHex, bytesFromHex, bufferConcats } from "./bin_utils";
2020-04-14 17:46:31 +02:00
// @ts-ignore
import {SecureRandom} from 'jsbn';
export const secureRandom = new SecureRandom();
2020-02-06 16:43:07 +01:00
Object.defineProperty(Uint8Array.prototype, 'hex', {
get: function(): string {
return bytesToHex([...this]);
},
2020-04-08 17:46:43 +02:00
2020-02-06 16:43:07 +01:00
set: function(str: string) {
this.set(bytesFromHex(str));
},
enumerable: true,
configurable: true
});
Uint8Array.prototype.randomize = function() {
2020-04-14 17:46:31 +02:00
secureRandom.nextBytes(this);
2020-02-06 16:43:07 +01:00
return this;
};
Uint8Array.prototype.concat = function(...args: Array<Uint8Array | ArrayBuffer | number[]>) {
return bufferConcats(this, ...args);
};
Uint8Array.prototype.toString = function() {
return String.fromCharCode.apply(null, [...this]);
};
Uint8Array.prototype.toJSON = function() {
return [...this];
};
2020-02-22 17:00:17 +01:00
Array.prototype.forEachReverse = function<T>(callback: (value: T, index?: number, array?: Array<T>) => void) {
let length = this.length;
for(var i = length - 1; i >= 0; --i) {
callback(this[i], i, this);
}
};
2020-02-06 16:43:07 +01:00
2020-03-01 18:26:25 +01:00
Array.prototype.findAndSplice = function<T>(verify: (value: T, index?: number, array?: Array<T>) => boolean) {
let index = this.findIndex(verify);
return index !== -1 ? this.splice(index, 1)[0] : undefined;
};
String.prototype.toHHMMSS = function(leadZero = false) {
const sec_num = parseInt(this + '', 10);
const hours = Math.floor(sec_num / 3600);
2020-03-01 18:26:25 +01:00
let minutes: any = Math.floor((sec_num - (hours * 3600)) / 60);
let seconds: any = sec_num - (hours * 3600) - (minutes * 60);
if(hours) leadZero = true;
2020-03-01 18:26:25 +01:00
if(minutes < 10) minutes = leadZero ? "0" + minutes : minutes;
if(seconds < 10) seconds = "0" + seconds;
return (hours ? /* ('0' + hours).slice(-2) */hours + ':' : '') + minutes + ':' + seconds;
};
2020-03-01 18:26:25 +01:00
2020-02-06 16:43:07 +01:00
declare global {
interface Uint8Array {
hex: string;
randomize: () => Uint8Array,
concat: (...args: Array<Uint8Array | ArrayBuffer | number[]>) => Uint8Array,
toString: () => string,
toJSON: () => number[],
2020-02-06 16:43:07 +01:00
}
2020-04-08 17:46:43 +02:00
2020-02-22 17:00:17 +01:00
interface Array<T> {
forEachReverse(callback: (value: T, index?: number, array?: Array<T>) => void): void;
2020-03-01 18:26:25 +01:00
findAndSplice(verify: (value: T, index?: number, array?: Array<T>) => boolean): T;
}
2020-04-08 17:46:43 +02:00
2020-03-01 18:26:25 +01:00
interface String {
toHHMMSS(leadZero?: boolean): string;
2020-02-22 17:00:17 +01:00
}
2020-02-06 16:43:07 +01:00
}