hexsha
stringlengths 40
40
| size
int64 906
46.7k
| ext
stringclasses 2
values | lang
stringclasses 1
value | max_stars_repo_path
stringlengths 5
110
| max_stars_repo_name
stringlengths 8
52
| max_stars_repo_head_hexsha
stringlengths 40
40
| max_stars_repo_licenses
sequencelengths 1
3
| max_stars_count
float64 1
2.05k
⌀ | max_stars_repo_stars_event_min_datetime
stringlengths 24
24
⌀ | max_stars_repo_stars_event_max_datetime
stringlengths 24
24
⌀ | max_issues_repo_path
stringlengths 5
110
| max_issues_repo_name
stringlengths 9
52
| max_issues_repo_head_hexsha
stringlengths 40
40
| max_issues_repo_licenses
sequencelengths 1
3
| max_issues_count
float64 1
1.47k
⌀ | max_issues_repo_issues_event_min_datetime
stringlengths 24
24
⌀ | max_issues_repo_issues_event_max_datetime
stringlengths 24
24
⌀ | max_forks_repo_path
stringlengths 5
110
| max_forks_repo_name
stringlengths 9
71
| max_forks_repo_head_hexsha
stringlengths 40
40
| max_forks_repo_licenses
sequencelengths 1
3
| max_forks_count
float64 1
1.13k
⌀ | max_forks_repo_forks_event_min_datetime
stringlengths 24
24
⌀ | max_forks_repo_forks_event_max_datetime
stringlengths 24
24
⌀ | content
stringlengths 906
46.7k
| avg_line_length
float64 12.8
57.6
| max_line_length
int64 33
2.07k
| alphanum_fraction
float64 0.14
0.75
| loc
int64 50
2.08k
| functions
int64 1
107
| function_signatures
int64 0
26
| function_parameters
int64 0
230
| variable_declarations
int64 0
112
| property_declarations
int64 0
826
| function_usages
int64 0
68
| trivial_types
int64 0
46
| predefined_types
int64 0
695
| type_definitions
int64 0
247
| dynamism_heuristic
int64 0
50
| loc_per_function
float64 5
255
| estimated_tokens
int64 219
16k
| fun_ann_density
float64 0
0.07
| var_ann_density
float64 0
0.05
| prop_ann_density
float64 0
0.13
| typedef_density
float64 0
0.02
| dynamism_density
float64 0
0.03
| trivial_density
float64 0
0.6
| predefined_density
float64 0
1.83
| metric
float64 0.2
0.41
| content_without_annotations
stringlengths 615
51.1k
|
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
adaeef19f40195d662204559e5fc80ae94e36e65 | 2,878 | tsx | TypeScript | images/frontend/app/src/tools/timeRangeCalculator.tsx | DanielDiCapua/osi4iot | 3be5f82884b5619dc5080ef124adcd3a88188511 | [
"Apache-2.0"
] | 1 | 2022-03-30T04:37:13.000Z | 2022-03-30T04:37:13.000Z | images/frontend/app/src/tools/timeRangeCalculator.tsx | DanielDiCapua/osi4iot | 3be5f82884b5619dc5080ef124adcd3a88188511 | [
"Apache-2.0"
] | null | null | null | images/frontend/app/src/tools/timeRangeCalculator.tsx | DanielDiCapua/osi4iot | 3be5f82884b5619dc5080ef124adcd3a88188511 | [
"Apache-2.0"
] | null | null | null |
const lastMinutesDate = (startDate: Date, minutes: number) => {
const lastMinutes = (new Date()).setMinutes(startDate.getMinutes() - minutes);
return new Date(lastMinutes);
};
const lastHoursDate = (startDate: Date, hours: number) => {
const lastHours = (new Date()).setHours(startDate.getHours() - hours);
return new Date(lastHours);
};
const lastDaysDate = (startDate: Date, days: number) => {
const lastDays = (new Date()).setHours(startDate.getHours() - 24*days);
return new Date(lastDays);
}
const lastWeeksDate = (startDate: Date, weeks: number) => {
const lastWeeks = (new Date()).setHours(startDate.getHours() - 7*24*weeks);
return new Date(lastWeeks);
}
const lastMonthsDate = (startDate: Date, months: number) => {
const lastMonths = (new Date()).setMonth(startDate.getMonth() - months);
return new Date(lastMonths);
}
const lastYearsDate = (startDate: Date, years: number) => {
const lastYears = (new Date()).setFullYear(startDate.getFullYear() - years);
return new Date(lastYears);
}
const timeRangeCalculator = (timeRangeString: string) => {
const timeRangeArray = timeRangeString.split(" ");
let startDateString = "";
let endDateString = "";
if (timeRangeArray[0] === "Last") {
const endDate = new Date();
let startDate = new Date();
endDateString = endDate.toISOString();
if (timeRangeArray.length === 2) {
if (timeRangeArray[1] === "minute") startDate = lastMinutesDate(startDate, 1);
else if (timeRangeArray[1] === "hour") startDate = lastHoursDate(startDate, 1);
else if (timeRangeArray[1] === "day") startDate = lastDaysDate(startDate, 1);
else if (timeRangeArray[1] === "week") startDate = lastWeeksDate(startDate, 1);
else if (timeRangeArray[1] === "month") startDate = lastMonthsDate(startDate, 1);
else if (timeRangeArray[1] === "year") startDate = lastYearsDate(startDate, 1);
} else if (timeRangeArray.length === 3) {
const timeRangeValue = parseInt(timeRangeArray[1], 10)
if (timeRangeArray[2] === "minutes") startDate = lastMinutesDate(startDate, timeRangeValue);
else if (timeRangeArray[2] === "hours") startDate = lastHoursDate(startDate, timeRangeValue);
else if (timeRangeArray[2] === "days") startDate = lastDaysDate(startDate, timeRangeValue);
else if (timeRangeArray[2] === "weeks") startDate = lastWeeksDate(startDate, timeRangeValue);
else if (timeRangeArray[2] === "months") startDate = lastMonthsDate(startDate, timeRangeValue);
else if (timeRangeArray[2] === "years") startDate = lastYearsDate(startDate, timeRangeValue);
}
startDateString = startDate.toISOString();
}
return [startDateString, endDateString];
}
export default timeRangeCalculator; | 47.180328 | 107 | 0.655316 | 53 | 7 | 0 | 13 | 19 | 0 | 6 | 0 | 7 | 0 | 0 | 5.428571 | 750 | 0.026667 | 0.025333 | 0 | 0 | 0 | 0 | 0.179487 | 0.316518 |
/* Example usages of 'lastMinutesDate' are shown below:
startDate = lastMinutesDate(startDate, 1);
startDate = lastMinutesDate(startDate, timeRangeValue);
*/
const lastMinutesDate = (startDate, minutes) => {
const lastMinutes = (new Date()).setMinutes(startDate.getMinutes() - minutes);
return new Date(lastMinutes);
};
/* Example usages of 'lastHoursDate' are shown below:
startDate = lastHoursDate(startDate, 1);
startDate = lastHoursDate(startDate, timeRangeValue);
*/
const lastHoursDate = (startDate, hours) => {
const lastHours = (new Date()).setHours(startDate.getHours() - hours);
return new Date(lastHours);
};
/* Example usages of 'lastDaysDate' are shown below:
startDate = lastDaysDate(startDate, 1);
startDate = lastDaysDate(startDate, timeRangeValue);
*/
const lastDaysDate = (startDate, days) => {
const lastDays = (new Date()).setHours(startDate.getHours() - 24*days);
return new Date(lastDays);
}
/* Example usages of 'lastWeeksDate' are shown below:
startDate = lastWeeksDate(startDate, 1);
startDate = lastWeeksDate(startDate, timeRangeValue);
*/
const lastWeeksDate = (startDate, weeks) => {
const lastWeeks = (new Date()).setHours(startDate.getHours() - 7*24*weeks);
return new Date(lastWeeks);
}
/* Example usages of 'lastMonthsDate' are shown below:
startDate = lastMonthsDate(startDate, 1);
startDate = lastMonthsDate(startDate, timeRangeValue);
*/
const lastMonthsDate = (startDate, months) => {
const lastMonths = (new Date()).setMonth(startDate.getMonth() - months);
return new Date(lastMonths);
}
/* Example usages of 'lastYearsDate' are shown below:
startDate = lastYearsDate(startDate, 1);
startDate = lastYearsDate(startDate, timeRangeValue);
*/
const lastYearsDate = (startDate, years) => {
const lastYears = (new Date()).setFullYear(startDate.getFullYear() - years);
return new Date(lastYears);
}
/* Example usages of 'timeRangeCalculator' are shown below:
;
*/
const timeRangeCalculator = (timeRangeString) => {
const timeRangeArray = timeRangeString.split(" ");
let startDateString = "";
let endDateString = "";
if (timeRangeArray[0] === "Last") {
const endDate = new Date();
let startDate = new Date();
endDateString = endDate.toISOString();
if (timeRangeArray.length === 2) {
if (timeRangeArray[1] === "minute") startDate = lastMinutesDate(startDate, 1);
else if (timeRangeArray[1] === "hour") startDate = lastHoursDate(startDate, 1);
else if (timeRangeArray[1] === "day") startDate = lastDaysDate(startDate, 1);
else if (timeRangeArray[1] === "week") startDate = lastWeeksDate(startDate, 1);
else if (timeRangeArray[1] === "month") startDate = lastMonthsDate(startDate, 1);
else if (timeRangeArray[1] === "year") startDate = lastYearsDate(startDate, 1);
} else if (timeRangeArray.length === 3) {
const timeRangeValue = parseInt(timeRangeArray[1], 10)
if (timeRangeArray[2] === "minutes") startDate = lastMinutesDate(startDate, timeRangeValue);
else if (timeRangeArray[2] === "hours") startDate = lastHoursDate(startDate, timeRangeValue);
else if (timeRangeArray[2] === "days") startDate = lastDaysDate(startDate, timeRangeValue);
else if (timeRangeArray[2] === "weeks") startDate = lastWeeksDate(startDate, timeRangeValue);
else if (timeRangeArray[2] === "months") startDate = lastMonthsDate(startDate, timeRangeValue);
else if (timeRangeArray[2] === "years") startDate = lastYearsDate(startDate, timeRangeValue);
}
startDateString = startDate.toISOString();
}
return [startDateString, endDateString];
}
export default timeRangeCalculator; |
adf4dd622bef97001e61ecc31a6880fac96ad885 | 3,587 | ts | TypeScript | packages/pyroscope-flamegraph/src/FlameGraph/format.ts | josdam/pyroscope | 9ec9c0ab4b68ca18a03e9f206e866ae56226ef10 | [
"Apache-2.0"
] | null | null | null | packages/pyroscope-flamegraph/src/FlameGraph/format.ts | josdam/pyroscope | 9ec9c0ab4b68ca18a03e9f206e866ae56226ef10 | [
"Apache-2.0"
] | 2 | 2022-02-16T15:10:32.000Z | 2022-02-22T12:11:35.000Z | packages/pyroscope-flamegraph/src/FlameGraph/format.ts | DashBouquet/pyroscope | 02f152deea7476130a69287177fdd48453659963 | [
"Apache-2.0"
] | null | null | null | /* eslint-disable max-classes-per-file */
/* eslint-disable no-plusplus */
/* eslint-disable eqeqeq */
/* eslint-disable prefer-destructuring */
export function numberWithCommas(x: number): string {
return x.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ',');
}
export function formatPercent(ratio: number) {
const percent = ratioToPercent(ratio);
return `${percent}%`;
}
export function ratioToPercent(ratio: number) {
return Math.round(10000 * ratio) / 100;
}
export enum Units {
Samples = 'samples',
Objects = 'objects',
Bytes = 'bytes',
}
export function getFormatter(max: number, sampleRate: number, units: Units) {
switch (units) {
case Units.Samples:
return new DurationFormatter(max / sampleRate);
case Units.Objects:
return new ObjectsFormatter(max);
case Units.Bytes:
return new BytesFormatter(max);
default:
// throw new Error(`Unsupported unit: ${units}`);
return new DurationFormatter(max / sampleRate);
}
}
// // this is a class and not a function because we can save some time by
// // precalculating divider and suffix and not doing it on each iteration
class DurationFormatter {
divider = 1;
suffix: string = 'second';
durations: [number, string][] = [
[60, 'minute'],
[60, 'hour'],
[24, 'day'],
[30, 'month'],
[12, 'year'],
];
constructor(maxDur: number) {
for (let i = 0; i < this.durations.length; i++) {
if (maxDur >= this.durations[i][0]) {
this.divider *= this.durations[i][0];
maxDur /= this.durations[i][0];
this.suffix = this.durations[i][1];
} else {
break;
}
}
}
format(samples: number, sampleRate: number) {
const n: any = samples / sampleRate / this.divider;
let nStr = n.toFixed(2);
if (n >= 0 && n < 0.01) {
nStr = '< 0.01';
} else if (n <= 0 && n > -0.01) {
nStr = '< 0.01';
}
return `${nStr} ${this.suffix}${n == 1 ? '' : 's'}`;
}
}
export class ObjectsFormatter {
divider = 1;
suffix = '';
objects: [number, string][] = [
[1000, 'K'],
[1000, 'M'],
[1000, 'G'],
[1000, 'T'],
[1000, 'P'],
];
constructor(maxObjects: number) {
for (let i = 0; i < this.objects.length; i++) {
if (maxObjects >= this.objects[i][0]) {
this.divider *= this.objects[i][0];
maxObjects /= this.objects[i][0];
this.suffix = this.objects[i][1];
} else {
break;
}
}
}
// TODO:
// how to indicate that sampleRate doesn't matter?
format(samples: number, sampleRate: number) {
const n = samples / this.divider;
let nStr = n.toFixed(2);
if (n >= 0 && n < 0.01) {
nStr = '< 0.01';
} else if (n <= 0 && n > -0.01) {
nStr = '< 0.01';
}
return `${nStr} ${this.suffix}`;
}
}
export class BytesFormatter {
divider = 1;
suffix = 'bytes';
bytes: [number, string][] = [
[1024, 'KB'],
[1024, 'MB'],
[1024, 'GB'],
[1024, 'TB'],
[1024, 'PB'],
];
constructor(maxBytes: number) {
for (let i = 0; i < this.bytes.length; i++) {
if (maxBytes >= this.bytes[i][0]) {
this.divider *= this.bytes[i][0];
maxBytes /= this.bytes[i][0];
this.suffix = this.bytes[i][1];
} else {
break;
}
}
}
format(samples: number, sampleRate: number) {
const n = samples / this.divider;
let nStr = n.toFixed(2);
if (n >= 0 && n < 0.01) {
nStr = '< 0.01';
} else if (n <= 0 && n > -0.01) {
nStr = '< 0.01';
}
return `${nStr} ${this.suffix}`;
}
}
| 22.99359 | 77 | 0.545302 | 123 | 10 | 0 | 15 | 10 | 9 | 1 | 1 | 22 | 3 | 0 | 6.5 | 1,191 | 0.020991 | 0.008396 | 0.007557 | 0.002519 | 0 | 0.022727 | 0.5 | 0.249898 | /* eslint-disable max-classes-per-file */
/* eslint-disable no-plusplus */
/* eslint-disable eqeqeq */
/* eslint-disable prefer-destructuring */
export function numberWithCommas(x) {
return x.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ',');
}
export function formatPercent(ratio) {
const percent = ratioToPercent(ratio);
return `${percent}%`;
}
export /* Example usages of 'ratioToPercent' are shown below:
ratioToPercent(ratio);
*/
function ratioToPercent(ratio) {
return Math.round(10000 * ratio) / 100;
}
export enum Units {
Samples = 'samples',
Objects = 'objects',
Bytes = 'bytes',
}
export function getFormatter(max, sampleRate, units) {
switch (units) {
case Units.Samples:
return new DurationFormatter(max / sampleRate);
case Units.Objects:
return new ObjectsFormatter(max);
case Units.Bytes:
return new BytesFormatter(max);
default:
// throw new Error(`Unsupported unit: ${units}`);
return new DurationFormatter(max / sampleRate);
}
}
// // this is a class and not a function because we can save some time by
// // precalculating divider and suffix and not doing it on each iteration
class DurationFormatter {
divider = 1;
suffix = 'second';
durations = [
[60, 'minute'],
[60, 'hour'],
[24, 'day'],
[30, 'month'],
[12, 'year'],
];
constructor(maxDur) {
for (let i = 0; i < this.durations.length; i++) {
if (maxDur >= this.durations[i][0]) {
this.divider *= this.durations[i][0];
maxDur /= this.durations[i][0];
this.suffix = this.durations[i][1];
} else {
break;
}
}
}
format(samples, sampleRate) {
const n = samples / sampleRate / this.divider;
let nStr = n.toFixed(2);
if (n >= 0 && n < 0.01) {
nStr = '< 0.01';
} else if (n <= 0 && n > -0.01) {
nStr = '< 0.01';
}
return `${nStr} ${this.suffix}${n == 1 ? '' : 's'}`;
}
}
export class ObjectsFormatter {
divider = 1;
suffix = '';
objects = [
[1000, 'K'],
[1000, 'M'],
[1000, 'G'],
[1000, 'T'],
[1000, 'P'],
];
constructor(maxObjects) {
for (let i = 0; i < this.objects.length; i++) {
if (maxObjects >= this.objects[i][0]) {
this.divider *= this.objects[i][0];
maxObjects /= this.objects[i][0];
this.suffix = this.objects[i][1];
} else {
break;
}
}
}
// TODO:
// how to indicate that sampleRate doesn't matter?
format(samples, sampleRate) {
const n = samples / this.divider;
let nStr = n.toFixed(2);
if (n >= 0 && n < 0.01) {
nStr = '< 0.01';
} else if (n <= 0 && n > -0.01) {
nStr = '< 0.01';
}
return `${nStr} ${this.suffix}`;
}
}
export class BytesFormatter {
divider = 1;
suffix = 'bytes';
bytes = [
[1024, 'KB'],
[1024, 'MB'],
[1024, 'GB'],
[1024, 'TB'],
[1024, 'PB'],
];
constructor(maxBytes) {
for (let i = 0; i < this.bytes.length; i++) {
if (maxBytes >= this.bytes[i][0]) {
this.divider *= this.bytes[i][0];
maxBytes /= this.bytes[i][0];
this.suffix = this.bytes[i][1];
} else {
break;
}
}
}
format(samples, sampleRate) {
const n = samples / this.divider;
let nStr = n.toFixed(2);
if (n >= 0 && n < 0.01) {
nStr = '< 0.01';
} else if (n <= 0 && n > -0.01) {
nStr = '< 0.01';
}
return `${nStr} ${this.suffix}`;
}
}
|
682aeec1fecbab4978758eab943eabd8aaf76c89 | 2,367 | ts | TypeScript | src/validationfunctions/validate.ts | WavyWalk/formtastisch | fe96d3349481e342bd2e89d9005aa5da726d34e7 | [
"MIT"
] | 19 | 2022-03-07T16:06:56.000Z | 2022-03-31T14:56:39.000Z | src/validationfunctions/validate.ts | WavyWalk/formtastisch | fe96d3349481e342bd2e89d9005aa5da726d34e7 | [
"MIT"
] | null | null | null | src/validationfunctions/validate.ts | WavyWalk/formtastisch | fe96d3349481e342bd2e89d9005aa5da726d34e7 | [
"MIT"
] | null | null | null | /**
* In order so that model can process validation, Every validation function must return this type.
*
* valid - if true all errors for property will be cleared
* valid - if false - if errors are array - will replace all errors for property with array. if single string, will add it, if
* there is no error with this message, else will ignore.
*
* errors - either array of error messages - if valid false will replace all errors for property, if single and false will add error if not there.
*
*/
export interface ValidationReturn {
valid: boolean
errors?: string[] | string
ignore?: boolean
}
export type ValidateFunction = (value: any, ...rest: any[]) => ValidationReturn
/**
* valid false is value is undefined or empty string
*/
export const validateIsRequired = (
value: any,
message: string = 'required'
): ValidationReturn => {
if (!value && (value === '' || value === undefined)) {
return { valid: false, errors: message }
}
return { valid: true }
}
/**
* valid false if value does not match pattern
*/
export const validatePattern = (
value: any,
regEx: RegExp,
message: string = 'errors.isNotEmail'
): ValidationReturn => {
if (regEx.test(value)) {
return { valid: true }
}
return { valid: false, errors: message }
}
/**
* valid false if length lt specified
*/
export const validateMinLength = (
value: string | undefined,
minLength: number,
message: string = 'errors.tooShort'
): ValidationReturn => {
if (value && value.length >= minLength) {
return { valid: true }
}
return { valid: false, errors: message }
}
/**
* valid false if length gt than specified
*/
export const validateMaxLength = (
value: string | undefined,
maxLength: number,
message: string = 'errors.tooLong'
): ValidationReturn => {
if (!value) {
return { valid: false, errors: message }
}
if (value.length > maxLength) {
return { valid: false, errors: message }
}
return { valid: true }
}
/**
* valid false if value not equals toMatch
*/
export const validateEquals = (
{
value,
toMatchWith
}: {
value?: string
toMatchWith?: string
},
message = 'errors.notEqualTo'
): ValidationReturn => {
if (!value && !toMatchWith) {
return { valid: true }
}
if (value !== toMatchWith) {
return { valid: false, errors: message }
}
return { valid: true }
}
| 24.153061 | 146 | 0.657372 | 66 | 5 | 0 | 13 | 5 | 3 | 0 | 4 | 14 | 2 | 0 | 5.2 | 621 | 0.028986 | 0.008052 | 0.004831 | 0.003221 | 0 | 0.153846 | 0.538462 | 0.266223 | /**
* In order so that model can process validation, Every validation function must return this type.
*
* valid - if true all errors for property will be cleared
* valid - if false - if errors are array - will replace all errors for property with array. if single string, will add it, if
* there is no error with this message, else will ignore.
*
* errors - either array of error messages - if valid false will replace all errors for property, if single and false will add error if not there.
*
*/
export interface ValidationReturn {
valid
errors?
ignore?
}
export type ValidateFunction = (value, ...rest) => ValidationReturn
/**
* valid false is value is undefined or empty string
*/
export const validateIsRequired = (
value,
message = 'required'
) => {
if (!value && (value === '' || value === undefined)) {
return { valid: false, errors: message }
}
return { valid: true }
}
/**
* valid false if value does not match pattern
*/
export const validatePattern = (
value,
regEx,
message = 'errors.isNotEmail'
) => {
if (regEx.test(value)) {
return { valid: true }
}
return { valid: false, errors: message }
}
/**
* valid false if length lt specified
*/
export const validateMinLength = (
value,
minLength,
message = 'errors.tooShort'
) => {
if (value && value.length >= minLength) {
return { valid: true }
}
return { valid: false, errors: message }
}
/**
* valid false if length gt than specified
*/
export const validateMaxLength = (
value,
maxLength,
message = 'errors.tooLong'
) => {
if (!value) {
return { valid: false, errors: message }
}
if (value.length > maxLength) {
return { valid: false, errors: message }
}
return { valid: true }
}
/**
* valid false if value not equals toMatch
*/
export const validateEquals = (
{
value,
toMatchWith
},
message = 'errors.notEqualTo'
) => {
if (!value && !toMatchWith) {
return { valid: true }
}
if (value !== toMatchWith) {
return { valid: false, errors: message }
}
return { valid: true }
}
|
c5055e95b1cf23c00d4f8174c39f7e7831a25a28 | 6,738 | ts | TypeScript | src/commands/parse.ts | sinclairzx81/smoke-pack | cccbaaed300b51a20dd537676378714f6bef8ba0 | [
"MIT"
] | 1 | 2022-01-04T23:13:41.000Z | 2022-01-04T23:13:41.000Z | src/commands/parse.ts | sinclairzx81/smoke-pack | cccbaaed300b51a20dd537676378714f6bef8ba0 | [
"MIT"
] | 1 | 2022-03-22T22:54:54.000Z | 2022-03-22T22:54:54.000Z | src/commands/parse.ts | sinclairzx81/smoke-pack | cccbaaed300b51a20dd537676378714f6bef8ba0 | [
"MIT"
] | 1 | 2022-01-04T23:13:47.000Z | 2022-01-04T23:13:47.000Z | /*--------------------------------------------------------------------------
MIT License
Copyright (c) smoke-pack 2019 Haydn Paterson (sinclair) <haydn.developer@gmail.com>
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
---------------------------------------------------------------------------*/
export interface InfoCommand { kind: 'info', message: string }
export interface ListCommand { kind: 'list' }
export interface CreateCommand { kind: 'create', name: string, type: string }
export interface AddCommand { kind: 'add', name: string, type: string }
export interface RemoveCommand { kind: 'remove', name: string }
export interface LinkCommand { kind: 'link', name: string, dependency: string }
export interface UnlinkCommand { kind: 'unlink', name: string, dependency: string }
export interface CleanCommand { kind: 'clean', name: string }
export interface BuildCommand { kind: 'build', name: string }
export interface WatchCommand { kind: 'watch', names: string[] }
export interface StartCommand { kind: 'start', name: string }
export interface TestCommand { kind: 'test', name: string }
export interface PackCommand { kind: 'pack', name: string }
export interface RunCommand { kind: 'run', name: string, script: string }
export type Command =
// general
| InfoCommand
// provision
| ListCommand
| CreateCommand
| AddCommand
| RemoveCommand
| LinkCommand
| UnlinkCommand
// automation
| CleanCommand
| BuildCommand
| WatchCommand
| StartCommand
| TestCommand
| PackCommand
| RunCommand
/** Parses the given command line arguments. */
export function parse(args: string[]): Command {
const forward = [args.shift()!, args.shift()!]
if(args.length === 0) {
const kind = 'info'
const message = ''
return { kind, message }
}
const commandKind = args.shift()!
switch(commandKind) {
// ---------------------
// provision
// ---------------------
case 'list': {
const kind = 'list'
return { kind }
}
// ---------------------
// provision
// ---------------------
case 'create': {
if(args.length !== 2) {
const kind = 'info'
const message = 'Expected <name> <type> arguments.'
return { kind, message }
}
const kind = 'create'
const name = args.shift()!
const type = args.shift()!
return { kind, name, type }
}
case 'add': {
if(args.length !== 2) {
const kind = 'info'
const message = 'Expected <name> <type> arguments.'
return { kind, message }
}
const kind = 'add'
const name = args.shift()!
const type = args.shift()!
return { kind, name, type }
}
case 'remove': {
if(args.length !== 1) {
const kind = 'info'
const message = 'Expected <name> argument.'
return { kind, message }
}
const kind = 'remove'
const name = args.shift()!
return { kind, name }
}
case "link": {
if(args.length !== 2) {
const kind = 'info'
const message = 'Expected <name> <dependency> arguments.'
return { kind, message }
}
const kind = 'link'
const name = args.shift()!
const dependency = args.shift()!
return { kind, name, dependency }
}
case "unlink": {
if(args.length !== 2) {
const kind = 'info'
const message = 'Expected <name> <dependency> arguments.'
return { kind, message }
}
const kind = 'unlink'
const name = args.shift()!
const dependency = args.shift()!
return { kind, name, dependency }
}
// ---------------------
// automation
// ---------------------
case 'clean': {
const kind = 'clean'
if(args.length !== 1) {
const name = '*'
return { kind, name }
}
const name = args.shift()!
return { kind, name }
}
case 'build': {
if(args.length !== 1) {
const kind = 'info'
const message = 'Expected <name> argument.'
return { kind, message }
}
const kind = 'build'
const name = args.shift()!
return { kind, name }
}
case 'watch': {
if(args.length < 1) {
const kind = 'info'
const message = 'Expected <name> argument.'
return { kind, message }
}
const kind = 'watch'
const names = [...args]
return { kind, names }
}
case 'start': {
if(args.length !== 1) {
const kind = 'info'
const message = 'Expected <name> argument.'
return { kind, message }
}
const kind = 'start'
const name = args.shift()!
return { kind, name }
}
case 'test': {
if(args.length !== 1) {
const kind = 'info'
const message = 'Expected <name> argument.'
return { kind, message }
}
const kind = 'test'
const name = args.shift()!
return { kind, name }
}
case 'pack': {
if(args.length !== 1) {
const kind = 'info'
const message = 'Expected <name> argument.'
return { kind, message }
}
const kind = 'pack'
const name = args.shift()!
return { kind, name }
}
case "run": {
if(args.length !== 2) {
const kind = 'info'
const message = 'Expected <name> <script> arguments.'
return { kind, message }
}
const kind = 'run'
const name = args.shift()!
const script = args.shift()!
return { kind, name, script }
}
default: {
const kind = 'info'
const message = `Invalid command '${commandKind}'`
return { kind, message }
}
}
}
| 30.351351 | 83 | 0.566043 | 173 | 1 | 0 | 1 | 59 | 32 | 0 | 0 | 19 | 15 | 0 | 142 | 1,670 | 0.001198 | 0.035329 | 0.019162 | 0.008982 | 0 | 0 | 0.204301 | 0.303138 | /*--------------------------------------------------------------------------
MIT License
Copyright (c) smoke-pack 2019 Haydn Paterson (sinclair) <haydn.developer@gmail.com>
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
---------------------------------------------------------------------------*/
export interface InfoCommand { kind, message }
export interface ListCommand { kind }
export interface CreateCommand { kind, name, type }
export interface AddCommand { kind, name, type }
export interface RemoveCommand { kind, name }
export interface LinkCommand { kind, name, dependency }
export interface UnlinkCommand { kind, name, dependency }
export interface CleanCommand { kind, name }
export interface BuildCommand { kind, name }
export interface WatchCommand { kind, names }
export interface StartCommand { kind, name }
export interface TestCommand { kind, name }
export interface PackCommand { kind, name }
export interface RunCommand { kind, name, script }
export type Command =
// general
| InfoCommand
// provision
| ListCommand
| CreateCommand
| AddCommand
| RemoveCommand
| LinkCommand
| UnlinkCommand
// automation
| CleanCommand
| BuildCommand
| WatchCommand
| StartCommand
| TestCommand
| PackCommand
| RunCommand
/** Parses the given command line arguments. */
export function parse(args) {
const forward = [args.shift()!, args.shift()!]
if(args.length === 0) {
const kind = 'info'
const message = ''
return { kind, message }
}
const commandKind = args.shift()!
switch(commandKind) {
// ---------------------
// provision
// ---------------------
case 'list': {
const kind = 'list'
return { kind }
}
// ---------------------
// provision
// ---------------------
case 'create': {
if(args.length !== 2) {
const kind = 'info'
const message = 'Expected <name> <type> arguments.'
return { kind, message }
}
const kind = 'create'
const name = args.shift()!
const type = args.shift()!
return { kind, name, type }
}
case 'add': {
if(args.length !== 2) {
const kind = 'info'
const message = 'Expected <name> <type> arguments.'
return { kind, message }
}
const kind = 'add'
const name = args.shift()!
const type = args.shift()!
return { kind, name, type }
}
case 'remove': {
if(args.length !== 1) {
const kind = 'info'
const message = 'Expected <name> argument.'
return { kind, message }
}
const kind = 'remove'
const name = args.shift()!
return { kind, name }
}
case "link": {
if(args.length !== 2) {
const kind = 'info'
const message = 'Expected <name> <dependency> arguments.'
return { kind, message }
}
const kind = 'link'
const name = args.shift()!
const dependency = args.shift()!
return { kind, name, dependency }
}
case "unlink": {
if(args.length !== 2) {
const kind = 'info'
const message = 'Expected <name> <dependency> arguments.'
return { kind, message }
}
const kind = 'unlink'
const name = args.shift()!
const dependency = args.shift()!
return { kind, name, dependency }
}
// ---------------------
// automation
// ---------------------
case 'clean': {
const kind = 'clean'
if(args.length !== 1) {
const name = '*'
return { kind, name }
}
const name = args.shift()!
return { kind, name }
}
case 'build': {
if(args.length !== 1) {
const kind = 'info'
const message = 'Expected <name> argument.'
return { kind, message }
}
const kind = 'build'
const name = args.shift()!
return { kind, name }
}
case 'watch': {
if(args.length < 1) {
const kind = 'info'
const message = 'Expected <name> argument.'
return { kind, message }
}
const kind = 'watch'
const names = [...args]
return { kind, names }
}
case 'start': {
if(args.length !== 1) {
const kind = 'info'
const message = 'Expected <name> argument.'
return { kind, message }
}
const kind = 'start'
const name = args.shift()!
return { kind, name }
}
case 'test': {
if(args.length !== 1) {
const kind = 'info'
const message = 'Expected <name> argument.'
return { kind, message }
}
const kind = 'test'
const name = args.shift()!
return { kind, name }
}
case 'pack': {
if(args.length !== 1) {
const kind = 'info'
const message = 'Expected <name> argument.'
return { kind, message }
}
const kind = 'pack'
const name = args.shift()!
return { kind, name }
}
case "run": {
if(args.length !== 2) {
const kind = 'info'
const message = 'Expected <name> <script> arguments.'
return { kind, message }
}
const kind = 'run'
const name = args.shift()!
const script = args.shift()!
return { kind, name, script }
}
default: {
const kind = 'info'
const message = `Invalid command '${commandKind}'`
return { kind, message }
}
}
}
|
c56756306c31c45077c7b7530c83ab4045f24df0 | 5,347 | ts | TypeScript | src/constants/validGuesses.ts | SWalls/turdle | 9e74a87b4d3a25847b8b62e95a439e002880eb84 | [
"MIT"
] | 1 | 2022-02-12T15:47:08.000Z | 2022-02-12T15:47:08.000Z | src/constants/validGuesses.ts | SWalls/turdle | 9e74a87b4d3a25847b8b62e95a439e002880eb84 | [
"MIT"
] | null | null | null | src/constants/validGuesses.ts | SWalls/turdle | 9e74a87b4d3a25847b8b62e95a439e002880eb84 | [
"MIT"
] | null | null | null | export const NUM_FRAMES = 5
export const NUM_COLORS = 5
export const ColorCodes = ['W', 'B', 'P', 'R', 'G']
export const KeyboardLetters = [
'Q',
'W',
'E',
'R',
'T',
'Y',
'U',
'I',
'O',
'P',
'A',
'S',
'D',
'F',
'G',
'H',
'J',
'K',
'L',
'Z',
'X',
'C',
'V',
'B',
'N',
]
export const VALIDGUESSES = generateAllValidGuesses()
export function isDisabled(letter: string, currentGuess: string[]): boolean {
const frame = letterToFrameIdx(letter)
const lastLetterFrame = letterToFrameIdx(
currentGuess[currentGuess.length - 1]
)
return (
currentGuess.length === 5 ||
currentGuess.some((c) => c !== letter && letterToFrameIdx(c) === frame) ||
(currentGuess.length > 0 &&
!currentGuess.some((c) => letterToFrameIdx(c) === frame) &&
frame !== (lastLetterFrame + 1 === 6 ? 1 : lastLetterFrame + 1))
)
}
export function wordleToTurdle(wordle?: string): string {
return (wordle || 'QQQQQ')
.split('')
.map((c) => turdleId(c))
.join(' ')
}
export function letterToTurdle(letter?: string): string {
return letterToFrameIdx(letter) - 1 + '_' + (letterToColorIdx(letter) - 1)
}
export function turdleToLetter(turdle: string): string {
const [fIdx, cIdx] = turdle.split('_')
return KeyboardLetters[
parseInt(cIdx) * NUM_FRAMES + (parseInt(fIdx) % NUM_COLORS)
]
}
/** Rounds to the nearest multiple of Y. */
export function roundMultiple(x: number, y: number): number {
return Math.ceil(x / y) * y
}
export function turdleId(value?: string): string {
return letterToFrameIdx(value) + letterToColorCode(value)
}
export function letterToFrameIdx(value?: string): number {
const letterIdx = KeyboardLetters.indexOf(value || 'Q')
return (letterIdx % NUM_COLORS) + 1
}
export function letterToColorCode(value?: string): string {
return ColorCodes[letterToColorIdx(value) - 1]
}
export function letterToColorIdx(value?: string): number {
const letterIdx = KeyboardLetters.indexOf(value || 'Q')
return roundMultiple(letterIdx + 1, NUM_FRAMES) / NUM_FRAMES
}
function generateAllValidGuesses(): string[] {
let guesses: string[] = []
const sequences = generateStartingSequences()
for (let i = sequences.length - 1; i >= 0; i--) {
let sequence = shiftArrayRight(sequences[i])
for (let j = 0; j < NUM_FRAMES; j++) {
const wordGuess = sequence
.map((t) => turdleToLetter(t))
.reduce((prefix, l) => prefix + l)
if (!guesses.includes(wordGuess)) {
guesses.push(wordGuess)
}
sequence = shiftArrayRight(sequence)
}
}
guesses = shuffle(guesses, xor(1))
return guesses
}
function generateStartingSequences(): string[][] {
const sequences: string[][] = []
const guesses: string[] = []
const colors: number[] = new Array(NUM_COLORS)
for (let i = 0; i < NUM_COLORS; i++) {
colors[i] = i
}
const allColors = variationsRep(colors)
for (let i = 0; i < NUM_COLORS; i++) {
allColors.push(new Array(NUM_COLORS).fill(i))
}
let sequence: string[] = []
for (let j = 0; j < allColors.length; j++) {
for (let k = 0; k < NUM_COLORS; k++) {
for (let h = 0; h < NUM_FRAMES; h++) {
for (let i = 0; i < NUM_FRAMES; i++) {
const f = (h + i) % NUM_FRAMES
const c = allColors[j][k++]
if (isNaN(f) || isNaN(c)) continue
sequence.push(f + '_' + c)
if (sequence.length === NUM_FRAMES) {
const wordGuess = sequence
.map((t) => turdleToLetter(t))
.reduce((prefix, l) => prefix + l)
if (!guesses.includes(wordGuess)) {
guesses.push(wordGuess)
sequences.push(sequence)
}
sequence = []
}
}
}
}
}
return sequences
}
/** Generates all variations with repetition (order matters). */
function variationsRep(arr: any[], l?: number): any[][] {
if (l === void 0) l = arr.length // Length of the combinations
var data = Array(l), // Used to store state
results = [] // Array of results
;(function f(pos) {
// Recursive function
if (pos === l) {
// End reached
results.push(data.slice()) // Add a copy of data to results
return
}
for (var i = 0; i < arr.length; ++i) {
data[pos] = arr[i] // Update data
f(pos + 1) // Call f recursively
}
})(0) // Start at index 0
return results // Return results
}
function shiftArrayRight(arr: any[]): any[] {
const temp = arr[arr.length - 1]
for (let i = arr.length - 1; i > 0; i--) {
arr[i] = arr[i - 1]
}
arr[0] = temp
return arr
}
// Predictable Fisher-Yates Shuffle, given a seed like xor(1)
function shuffle(arr: any[], seed = Math.random): any[] {
let m = arr.length
let t
let i
while (m) {
i = Math.floor(seed() * m--)
t = arr[m]
arr[m] = arr[i]
arr[i] = t
}
return arr
}
// XORshift PRNG
function xor(seed: number): () => number {
const baseSeeds = [123456789, 362436069, 521288629, 88675123]
let [x, y, z, w] = baseSeeds
const random = (): number => {
const t = x ^ (x << 11)
;[x, y, z] = [y, z, w]
w = w ^ (w >> 19) ^ (t ^ (t >> 8))
return w / 0x7fffffff
}
;[x, y, z, w] = baseSeeds.map((i) => i + seed)
;[x, y, z, w] = [0, 0, 0, 0].map(() => Math.round(random() * 1e16))
return random
}
| 25.706731 | 78 | 0.582757 | 179 | 26 | 0 | 28 | 42 | 0 | 14 | 6 | 31 | 0 | 0 | 5.346154 | 1,767 | 0.03056 | 0.023769 | 0 | 0 | 0 | 0.0625 | 0.322917 | 0.321389 | export const NUM_FRAMES = 5
export const NUM_COLORS = 5
export const ColorCodes = ['W', 'B', 'P', 'R', 'G']
export const KeyboardLetters = [
'Q',
'W',
'E',
'R',
'T',
'Y',
'U',
'I',
'O',
'P',
'A',
'S',
'D',
'F',
'G',
'H',
'J',
'K',
'L',
'Z',
'X',
'C',
'V',
'B',
'N',
]
export const VALIDGUESSES = generateAllValidGuesses()
export function isDisabled(letter, currentGuess) {
const frame = letterToFrameIdx(letter)
const lastLetterFrame = letterToFrameIdx(
currentGuess[currentGuess.length - 1]
)
return (
currentGuess.length === 5 ||
currentGuess.some((c) => c !== letter && letterToFrameIdx(c) === frame) ||
(currentGuess.length > 0 &&
!currentGuess.some((c) => letterToFrameIdx(c) === frame) &&
frame !== (lastLetterFrame + 1 === 6 ? 1 : lastLetterFrame + 1))
)
}
export function wordleToTurdle(wordle?) {
return (wordle || 'QQQQQ')
.split('')
.map((c) => turdleId(c))
.join(' ')
}
export function letterToTurdle(letter?) {
return letterToFrameIdx(letter) - 1 + '_' + (letterToColorIdx(letter) - 1)
}
export /* Example usages of 'turdleToLetter' are shown below:
turdleToLetter(t);
*/
function turdleToLetter(turdle) {
const [fIdx, cIdx] = turdle.split('_')
return KeyboardLetters[
parseInt(cIdx) * NUM_FRAMES + (parseInt(fIdx) % NUM_COLORS)
]
}
/** Rounds to the nearest multiple of Y. */
export /* Example usages of 'roundMultiple' are shown below:
roundMultiple(letterIdx + 1, NUM_FRAMES) / NUM_FRAMES;
*/
function roundMultiple(x, y) {
return Math.ceil(x / y) * y
}
export /* Example usages of 'turdleId' are shown below:
turdleId(c);
*/
function turdleId(value?) {
return letterToFrameIdx(value) + letterToColorCode(value)
}
export /* Example usages of 'letterToFrameIdx' are shown below:
letterToFrameIdx(letter);
letterToFrameIdx(currentGuess[currentGuess.length - 1]);
c !== letter && letterToFrameIdx(c) === frame;
letterToFrameIdx(c) === frame;
letterToFrameIdx(letter) - 1 + '_' + (letterToColorIdx(letter) - 1);
letterToFrameIdx(value) + letterToColorCode(value);
*/
function letterToFrameIdx(value?) {
const letterIdx = KeyboardLetters.indexOf(value || 'Q')
return (letterIdx % NUM_COLORS) + 1
}
export /* Example usages of 'letterToColorCode' are shown below:
letterToFrameIdx(value) + letterToColorCode(value);
*/
function letterToColorCode(value?) {
return ColorCodes[letterToColorIdx(value) - 1]
}
export /* Example usages of 'letterToColorIdx' are shown below:
letterToColorIdx(letter) - 1;
ColorCodes[letterToColorIdx(value) - 1];
*/
function letterToColorIdx(value?) {
const letterIdx = KeyboardLetters.indexOf(value || 'Q')
return roundMultiple(letterIdx + 1, NUM_FRAMES) / NUM_FRAMES
}
/* Example usages of 'generateAllValidGuesses' are shown below:
generateAllValidGuesses();
*/
function generateAllValidGuesses() {
let guesses = []
const sequences = generateStartingSequences()
for (let i = sequences.length - 1; i >= 0; i--) {
let sequence = shiftArrayRight(sequences[i])
for (let j = 0; j < NUM_FRAMES; j++) {
const wordGuess = sequence
.map((t) => turdleToLetter(t))
.reduce((prefix, l) => prefix + l)
if (!guesses.includes(wordGuess)) {
guesses.push(wordGuess)
}
sequence = shiftArrayRight(sequence)
}
}
guesses = shuffle(guesses, xor(1))
return guesses
}
/* Example usages of 'generateStartingSequences' are shown below:
generateStartingSequences();
*/
function generateStartingSequences() {
const sequences = []
const guesses = []
const colors = new Array(NUM_COLORS)
for (let i = 0; i < NUM_COLORS; i++) {
colors[i] = i
}
const allColors = variationsRep(colors)
for (let i = 0; i < NUM_COLORS; i++) {
allColors.push(new Array(NUM_COLORS).fill(i))
}
let sequence = []
for (let j = 0; j < allColors.length; j++) {
for (let k = 0; k < NUM_COLORS; k++) {
for (let h = 0; h < NUM_FRAMES; h++) {
for (let i = 0; i < NUM_FRAMES; i++) {
const f = (h + i) % NUM_FRAMES
const c = allColors[j][k++]
if (isNaN(f) || isNaN(c)) continue
sequence.push(f + '_' + c)
if (sequence.length === NUM_FRAMES) {
const wordGuess = sequence
.map((t) => turdleToLetter(t))
.reduce((prefix, l) => prefix + l)
if (!guesses.includes(wordGuess)) {
guesses.push(wordGuess)
sequences.push(sequence)
}
sequence = []
}
}
}
}
}
return sequences
}
/** Generates all variations with repetition (order matters). */
/* Example usages of 'variationsRep' are shown below:
variationsRep(colors);
*/
function variationsRep(arr, l?) {
if (l === void 0) l = arr.length // Length of the combinations
var data = Array(l), // Used to store state
results = [] // Array of results
;(function f(pos) {
// Recursive function
if (pos === l) {
// End reached
results.push(data.slice()) // Add a copy of data to results
return
}
for (var i = 0; i < arr.length; ++i) {
data[pos] = arr[i] // Update data
f(pos + 1) // Call f recursively
}
})(0) // Start at index 0
return results // Return results
}
/* Example usages of 'shiftArrayRight' are shown below:
shiftArrayRight(sequences[i]);
sequence = shiftArrayRight(sequence);
*/
function shiftArrayRight(arr) {
const temp = arr[arr.length - 1]
for (let i = arr.length - 1; i > 0; i--) {
arr[i] = arr[i - 1]
}
arr[0] = temp
return arr
}
// Predictable Fisher-Yates Shuffle, given a seed like xor(1)
/* Example usages of 'shuffle' are shown below:
guesses = shuffle(guesses, xor(1));
*/
function shuffle(arr, seed = Math.random) {
let m = arr.length
let t
let i
while (m) {
i = Math.floor(seed() * m--)
t = arr[m]
arr[m] = arr[i]
arr[i] = t
}
return arr
}
// XORshift PRNG
/* Example usages of 'xor' are shown below:
guesses = shuffle(guesses, xor(1));
*/
function xor(seed) {
const baseSeeds = [123456789, 362436069, 521288629, 88675123]
let [x, y, z, w] = baseSeeds
/* Example usages of 'random' are shown below:
Math.random;
Math.round(random() * 1e16);
return random;
*/
const random = () => {
const t = x ^ (x << 11)
;[x, y, z] = [y, z, w]
w = w ^ (w >> 19) ^ (t ^ (t >> 8))
return w / 0x7fffffff
}
;[x, y, z, w] = baseSeeds.map((i) => i + seed)
;[x, y, z, w] = [0, 0, 0, 0].map(() => Math.round(random() * 1e16))
return random
}
|
c5cbef909f0917171ef87f6f627d749ffbf01b40 | 5,121 | ts | TypeScript | challenges/day23.ts | Ldoppea/advent-of-code-2020-typescript | 608c15619b9cae3bbc65d2d5d42455710d517221 | [
"MIT"
] | null | null | null | challenges/day23.ts | Ldoppea/advent-of-code-2020-typescript | 608c15619b9cae3bbc65d2d5d42455710d517221 | [
"MIT"
] | null | null | null | challenges/day23.ts | Ldoppea/advent-of-code-2020-typescript | 608c15619b9cae3bbc65d2d5d42455710d517221 | [
"MIT"
] | 1 | 2022-01-28T17:21:42.000Z | 2022-01-28T17:21:42.000Z | interface GameState {
cups: number[],
currentCupIndex: number
}
export function playRound(gameState: GameState): GameState {
const localCups = [...gameState.cups];
const currentIndex = gameState.currentCupIndex;
const tail = localCups.splice(0, currentIndex);
localCups.push(...tail);
const currentCup = localCups[0];
const nextThreeCups = localCups.splice(1, 3);
let destinationCup = currentCup - 1;
if (destinationCup === 0) {
destinationCup = Math.max(...gameState.cups);
}
while (nextThreeCups.includes(destinationCup)) {
destinationCup -= 1;
if (destinationCup === 0) {
destinationCup = Math.max(...gameState.cups);
}
}
const destinationIndex = localCups.indexOf(destinationCup) + 1;
localCups.splice(destinationIndex, 0, ...nextThreeCups);
const head = localCups.splice(localCups.length - currentIndex, currentIndex);
localCups.unshift(...head);
return {
cups: localCups,
currentCupIndex: (currentIndex + 1) % localCups.length
};
}
export function playXRound(gameState: GameState, numberOfRounds: number): GameState {
let currentGameState = gameState;
for (let i = 0; i < numberOfRounds; i++) {
currentGameState = playRound(currentGameState);
}
return currentGameState;
}
export function getCupsLabeling(input: string, numberOfRounds: number): string {
const cups = input.split('').map(i => parseInt(i)); //?
const gameState = {
cups,
currentCupIndex: 0
}
const result = playXRound(gameState, numberOfRounds);
const indexOf1 = result.cups.indexOf(1);
const tail = result.cups.splice(0, indexOf1);
result.cups.push(...tail);
result.cups.shift()
return result.cups
.join('');
}
export interface GameStateLinkedArray {
cups: number[],
currentCup: number,
maxCup: number
}
export function convertToLinkedArray(orderedListOfCups: number[]): number[] {
const linkedArray: number[] = [-1];
for(let i = 0; i < orderedListOfCups.length; i++) {
const currentCup = orderedListOfCups[i];
const nextIndex = (i+1) % orderedListOfCups.length;
const nextCup = orderedListOfCups[nextIndex];
linkedArray[currentCup] = nextCup;
}
return linkedArray;
}
export function convertToOrderedArray(linkedListOfCups: number[]): number[] {
const orderedArray: number[] = [];
const firstItem = linkedListOfCups[1]; //?
orderedArray.push(firstItem);
let previousIndex = linkedListOfCups.indexOf(firstItem);
while (previousIndex !== firstItem) {
orderedArray.unshift(previousIndex);
previousIndex = linkedListOfCups.indexOf(previousIndex);
}
return orderedArray;
}
export function shiftOrderedArray(orderedListOfCups: number[], startingCup: number) {
const indexOfStartingCup = orderedListOfCups.indexOf(startingCup);
const tail = orderedListOfCups.splice(0, indexOfStartingCup);
orderedListOfCups.push(...tail);
}
export function removeNext(linkedListOfCups:number[], cup: number) {
const nextCup = linkedListOfCups[cup];
const nextNextCup = linkedListOfCups[nextCup];
linkedListOfCups[cup] = nextNextCup;
return nextCup;
}
export function removeNextThree(linkedListOfCups:number[], cup: number): number[] {
return [
removeNext(linkedListOfCups, cup),
removeNext(linkedListOfCups, cup),
removeNext(linkedListOfCups, cup)
]
}
export function insertNext (linkedListOfCups:number[], cup: number, insertedCup: number) {
const nextCup = linkedListOfCups[cup];
linkedListOfCups[cup] = insertedCup;
linkedListOfCups[insertedCup] = nextCup;
}
export function insertNextThree(linkedListOfCups:number[], cup: number, insertedCups: number[]) {
insertedCups.reverse().forEach(insertedCup => {
insertNext(linkedListOfCups, cup, insertedCup)
})
}
export function playRoundLinkedArray(gameState: GameStateLinkedArray) {
const nextThree = removeNextThree(gameState.cups, gameState.currentCup); //?
let destinationCup = gameState.currentCup;
do {
destinationCup -= 1;
if (destinationCup === 0) {
destinationCup = gameState.maxCup;
}
} while (nextThree.includes(destinationCup))
insertNextThree(gameState.cups, destinationCup, nextThree);
gameState.currentCup = gameState.cups[gameState.currentCup];
}
export function playXRoundLinkedArray(gameState: GameStateLinkedArray, numberOfRounds: number) {
for (let i = 0; i < numberOfRounds; i++) {
playRoundLinkedArray(gameState);
}
}
export function getStars(input: string, numberOfRounds: number): number {
const cups = input.split('').map(i => parseInt(i)); //?
const linkedCups = convertToLinkedArray(cups); //?.
const macCups = 1_000_000;
const maxCupsFromFile = Math.max(...cups);
let lastCup = cups[cups.length - 1];
for (let i = maxCupsFromFile + 1; i <= macCups; i++) {
insertNext(linkedCups, lastCup, i);
lastCup = i;
}
const gameState = {
cups: linkedCups,
currentCup: cups[0],
maxCup: macCups
};
playXRoundLinkedArray(gameState, numberOfRounds);
const nextCup1 = gameState.cups[1];
const nextCup2 = gameState.cups[nextCup1];
return nextCup1 * nextCup2;
} | 25.863636 | 97 | 0.714899 | 142 | 16 | 0 | 27 | 40 | 5 | 9 | 0 | 32 | 2 | 0 | 6.875 | 1,524 | 0.028215 | 0.026247 | 0.003281 | 0.001312 | 0 | 0 | 0.363636 | 0.325784 | interface GameState {
cups,
currentCupIndex
}
export /* Example usages of 'playRound' are shown below:
currentGameState = playRound(currentGameState);
*/
function playRound(gameState) {
const localCups = [...gameState.cups];
const currentIndex = gameState.currentCupIndex;
const tail = localCups.splice(0, currentIndex);
localCups.push(...tail);
const currentCup = localCups[0];
const nextThreeCups = localCups.splice(1, 3);
let destinationCup = currentCup - 1;
if (destinationCup === 0) {
destinationCup = Math.max(...gameState.cups);
}
while (nextThreeCups.includes(destinationCup)) {
destinationCup -= 1;
if (destinationCup === 0) {
destinationCup = Math.max(...gameState.cups);
}
}
const destinationIndex = localCups.indexOf(destinationCup) + 1;
localCups.splice(destinationIndex, 0, ...nextThreeCups);
const head = localCups.splice(localCups.length - currentIndex, currentIndex);
localCups.unshift(...head);
return {
cups: localCups,
currentCupIndex: (currentIndex + 1) % localCups.length
};
}
export /* Example usages of 'playXRound' are shown below:
playXRound(gameState, numberOfRounds);
*/
function playXRound(gameState, numberOfRounds) {
let currentGameState = gameState;
for (let i = 0; i < numberOfRounds; i++) {
currentGameState = playRound(currentGameState);
}
return currentGameState;
}
export function getCupsLabeling(input, numberOfRounds) {
const cups = input.split('').map(i => parseInt(i)); //?
const gameState = {
cups,
currentCupIndex: 0
}
const result = playXRound(gameState, numberOfRounds);
const indexOf1 = result.cups.indexOf(1);
const tail = result.cups.splice(0, indexOf1);
result.cups.push(...tail);
result.cups.shift()
return result.cups
.join('');
}
export interface GameStateLinkedArray {
cups,
currentCup,
maxCup
}
export /* Example usages of 'convertToLinkedArray' are shown below:
convertToLinkedArray(cups);
*/
function convertToLinkedArray(orderedListOfCups) {
const linkedArray = [-1];
for(let i = 0; i < orderedListOfCups.length; i++) {
const currentCup = orderedListOfCups[i];
const nextIndex = (i+1) % orderedListOfCups.length;
const nextCup = orderedListOfCups[nextIndex];
linkedArray[currentCup] = nextCup;
}
return linkedArray;
}
export function convertToOrderedArray(linkedListOfCups) {
const orderedArray = [];
const firstItem = linkedListOfCups[1]; //?
orderedArray.push(firstItem);
let previousIndex = linkedListOfCups.indexOf(firstItem);
while (previousIndex !== firstItem) {
orderedArray.unshift(previousIndex);
previousIndex = linkedListOfCups.indexOf(previousIndex);
}
return orderedArray;
}
export function shiftOrderedArray(orderedListOfCups, startingCup) {
const indexOfStartingCup = orderedListOfCups.indexOf(startingCup);
const tail = orderedListOfCups.splice(0, indexOfStartingCup);
orderedListOfCups.push(...tail);
}
export /* Example usages of 'removeNext' are shown below:
removeNext(linkedListOfCups, cup);
*/
function removeNext(linkedListOfCups, cup) {
const nextCup = linkedListOfCups[cup];
const nextNextCup = linkedListOfCups[nextCup];
linkedListOfCups[cup] = nextNextCup;
return nextCup;
}
export /* Example usages of 'removeNextThree' are shown below:
removeNextThree(gameState.cups, gameState.currentCup);
*/
function removeNextThree(linkedListOfCups, cup) {
return [
removeNext(linkedListOfCups, cup),
removeNext(linkedListOfCups, cup),
removeNext(linkedListOfCups, cup)
]
}
export /* Example usages of 'insertNext' are shown below:
insertNext(linkedListOfCups, cup, insertedCup);
insertNext(linkedCups, lastCup, i);
*/
function insertNext (linkedListOfCups, cup, insertedCup) {
const nextCup = linkedListOfCups[cup];
linkedListOfCups[cup] = insertedCup;
linkedListOfCups[insertedCup] = nextCup;
}
export /* Example usages of 'insertNextThree' are shown below:
insertNextThree(gameState.cups, destinationCup, nextThree);
*/
function insertNextThree(linkedListOfCups, cup, insertedCups) {
insertedCups.reverse().forEach(insertedCup => {
insertNext(linkedListOfCups, cup, insertedCup)
})
}
export /* Example usages of 'playRoundLinkedArray' are shown below:
playRoundLinkedArray(gameState);
*/
function playRoundLinkedArray(gameState) {
const nextThree = removeNextThree(gameState.cups, gameState.currentCup); //?
let destinationCup = gameState.currentCup;
do {
destinationCup -= 1;
if (destinationCup === 0) {
destinationCup = gameState.maxCup;
}
} while (nextThree.includes(destinationCup))
insertNextThree(gameState.cups, destinationCup, nextThree);
gameState.currentCup = gameState.cups[gameState.currentCup];
}
export /* Example usages of 'playXRoundLinkedArray' are shown below:
playXRoundLinkedArray(gameState, numberOfRounds);
*/
function playXRoundLinkedArray(gameState, numberOfRounds) {
for (let i = 0; i < numberOfRounds; i++) {
playRoundLinkedArray(gameState);
}
}
export function getStars(input, numberOfRounds) {
const cups = input.split('').map(i => parseInt(i)); //?
const linkedCups = convertToLinkedArray(cups); //?.
const macCups = 1_000_000;
const maxCupsFromFile = Math.max(...cups);
let lastCup = cups[cups.length - 1];
for (let i = maxCupsFromFile + 1; i <= macCups; i++) {
insertNext(linkedCups, lastCup, i);
lastCup = i;
}
const gameState = {
cups: linkedCups,
currentCup: cups[0],
maxCup: macCups
};
playXRoundLinkedArray(gameState, numberOfRounds);
const nextCup1 = gameState.cups[1];
const nextCup2 = gameState.cups[nextCup1];
return nextCup1 * nextCup2;
} |
c5d1ba02e6d0b3653f7aed3e4b704bd6fd0c3c18 | 4,630 | ts | TypeScript | src/bright-code/code/xml.ts | Tyh2001/bright-code | d17443a5ada2d3a825f7529cbb54a8d396783364 | [
"MIT"
] | 1 | 2022-03-27T14:36:32.000Z | 2022-03-27T14:36:32.000Z | src/bright-code/code/xml.ts | Tyh2001/bright-code | d17443a5ada2d3a825f7529cbb54a8d396783364 | [
"MIT"
] | null | null | null | src/bright-code/code/xml.ts | Tyh2001/bright-code | d17443a5ada2d3a825f7529cbb54a8d396783364 | [
"MIT"
] | null | null | null | export const xml = hljs => {
const regex = hljs.regex
const TAG_NAME_RE = regex.concat(
/[A-Z_]/,
regex.optional(/[A-Z0-9_.-]*:/),
/[A-Z0-9_.-]*/
)
const XML_IDENT_RE: RegExp = /[A-Za-z0-9._:-]+/
const XML_ENTITIES: {
className: string;
begin: RegExp;
} = {
className: 'symbol',
begin: /&[a-z]+;|&#[0-9]+;|&#x[a-f0-9]+;/
}
const XML_META_KEYWORDS: {
begin: RegExp;
contains: {
className: string;
begin: RegExp;
illegal: RegExp;
}[];
} = {
begin: /\s/,
contains: [
{
className: 'keyword',
begin: /#?[a-z_][a-z1-9_-]+/,
illegal: /\n/
}
]
}
const XML_META_PAR_KEYWORDS = hljs.inherit(XML_META_KEYWORDS, {
begin: /\(/,
end: /\)/
})
const APOS_META_STRING_MODE = hljs.inherit(hljs.APOS_STRING_MODE, {
className: 'string'
})
const QUOTE_META_STRING_MODE = hljs.inherit(hljs.QUOTE_STRING_MODE, {
className: 'string'
})
const TAG_INTERNALS = {
endsWithParent: true,
illegal: /</,
relevance: 0,
contains: [
{
className: 'attr',
begin: XML_IDENT_RE,
relevance: 0
},
{
begin: /=\s*/,
relevance: 0,
contains: [
{
className: 'string',
endsParent: true,
variants: [
{
begin: /"/,
end: /"/,
contains: [XML_ENTITIES]
},
{
begin: /'/,
end: /'/,
contains: [XML_ENTITIES]
},
{ begin: /[^\s"'=<>`]+/ }
]
}
]
}
]
}
return {
name: 'HTML, XML',
aliases: [
'html',
'xhtml',
'rss',
'atom',
'xjb',
'xsd',
'xsl',
'plist',
'wsf',
'svg'
],
case_insensitive: true,
contains: [
{
className: 'meta',
begin: /<![a-z]/,
end: />/,
relevance: 10,
contains: [
XML_META_KEYWORDS,
QUOTE_META_STRING_MODE,
APOS_META_STRING_MODE,
XML_META_PAR_KEYWORDS,
{
begin: /\[/,
end: /\]/,
contains: [
{
className: 'meta',
begin: /<![a-z]/,
end: />/,
contains: [
XML_META_KEYWORDS,
XML_META_PAR_KEYWORDS,
QUOTE_META_STRING_MODE,
APOS_META_STRING_MODE
]
}
]
}
]
},
hljs.COMMENT(/<!--/, /-->/, { relevance: 10 }),
{
begin: /<!\[CDATA\[/,
end: /\]\]>/,
relevance: 10
},
XML_ENTITIES,
{
className: 'meta',
end: /\?>/,
variants: [
{
begin: /<\?xml/,
relevance: 10,
contains: [QUOTE_META_STRING_MODE]
},
{
begin: /<\?[a-z][a-z0-9]+/
}
]
},
{
className: 'tag',
begin: /<style(?=\s|>)/,
end: />/,
keywords: { name: 'style' },
contains: [TAG_INTERNALS],
starts: {
end: /<\/style>/,
returnEnd: true,
subLanguage: ['css', 'xml']
}
},
{
className: 'tag',
begin: /<script(?=\s|>)/,
end: />/,
keywords: { name: 'script' },
contains: [TAG_INTERNALS],
starts: {
end: /<\/script>/,
returnEnd: true,
subLanguage: ['javascript', 'handlebars', 'xml']
}
},
{
className: 'tag',
begin: /<>|<\/>/
},
// open tag
{
className: 'tag',
begin: regex.concat(
/</,
regex.lookahead(
regex.concat(
TAG_NAME_RE,
regex.either(/\/>/, />/, /\s/)
)
)
),
end: /\/?>/,
contains: [
{
className: 'name',
begin: TAG_NAME_RE,
relevance: 0,
starts: TAG_INTERNALS
}
]
},
{
className: 'tag',
begin: regex.concat(
/<\//,
regex.lookahead(regex.concat(TAG_NAME_RE, />/))
),
contains: [
{
className: 'name',
begin: TAG_NAME_RE,
relevance: 0
},
{
begin: />/,
relevance: 0,
endsParent: true
}
]
}
]
}
}
| 21.435185 | 71 | 0.384665 | 214 | 1 | 0 | 1 | 10 | 0 | 0 | 0 | 2 | 0 | 0 | 212 | 1,267 | 0.001579 | 0.007893 | 0 | 0 | 0 | 0 | 0.166667 | 0.200246 | export const xml = hljs => {
const regex = hljs.regex
const TAG_NAME_RE = regex.concat(
/[A-Z_]/,
regex.optional(/[A-Z0-9_.-]*:/),
/[A-Z0-9_.-]*/
)
const XML_IDENT_RE = /[A-Za-z0-9._:-]+/
const XML_ENTITIES = {
className: 'symbol',
begin: /&[a-z]+;|&#[0-9]+;|&#x[a-f0-9]+;/
}
const XML_META_KEYWORDS = {
begin: /\s/,
contains: [
{
className: 'keyword',
begin: /#?[a-z_][a-z1-9_-]+/,
illegal: /\n/
}
]
}
const XML_META_PAR_KEYWORDS = hljs.inherit(XML_META_KEYWORDS, {
begin: /\(/,
end: /\)/
})
const APOS_META_STRING_MODE = hljs.inherit(hljs.APOS_STRING_MODE, {
className: 'string'
})
const QUOTE_META_STRING_MODE = hljs.inherit(hljs.QUOTE_STRING_MODE, {
className: 'string'
})
const TAG_INTERNALS = {
endsWithParent: true,
illegal: /</,
relevance: 0,
contains: [
{
className: 'attr',
begin: XML_IDENT_RE,
relevance: 0
},
{
begin: /=\s*/,
relevance: 0,
contains: [
{
className: 'string',
endsParent: true,
variants: [
{
begin: /"/,
end: /"/,
contains: [XML_ENTITIES]
},
{
begin: /'/,
end: /'/,
contains: [XML_ENTITIES]
},
{ begin: /[^\s"'=<>`]+/ }
]
}
]
}
]
}
return {
name: 'HTML, XML',
aliases: [
'html',
'xhtml',
'rss',
'atom',
'xjb',
'xsd',
'xsl',
'plist',
'wsf',
'svg'
],
case_insensitive: true,
contains: [
{
className: 'meta',
begin: /<![a-z]/,
end: />/,
relevance: 10,
contains: [
XML_META_KEYWORDS,
QUOTE_META_STRING_MODE,
APOS_META_STRING_MODE,
XML_META_PAR_KEYWORDS,
{
begin: /\[/,
end: /\]/,
contains: [
{
className: 'meta',
begin: /<![a-z]/,
end: />/,
contains: [
XML_META_KEYWORDS,
XML_META_PAR_KEYWORDS,
QUOTE_META_STRING_MODE,
APOS_META_STRING_MODE
]
}
]
}
]
},
hljs.COMMENT(/<!--/, /-->/, { relevance: 10 }),
{
begin: /<!\[CDATA\[/,
end: /\]\]>/,
relevance: 10
},
XML_ENTITIES,
{
className: 'meta',
end: /\?>/,
variants: [
{
begin: /<\?xml/,
relevance: 10,
contains: [QUOTE_META_STRING_MODE]
},
{
begin: /<\?[a-z][a-z0-9]+/
}
]
},
{
className: 'tag',
begin: /<style(?=\s|>)/,
end: />/,
keywords: { name: 'style' },
contains: [TAG_INTERNALS],
starts: {
end: /<\/style>/,
returnEnd: true,
subLanguage: ['css', 'xml']
}
},
{
className: 'tag',
begin: /<script(?=\s|>)/,
end: />/,
keywords: { name: 'script' },
contains: [TAG_INTERNALS],
starts: {
end: /<\/script>/,
returnEnd: true,
subLanguage: ['javascript', 'handlebars', 'xml']
}
},
{
className: 'tag',
begin: /<>|<\/>/
},
// open tag
{
className: 'tag',
begin: regex.concat(
/</,
regex.lookahead(
regex.concat(
TAG_NAME_RE,
regex.either(/\/>/, />/, /\s/)
)
)
),
end: /\/?>/,
contains: [
{
className: 'name',
begin: TAG_NAME_RE,
relevance: 0,
starts: TAG_INTERNALS
}
]
},
{
className: 'tag',
begin: regex.concat(
/<\//,
regex.lookahead(regex.concat(TAG_NAME_RE, />/))
),
contains: [
{
className: 'name',
begin: TAG_NAME_RE,
relevance: 0
},
{
begin: />/,
relevance: 0,
endsParent: true
}
]
}
]
}
}
|
c5f60702c43becf44a23804b3ee1c09511c1e323 | 3,608 | ts | TypeScript | src/web_ui/computone-web-ui/src/tools/tree.ts | quickgiant/computone | 9a49cec64199516f7691503b1b8f9b7596c1b949 | [
"MIT"
] | 1 | 2022-02-12T00:21:00.000Z | 2022-02-12T00:21:00.000Z | src/web_ui/computone-web-ui/src/tools/tree.ts | quickgiant/computone | 9a49cec64199516f7691503b1b8f9b7596c1b949 | [
"MIT"
] | null | null | null | src/web_ui/computone-web-ui/src/tools/tree.ts | quickgiant/computone | 9a49cec64199516f7691503b1b8f9b7596c1b949 | [
"MIT"
] | null | null | null | export interface TreeNode<TData, TId = string> {
id: TId;
data: TData;
children?: TreeNode<TData, TId>[];
}
export interface TreeSearchEntry<TData, TId = string> {
node: TreeNode<TData, TId>;
parents: TreeNode<TData, TId>[];
}
/**
* Performs a preorder traversal over a tree, and runs a callback for each node.
*
* @param root - Root node to traverse, representing a tree
* @param callback - The callback to run for each node
*/
export function treeTraverse<TData, TId = string>(
root: TreeNode<TData, TId>,
callback: (node: TreeNode<TData, TId>) => void
): void {
const nodesToTraverse: TreeNode<TData, TId>[] = [root];
let currentNode: TreeNode<TData, TId> | undefined;
while ((currentNode = nodesToTraverse.shift())) {
callback(currentNode);
if (currentNode.children) {
nodesToTraverse.push(...currentNode.children);
}
}
}
/**
* Performs a breadth-first-search over a tree, and returns the found node and the list of parent
* nodes, or null if the node could not be found.
*
* @param id - The ID of the node being searched for
* @param root - Root node to search, representing a tree
* @returns A search entry containing the found node and the list of parent nodes, or null if the
* node could not be found
*/
export function treeSearch<TData, TId = string>(
id: TId,
root: TreeNode<TData, TId>
): TreeSearchEntry<TData, TId> | null {
const searchEntries: TreeSearchEntry<TData, TId>[] = [
{
node: root,
parents: [],
},
];
let found = false;
let currentSearchEntry: TreeSearchEntry<TData, TId> | undefined;
while (!found && (currentSearchEntry = searchEntries.shift())) {
const { node, parents } = currentSearchEntry;
if (node.id === id) {
found = true;
} else if (node.children) {
searchEntries.push(
...node.children.map((childNode) => ({ node: childNode, parents: [...parents, node] }))
);
}
}
if (found && currentSearchEntry) {
return currentSearchEntry;
} else {
return null;
}
}
/**
* Updates a node in a tree with the following invariants:
* - No node is mutated
* - No node's list of children is mutated
* - If a child of a node was updated, the parent is updated with a new reference
*
* The result of this function is a copy of the root nodes where only the branch that received the
* update contains new references.
*
* @param id - The ID of the target node
* @param root - A root node representing a tree containing the target node
* @param update - An updater function for the target node
* @returns A copy of the root node where the target node and its parents have been updated
*/
export function updateTreeNode<TData, TId = string>(
id: TId,
root: TreeNode<TData, TId>,
update: (node: TreeNode<TData, TId>) => TreeNode<TData, TId>
): TreeNode<TData, TId> {
const searchResult = treeSearch(id, root);
if (!searchResult) {
throw new Error(`Could not find tree node with id "${String(id)} while trying to update"`);
}
const { node, parents } = searchResult;
const updatedNode = update(node);
let currentNode = updatedNode;
let currentParent;
while ((currentParent = parents.pop())) {
currentParent = {
...currentParent,
// Replace modified node in children list
children: currentParent.children?.map((childNode) =>
childNode.id === currentNode.id ? currentNode : childNode
),
};
currentNode = currentParent;
}
// Current node should now be the modified root parent, so replace it in the root node list and
// return the list.
return currentNode;
}
| 31.373913 | 98 | 0.674058 | 74 | 5 | 0 | 9 | 11 | 5 | 1 | 0 | 7 | 2 | 0 | 10.2 | 971 | 0.014418 | 0.011329 | 0.005149 | 0.00206 | 0 | 0 | 0.233333 | 0.244074 | export interface TreeNode<TData, TId = string> {
id;
data;
children?;
}
export interface TreeSearchEntry<TData, TId = string> {
node;
parents;
}
/**
* Performs a preorder traversal over a tree, and runs a callback for each node.
*
* @param root - Root node to traverse, representing a tree
* @param callback - The callback to run for each node
*/
export function treeTraverse<TData, TId = string>(
root,
callback
) {
const nodesToTraverse = [root];
let currentNode;
while ((currentNode = nodesToTraverse.shift())) {
callback(currentNode);
if (currentNode.children) {
nodesToTraverse.push(...currentNode.children);
}
}
}
/**
* Performs a breadth-first-search over a tree, and returns the found node and the list of parent
* nodes, or null if the node could not be found.
*
* @param id - The ID of the node being searched for
* @param root - Root node to search, representing a tree
* @returns A search entry containing the found node and the list of parent nodes, or null if the
* node could not be found
*/
export /* Example usages of 'treeSearch' are shown below:
treeSearch(id, root);
*/
function treeSearch<TData, TId = string>(
id,
root
) {
const searchEntries = [
{
node: root,
parents: [],
},
];
let found = false;
let currentSearchEntry;
while (!found && (currentSearchEntry = searchEntries.shift())) {
const { node, parents } = currentSearchEntry;
if (node.id === id) {
found = true;
} else if (node.children) {
searchEntries.push(
...node.children.map((childNode) => ({ node: childNode, parents: [...parents, node] }))
);
}
}
if (found && currentSearchEntry) {
return currentSearchEntry;
} else {
return null;
}
}
/**
* Updates a node in a tree with the following invariants:
* - No node is mutated
* - No node's list of children is mutated
* - If a child of a node was updated, the parent is updated with a new reference
*
* The result of this function is a copy of the root nodes where only the branch that received the
* update contains new references.
*
* @param id - The ID of the target node
* @param root - A root node representing a tree containing the target node
* @param update - An updater function for the target node
* @returns A copy of the root node where the target node and its parents have been updated
*/
export function updateTreeNode<TData, TId = string>(
id,
root,
update
) {
const searchResult = treeSearch(id, root);
if (!searchResult) {
throw new Error(`Could not find tree node with id "${String(id)} while trying to update"`);
}
const { node, parents } = searchResult;
const updatedNode = update(node);
let currentNode = updatedNode;
let currentParent;
while ((currentParent = parents.pop())) {
currentParent = {
...currentParent,
// Replace modified node in children list
children: currentParent.children?.map((childNode) =>
childNode.id === currentNode.id ? currentNode : childNode
),
};
currentNode = currentParent;
}
// Current node should now be the modified root parent, so replace it in the root node list and
// return the list.
return currentNode;
}
|
765573ac7984861b1ccbd764038f5b7f3f167238 | 2,745 | ts | TypeScript | packages/cactus-plugin-blockchain-migrator/src/main/typescript/TranslatorCode/BasicFunctions/BasicFunctions.ts | theliso/cactus | cfc2f59544d2b038104401abdb2abebf0caa8a78 | [
"Apache-2.0"
] | null | null | null | packages/cactus-plugin-blockchain-migrator/src/main/typescript/TranslatorCode/BasicFunctions/BasicFunctions.ts | theliso/cactus | cfc2f59544d2b038104401abdb2abebf0caa8a78 | [
"Apache-2.0"
] | null | null | null | packages/cactus-plugin-blockchain-migrator/src/main/typescript/TranslatorCode/BasicFunctions/BasicFunctions.ts | theliso/cactus | cfc2f59544d2b038104401abdb2abebf0caa8a78 | [
"Apache-2.0"
] | 1 | 2022-02-16T16:24:06.000Z | 2022-02-16T16:24:06.000Z | export class BasicFunctions {
static getItemDetail(name, list) {
for (let i = 0; i < list.length; i++) {
if (list[i].Name == name) {
return list[i];
}
}
}
static isItemExistInList(name, list): boolean {
if (list == undefined) return false;
for (let i = 0; i < list.length; i++) {
if (list[i].Name == name) {
return true;
}
}
return false;
}
static getItemDetailWithContractName(name, contractName, list) {
for (let i = 0; i < list.length; i++) {
if (list[i].Name === name && list[i].ContractName === contractName) {
return list[i];
}
}
}
static isItemExistInListWithContractName(name, contractName, list): boolean {
for (let i = 0; i < list.length; i++) {
if (list[i].Name === name && list[i].ContractName === contractName) {
return true;
}
}
return false;
}
static getListWithGivenContractName(contractName, list) {
let returnList = [];
for (let i = 0; i < list.length; i++) {
if (list[i].ContractName == contractName) {
returnList.push(list[i]);
}
}
return returnList;
}
static defaultValue(TypeName): string {
if (TypeName.type == 'ElementaryTypeName') {
if (TypeName.name.replace(/\'/g, '').split(/(\d+)/)[0] == 'uint' || TypeName.name.replace(/\'/g, '').split(/(\d+)/)[0] == 'int') {
return '0';
}
else if (TypeName.name == 'bool') {
return 'false';
}
else if (TypeName.name == 'address' || TypeName.name == 'string' || TypeName.name.startsWith("bytes")) {
return '\'\'';
}
}
else if (TypeName.type == 'UserDefinedTypeName') // not struct yet
{
return '0'; // for enumType
}
else if (TypeName.type == 'ArrayTypeName') {
return '[]';
}
else if (TypeName.type == 'Mapping') {
return '{}';
}
}
static isAssignmentOperator(operator: string): boolean {
if (operator == '=' || operator == '+=' || operator == '-=' || operator == '*=' || operator == '/=' || operator == '%=' || operator == '|=' || operator == '&=' || operator == '^=' || operator == '<<=' || operator == '>>=') {
return true;
}
return false;
}
static isEquivalent(a: any, b: any): boolean {
if (a == undefined || b == undefined) {
return false;
}
// Create arrays of property names
let aProps = Object.getOwnPropertyNames(a);
let bProps = Object.getOwnPropertyNames(b);
if (aProps.length != bProps.length) {
return false;
}
for (let i = 0; i < aProps.length; i++) {
let propName = aProps[i];
if (a[propName] !== b[propName]) {
return false;
}
}
return true;
}
} | 25.896226 | 228 | 0.533698 | 88 | 8 | 0 | 16 | 10 | 0 | 0 | 2 | 6 | 1 | 0 | 8.75 | 769 | 0.031209 | 0.013004 | 0 | 0.0013 | 0 | 0.058824 | 0.176471 | 0.286506 | export class BasicFunctions {
static getItemDetail(name, list) {
for (let i = 0; i < list.length; i++) {
if (list[i].Name == name) {
return list[i];
}
}
}
static isItemExistInList(name, list) {
if (list == undefined) return false;
for (let i = 0; i < list.length; i++) {
if (list[i].Name == name) {
return true;
}
}
return false;
}
static getItemDetailWithContractName(name, contractName, list) {
for (let i = 0; i < list.length; i++) {
if (list[i].Name === name && list[i].ContractName === contractName) {
return list[i];
}
}
}
static isItemExistInListWithContractName(name, contractName, list) {
for (let i = 0; i < list.length; i++) {
if (list[i].Name === name && list[i].ContractName === contractName) {
return true;
}
}
return false;
}
static getListWithGivenContractName(contractName, list) {
let returnList = [];
for (let i = 0; i < list.length; i++) {
if (list[i].ContractName == contractName) {
returnList.push(list[i]);
}
}
return returnList;
}
static defaultValue(TypeName) {
if (TypeName.type == 'ElementaryTypeName') {
if (TypeName.name.replace(/\'/g, '').split(/(\d+)/)[0] == 'uint' || TypeName.name.replace(/\'/g, '').split(/(\d+)/)[0] == 'int') {
return '0';
}
else if (TypeName.name == 'bool') {
return 'false';
}
else if (TypeName.name == 'address' || TypeName.name == 'string' || TypeName.name.startsWith("bytes")) {
return '\'\'';
}
}
else if (TypeName.type == 'UserDefinedTypeName') // not struct yet
{
return '0'; // for enumType
}
else if (TypeName.type == 'ArrayTypeName') {
return '[]';
}
else if (TypeName.type == 'Mapping') {
return '{}';
}
}
static isAssignmentOperator(operator) {
if (operator == '=' || operator == '+=' || operator == '-=' || operator == '*=' || operator == '/=' || operator == '%=' || operator == '|=' || operator == '&=' || operator == '^=' || operator == '<<=' || operator == '>>=') {
return true;
}
return false;
}
static isEquivalent(a, b) {
if (a == undefined || b == undefined) {
return false;
}
// Create arrays of property names
let aProps = Object.getOwnPropertyNames(a);
let bProps = Object.getOwnPropertyNames(b);
if (aProps.length != bProps.length) {
return false;
}
for (let i = 0; i < aProps.length; i++) {
let propName = aProps[i];
if (a[propName] !== b[propName]) {
return false;
}
}
return true;
}
} |
76efbc784ee084ef6080dc9b7e3dd41f20103806 | 2,361 | ts | TypeScript | src/app/@theme/model/engagement.ts | ShefaliAgarwal/sonik | 52ba13a944ed1f5b614f1998b2b62e0a84f9acc2 | [
"MIT"
] | null | null | null | src/app/@theme/model/engagement.ts | ShefaliAgarwal/sonik | 52ba13a944ed1f5b614f1998b2b62e0a84f9acc2 | [
"MIT"
] | 1 | 2022-03-02T05:02:21.000Z | 2022-03-02T05:02:21.000Z | src/app/@theme/model/engagement.ts | ShefaliAgarwal/sonik | 52ba13a944ed1f5b614f1998b2b62e0a84f9acc2 | [
"MIT"
] | null | null | null | export class EngagementCardReqObj {
start_date: any;
end_date: any;
channel_type: any;
engagement_metric: any;
constructor() {
let date = new Date();
let datee = new Date(date.getTime() - (7 * 24 * 60 * 60 * 1000));
this.start_date = Math.round((Math.floor(datee.getTime()) / 1000));
this.end_date = Math.round((Math.floor(date.getTime()) / 1000));
}
}
export class EngagementCardResponseObj {
title: any;
count: any;
percentage: any;
increment: boolean;
rate:boolean;
constructor() {
this.title = '';
this.count = 0;
this.percentage = 0;
this.increment = false;
this.rate = false;
}
}
export class EngBarChartData {
chartLabel: string[];
data: number[][];
}
export class EngBarChartReq {
start_date: any;
end_date: any;
segment: any;
channel_type: any;
engagement_metric: any;
dimension: any;
constructor() {
let date = new Date();
let datee = new Date(date.getTime() - (7 * 24 * 60 * 60 * 1000));
this.start_date = Math.round((Math.floor(datee.getTime()) / 1000));
this.end_date = Math.round((Math.floor(date.getTime()) / 1000));
this.channel_type = undefined;
this.segment = undefined;
}
}
export class PieChartReq {
start_date: any;
end_date: any;
channel_type: any;
dimension: any;
segment: any;
constructor() {
let date = new Date();
let datee = new Date(date.getTime() - (7 * 24 * 60 * 60 * 1000));
this.start_date = Math.round((Math.floor(datee.getTime()) / 1000));
this.end_date = Math.round((Math.floor(date.getTime()) / 1000));
this.channel_type = undefined;
this.segment = undefined;
}
}
export class PieChartData {
chartLabel: string[];
data: number[][];
}
export class EngagementTableReq {
start_date: any;
end_date: any;
channel_type: any;
dimension: any;
segment: any;
constructor() {
let date = new Date();
let datee = new Date(date.getTime() - (7 * 24 * 60 * 60 * 1000));
this.start_date = Math.round((Math.floor(datee.getTime()) / 1000));
this.end_date = Math.round((Math.floor(date.getTime()) / 1000));
this.channel_type = undefined;
this.segment = undefined;
}
} | 27.453488 | 75 | 0.590004 | 80 | 5 | 0 | 0 | 8 | 29 | 0 | 23 | 6 | 7 | 0 | 5.4 | 746 | 0.006702 | 0.010724 | 0.038874 | 0.009383 | 0 | 0.547619 | 0.142857 | 0.226985 | export class EngagementCardReqObj {
start_date;
end_date;
channel_type;
engagement_metric;
constructor() {
let date = new Date();
let datee = new Date(date.getTime() - (7 * 24 * 60 * 60 * 1000));
this.start_date = Math.round((Math.floor(datee.getTime()) / 1000));
this.end_date = Math.round((Math.floor(date.getTime()) / 1000));
}
}
export class EngagementCardResponseObj {
title;
count;
percentage;
increment;
rate;
constructor() {
this.title = '';
this.count = 0;
this.percentage = 0;
this.increment = false;
this.rate = false;
}
}
export class EngBarChartData {
chartLabel;
data;
}
export class EngBarChartReq {
start_date;
end_date;
segment;
channel_type;
engagement_metric;
dimension;
constructor() {
let date = new Date();
let datee = new Date(date.getTime() - (7 * 24 * 60 * 60 * 1000));
this.start_date = Math.round((Math.floor(datee.getTime()) / 1000));
this.end_date = Math.round((Math.floor(date.getTime()) / 1000));
this.channel_type = undefined;
this.segment = undefined;
}
}
export class PieChartReq {
start_date;
end_date;
channel_type;
dimension;
segment;
constructor() {
let date = new Date();
let datee = new Date(date.getTime() - (7 * 24 * 60 * 60 * 1000));
this.start_date = Math.round((Math.floor(datee.getTime()) / 1000));
this.end_date = Math.round((Math.floor(date.getTime()) / 1000));
this.channel_type = undefined;
this.segment = undefined;
}
}
export class PieChartData {
chartLabel;
data;
}
export class EngagementTableReq {
start_date;
end_date;
channel_type;
dimension;
segment;
constructor() {
let date = new Date();
let datee = new Date(date.getTime() - (7 * 24 * 60 * 60 * 1000));
this.start_date = Math.round((Math.floor(datee.getTime()) / 1000));
this.end_date = Math.round((Math.floor(date.getTime()) / 1000));
this.channel_type = undefined;
this.segment = undefined;
}
} |
4ab9eed9cbc53ed6e544dca10cf2f6417c2bdcd7 | 1,799 | ts | TypeScript | src/lib.ts | madeindjs/vscode-markdown-move | a68f62930278debb62041c4ba4b39954791a3144 | [
"MIT"
] | 1 | 2022-01-19T02:29:04.000Z | 2022-01-19T02:29:04.000Z | src/lib.ts | madeindjs/vscode-markdown-move | a68f62930278debb62041c4ba4b39954791a3144 | [
"MIT"
] | 1 | 2022-01-02T21:20:52.000Z | 2022-01-02T21:20:52.000Z | src/lib.ts | madeindjs/vscode-markdown-move | a68f62930278debb62041c4ba4b39954791a3144 | [
"MIT"
] | null | null | null | export type Section = [number, number];
export function getPreviousTitleLine(lines: string[], lineIndex: number): number {
do {
const line = lines[lineIndex];
if (line.match(/#+ /) !== null) {
return lineIndex;
}
lineIndex--;
} while (lineIndex >= 0);
throw Error("cannot find previous title");
}
export function getEndOfSectionLine(lines: string[], lineIndex: number, sectionDepth: number): number {
const nextHeaderRe = new RegExp(`^(\\#){1,${sectionDepth}} `);
let cursor = lineIndex + 1;
while (lines[cursor] !== undefined) {
const line = lines[cursor];
if (line.match(nextHeaderRe) && cursor !== 0) {
return cursor - 1;
}
cursor++;
}
return lines.length - 1;
}
/**
* @returns index of started / ended line index
*/
export function getSection(lines: string[], lineIndex: number): Section {
const titleLine = getPreviousTitleLine(lines, lineIndex);
const sectionDeep = lines[titleLine].split(" ")[0].length;
const lastLine = getEndOfSectionLine(lines, lineIndex, sectionDeep);
return [titleLine, lastLine];
}
export function promote(lines: string[], lineIndex: number): string[] {
const section = getSection(lines, lineIndex);
const newLines = [...lines];
for (let i = section[0]; i <= section[1]; i++) {
const line = newLines[i];
if (line.match(/^(\#){2,6} +/) !== null) {
newLines[i] = line.substring(1);
}
}
return newLines;
}
export function demote(lines: string[], lineIndex: number): string[] {
const section = getSection(lines, lineIndex);
const newLines = [...lines];
for (let i = section[0]; i <= section[1]; i++) {
const line = newLines[i];
if (line.match(/^(\#){1,5} +/) !== null) {
newLines[i] = "#".concat(line);
}
}
return newLines;
}
| 23.671053 | 103 | 0.625347 | 51 | 5 | 0 | 11 | 15 | 0 | 3 | 0 | 17 | 1 | 0 | 8 | 521 | 0.03071 | 0.028791 | 0 | 0.001919 | 0 | 0 | 0.548387 | 0.339152 | export type Section = [number, number];
export /* Example usages of 'getPreviousTitleLine' are shown below:
getPreviousTitleLine(lines, lineIndex);
*/
function getPreviousTitleLine(lines, lineIndex) {
do {
const line = lines[lineIndex];
if (line.match(/#+ /) !== null) {
return lineIndex;
}
lineIndex--;
} while (lineIndex >= 0);
throw Error("cannot find previous title");
}
export /* Example usages of 'getEndOfSectionLine' are shown below:
getEndOfSectionLine(lines, lineIndex, sectionDeep);
*/
function getEndOfSectionLine(lines, lineIndex, sectionDepth) {
const nextHeaderRe = new RegExp(`^(\\#){1,${sectionDepth}} `);
let cursor = lineIndex + 1;
while (lines[cursor] !== undefined) {
const line = lines[cursor];
if (line.match(nextHeaderRe) && cursor !== 0) {
return cursor - 1;
}
cursor++;
}
return lines.length - 1;
}
/**
* @returns index of started / ended line index
*/
export /* Example usages of 'getSection' are shown below:
getSection(lines, lineIndex);
*/
function getSection(lines, lineIndex) {
const titleLine = getPreviousTitleLine(lines, lineIndex);
const sectionDeep = lines[titleLine].split(" ")[0].length;
const lastLine = getEndOfSectionLine(lines, lineIndex, sectionDeep);
return [titleLine, lastLine];
}
export function promote(lines, lineIndex) {
const section = getSection(lines, lineIndex);
const newLines = [...lines];
for (let i = section[0]; i <= section[1]; i++) {
const line = newLines[i];
if (line.match(/^(\#){2,6} +/) !== null) {
newLines[i] = line.substring(1);
}
}
return newLines;
}
export function demote(lines, lineIndex) {
const section = getSection(lines, lineIndex);
const newLines = [...lines];
for (let i = section[0]; i <= section[1]; i++) {
const line = newLines[i];
if (line.match(/^(\#){1,5} +/) !== null) {
newLines[i] = "#".concat(line);
}
}
return newLines;
}
|
4ae0d90b63b4fe4e2c5c13b303821da4fa8ea77c | 2,586 | ts | TypeScript | src/model/CaskFormula.ts | Jonass-K/CaskStore-Backend | cbaf47216cb9f637f7f61f9eb3e64d6a69dc40be | [
"MIT"
] | 1 | 2022-03-30T17:16:11.000Z | 2022-03-30T17:16:11.000Z | src/model/CaskFormula.ts | Jonass-K/CaskStore-Backend | cbaf47216cb9f637f7f61f9eb3e64d6a69dc40be | [
"MIT"
] | 4 | 2022-03-25T08:41:45.000Z | 2022-03-26T15:03:14.000Z | src/model/CaskFormula.ts | Jonass-K/CaskStore-Backend | cbaf47216cb9f637f7f61f9eb3e64d6a69dc40be | [
"MIT"
] | null | null | null | /**
* The CaskFormula represents a cask formula defined by the brew api.
*/
export class CaskFormula {
title: string;
name: string | undefined = undefined;
allNames: string[] = [];
desc: string | undefined = undefined;
homepage: string | undefined = undefined;
url: string | undefined = undefined;
install30: number | undefined = undefined;
install90: number | undefined = undefined;
install365: number | undefined = undefined;
constructor(title: string) {
this.title = title;
}
/**
* Returns the cask formula created from the given json object.
* Analytics are optional.
*
* @param json - The json object
* @returns The cask formula
*/
static fromJson({ token, name, desc, url, homepage, analytics = undefined }:
{
token: string,
name: string[],
desc: string,
url: string,
homepage: string,
analytics?: {
install: {
"30d": any,
"90d": any,
"365d": any
}
} | undefined
}
): CaskFormula {
let caskFormula = new CaskFormula(token);
caskFormula.name = name[0];
caskFormula.allNames = name;
caskFormula.desc = desc;
caskFormula.url = url;
caskFormula.homepage = homepage;
if (analytics === undefined) {
return caskFormula;
}
caskFormula.install30 = analytics.install["30d"][token];
caskFormula.install90 = analytics.install["90d"][token];
caskFormula.install365 = analytics.install["365d"][token];
return caskFormula;
}
/**
* Returns the cask formula created from the given json object with only analytics.
*
* @param json - The json object
* @returns The cask formula
*/
static fromAnalyticsJson({ cask, count }: { cask: string, count: string }, days: Days): CaskFormula {
let caskFormula = new CaskFormula(cask);
let countNum = +count.replace(",", "");
switch (days) {
case Days.THIRTY_DAYS:
caskFormula.install30 = countNum;
break;
case Days.NINETY_DAYS:
caskFormula.install90 = countNum;
break;
case Days.YEAR:
caskFormula.install365 = countNum;
break;
}
return caskFormula;
}
}
export enum Days {
THIRTY_DAYS = "30d",
NINETY_DAYS = "90d",
YEAR = "365d"
} | 29.386364 | 105 | 0.549884 | 65 | 3 | 0 | 4 | 3 | 9 | 0 | 3 | 17 | 1 | 0 | 9.333333 | 635 | 0.011024 | 0.004724 | 0.014173 | 0.001575 | 0 | 0.157895 | 0.894737 | 0.210143 | /**
* The CaskFormula represents a cask formula defined by the brew api.
*/
export class CaskFormula {
title;
name = undefined;
allNames = [];
desc = undefined;
homepage = undefined;
url = undefined;
install30 = undefined;
install90 = undefined;
install365 = undefined;
constructor(title) {
this.title = title;
}
/**
* Returns the cask formula created from the given json object.
* Analytics are optional.
*
* @param json - The json object
* @returns The cask formula
*/
static fromJson({ token, name, desc, url, homepage, analytics = undefined }
) {
let caskFormula = new CaskFormula(token);
caskFormula.name = name[0];
caskFormula.allNames = name;
caskFormula.desc = desc;
caskFormula.url = url;
caskFormula.homepage = homepage;
if (analytics === undefined) {
return caskFormula;
}
caskFormula.install30 = analytics.install["30d"][token];
caskFormula.install90 = analytics.install["90d"][token];
caskFormula.install365 = analytics.install["365d"][token];
return caskFormula;
}
/**
* Returns the cask formula created from the given json object with only analytics.
*
* @param json - The json object
* @returns The cask formula
*/
static fromAnalyticsJson({ cask, count }, days) {
let caskFormula = new CaskFormula(cask);
let countNum = +count.replace(",", "");
switch (days) {
case Days.THIRTY_DAYS:
caskFormula.install30 = countNum;
break;
case Days.NINETY_DAYS:
caskFormula.install90 = countNum;
break;
case Days.YEAR:
caskFormula.install365 = countNum;
break;
}
return caskFormula;
}
}
export enum Days {
THIRTY_DAYS = "30d",
NINETY_DAYS = "90d",
YEAR = "365d"
} |
553cf14a9bf5a19d26d116e86ee8cce6754dd499 | 2,111 | ts | TypeScript | problems/1046-last-stone-weight/index.ts | marcobiedermann/leetcode | a49e4ba631ddb70a937bfbccb408d3f544eae997 | [
"MIT"
] | 1 | 2022-01-25T14:02:50.000Z | 2022-01-25T14:02:50.000Z | problems/1046-last-stone-weight/index.ts | marcobiedermann/leetcode | a49e4ba631ddb70a937bfbccb408d3f544eae997 | [
"MIT"
] | null | null | null | problems/1046-last-stone-weight/index.ts | marcobiedermann/leetcode | a49e4ba631ddb70a937bfbccb408d3f544eae997 | [
"MIT"
] | null | null | null | class MaxHeap {
data: number[];
comparator: Function;
constructor(data: number[]) {
this.data = data;
this.comparator = (a: number, b: number) => b - a;
this.heapify();
}
bubbleDown(index: number) {
const lastIndex = this.size() - 1;
while (true) {
const leftIndex = index * 2 + 1;
const rightIndex = index * 2 + 2;
let findIndex = index;
if (
leftIndex <= lastIndex &&
this.comparator(this.data[leftIndex], this.data[findIndex]) < 0
) {
findIndex = leftIndex;
}
if (
rightIndex <= lastIndex &&
this.comparator(this.data[rightIndex], this.data[findIndex]) < 0
) {
findIndex = rightIndex;
}
if (index !== findIndex) {
this.swap(index, findIndex);
index = findIndex;
} else {
break;
}
}
}
bubbleUp(index: number) {
while (index > 0) {
const parentIndex = (index - 1) >> 1;
if (this.comparator(this.data[index], this.data[parentIndex]) < 0) {
this.swap(index, parentIndex);
index = parentIndex;
} else {
break;
}
}
}
heapify() {
if (this.size() < 2) {
return;
}
for (let i = 1; i < this.size(); i += 1) {
this.bubbleUp(i);
}
}
offer(value: number) {
this.data.push(value);
this.bubbleUp(this.size() - 1);
}
poll() {
if (this.size() === 0) {
return null;
}
const result = this.data[0];
const last = this.data.pop();
if (this.size() !== 0) {
this.data[0] = last;
this.bubbleDown(0);
}
return result;
}
size() {
return this.data.length;
}
swap(a: number, b: number) {
[this.data[a], this.data[b]] = [this.data[b], this.data[a]];
}
}
function lastStoneWeight(stones: number[]): number | null {
const heap = new MaxHeap(stones);
while (heap.size() > 1) {
const y = heap.poll();
const x = heap.poll();
if (x < y) {
heap.offer(y - x);
}
}
return heap.size() === 1 ? heap.poll() : 0;
}
export default lastStoneWeight;
| 18.681416 | 74 | 0.520606 | 88 | 10 | 0 | 9 | 11 | 2 | 8 | 1 | 11 | 1 | 0 | 6.6 | 655 | 0.029008 | 0.016794 | 0.003053 | 0.001527 | 0 | 0.03125 | 0.34375 | 0.296364 | class MaxHeap {
data;
comparator;
constructor(data) {
this.data = data;
this.comparator = (a, b) => b - a;
this.heapify();
}
bubbleDown(index) {
const lastIndex = this.size() - 1;
while (true) {
const leftIndex = index * 2 + 1;
const rightIndex = index * 2 + 2;
let findIndex = index;
if (
leftIndex <= lastIndex &&
this.comparator(this.data[leftIndex], this.data[findIndex]) < 0
) {
findIndex = leftIndex;
}
if (
rightIndex <= lastIndex &&
this.comparator(this.data[rightIndex], this.data[findIndex]) < 0
) {
findIndex = rightIndex;
}
if (index !== findIndex) {
this.swap(index, findIndex);
index = findIndex;
} else {
break;
}
}
}
bubbleUp(index) {
while (index > 0) {
const parentIndex = (index - 1) >> 1;
if (this.comparator(this.data[index], this.data[parentIndex]) < 0) {
this.swap(index, parentIndex);
index = parentIndex;
} else {
break;
}
}
}
heapify() {
if (this.size() < 2) {
return;
}
for (let i = 1; i < this.size(); i += 1) {
this.bubbleUp(i);
}
}
offer(value) {
this.data.push(value);
this.bubbleUp(this.size() - 1);
}
poll() {
if (this.size() === 0) {
return null;
}
const result = this.data[0];
const last = this.data.pop();
if (this.size() !== 0) {
this.data[0] = last;
this.bubbleDown(0);
}
return result;
}
size() {
return this.data.length;
}
swap(a, b) {
[this.data[a], this.data[b]] = [this.data[b], this.data[a]];
}
}
/* Example usages of 'lastStoneWeight' are shown below:
;
*/
function lastStoneWeight(stones) {
const heap = new MaxHeap(stones);
while (heap.size() > 1) {
const y = heap.poll();
const x = heap.poll();
if (x < y) {
heap.offer(y - x);
}
}
return heap.size() === 1 ? heap.poll() : 0;
}
export default lastStoneWeight;
|
553d2b86fe365e349cb4d8fadb65238f0656b0c5 | 1,694 | ts | TypeScript | src/index.ts | DevimalPlanet/object-traversal | 9ba7c1e5cccb317ef6f069e0e67616af0dff467e | [
"MIT"
] | 2 | 2022-01-18T06:27:18.000Z | 2022-03-21T04:26:31.000Z | src/index.ts | DevimalPlanet/object-traversal | 9ba7c1e5cccb317ef6f069e0e67616af0dff467e | [
"MIT"
] | 18 | 2022-02-21T21:56:31.000Z | 2022-03-25T23:26:26.000Z | src/index.ts | DevimalPlanet/object-traversal | 9ba7c1e5cccb317ef6f069e0e67616af0dff467e | [
"MIT"
] | 1 | 2022-03-02T00:12:53.000Z | 2022-03-02T00:12:53.000Z | type ArbitraryObject = Record<string, any>;
export interface TraversalMeta {
currentPath: string | null;
visitedNodes: WeakSet<ArbitraryObject>;
depth: number;
}
/**
* parent and key are null when processing the root object
*/
export type TraversalCallbackContext = {
parent: ArbitraryObject | null;
key: string | null;
value: any;
meta: TraversalMeta;
};
export type TraversalCallback = (context: TraversalCallbackContext) => void;
/** Applies a given callback function to all properties of an object and its children objects */
export const traverse = (
root: ArbitraryObject,
callback: TraversalCallback
): void => {
if (typeof root !== 'object' || root === null) {
throw new Error('First argument must be an object');
}
const recursionMeta: TraversalMeta = {
visitedNodes: new WeakSet(),
currentPath: null,
depth: 0,
};
callback({ parent: null, key: null, value: root, meta: recursionMeta });
_traverse(root, callback, recursionMeta);
};
const _traverse = (
object: ArbitraryObject,
callback: TraversalCallback,
meta: TraversalMeta
) => {
if (meta.visitedNodes.has(object)) {
return;
}
meta.visitedNodes.add(object);
for (const key in object) {
const value = object[key];
const previousPath = meta.currentPath;
const currentPath = !previousPath ? `${key}` : `${previousPath}.${key}`;
const newMeta: TraversalMeta = {
currentPath: currentPath,
visitedNodes: meta.visitedNodes,
depth: meta.depth + 1,
};
callback({ parent: object, key, value, meta: newMeta });
if (typeof value === 'object' && value !== null) {
_traverse(value, callback, newMeta);
}
}
};
| 24.550725 | 96 | 0.671192 | 52 | 2 | 0 | 5 | 7 | 7 | 1 | 2 | 6 | 4 | 2 | 14 | 449 | 0.01559 | 0.01559 | 0.01559 | 0.008909 | 0.004454 | 0.095238 | 0.285714 | 0.269565 | type ArbitraryObject = Record<string, any>;
export interface TraversalMeta {
currentPath;
visitedNodes;
depth;
}
/**
* parent and key are null when processing the root object
*/
export type TraversalCallbackContext = {
parent;
key;
value;
meta;
};
export type TraversalCallback = (context) => void;
/** Applies a given callback function to all properties of an object and its children objects */
export const traverse = (
root,
callback
) => {
if (typeof root !== 'object' || root === null) {
throw new Error('First argument must be an object');
}
const recursionMeta = {
visitedNodes: new WeakSet(),
currentPath: null,
depth: 0,
};
callback({ parent: null, key: null, value: root, meta: recursionMeta });
_traverse(root, callback, recursionMeta);
};
/* Example usages of '_traverse' are shown below:
_traverse(root, callback, recursionMeta);
_traverse(value, callback, newMeta);
*/
const _traverse = (
object,
callback,
meta
) => {
if (meta.visitedNodes.has(object)) {
return;
}
meta.visitedNodes.add(object);
for (const key in object) {
const value = object[key];
const previousPath = meta.currentPath;
const currentPath = !previousPath ? `${key}` : `${previousPath}.${key}`;
const newMeta = {
currentPath: currentPath,
visitedNodes: meta.visitedNodes,
depth: meta.depth + 1,
};
callback({ parent: object, key, value, meta: newMeta });
if (typeof value === 'object' && value !== null) {
_traverse(value, callback, newMeta);
}
}
};
|
555e98efc9e473d736ca11e9b35e919ff786f60b | 2,613 | ts | TypeScript | packages/api-apw/__tests__/utils/graphql/contentReview.ts | ShraavaniTople/webiny-js | ed0b473610b0efe04e843bec914146dfcf9069f0 | [
"MIT"
] | 2 | 2022-03-16T10:22:54.000Z | 2022-03-16T10:23:22.000Z | packages/api-apw/__tests__/utils/graphql/contentReview.ts | ShraavaniTople/webiny-js | ed0b473610b0efe04e843bec914146dfcf9069f0 | [
"MIT"
] | null | null | null | packages/api-apw/__tests__/utils/graphql/contentReview.ts | ShraavaniTople/webiny-js | ed0b473610b0efe04e843bec914146dfcf9069f0 | [
"MIT"
] | null | null | null | const ERROR_FIELDS = `{
message
code
data
}`;
const getDataFields = (fields = "") => `{
id
createdOn
savedOn
createdBy {
id
displayName
type
}
status
steps {
status
slug
pendingChangeRequests
signOffProvidedOn
signOffProvidedBy {
id
displayName
}
}
content {
type
id
settings
}
${fields}
}`;
export const GET_CONTENT_REVIEW_QUERY = /* GraphQL */ `
query GetContentReview($id: ID!) {
apw {
getContentReview(id: $id) {
data ${getDataFields()}
error ${ERROR_FIELDS}
}
}
}
`;
export const LIST_CONTENT_REVIEWS_QUERY = /* GraphQL */ `
query ListContentReviews(
$where: ApwListContentReviewsWhereInput,
$limit: Int,
$after: String,
$sort: [ApwListContentReviewsSort!],
$search: ApwListContentReviewsSearchInput
) {
apw {
listContentReviews(
where: $where,
limit: $limit,
after: $after,
sort: $sort,
search: $search
) {
data ${getDataFields()}
error ${ERROR_FIELDS}
meta {
hasMoreItems
totalCount
cursor
}
}
}
}
`;
export const CREATE_CONTENT_REVIEW_MUTATION = /* GraphQL */ `
mutation CreateContentReviewMutation($data: ApwCreateContentReviewInput!) {
apw {
createContentReview(data: $data) {
data ${getDataFields()}
error ${ERROR_FIELDS}
}
}
}
`;
export const DELETE_CONTENT_REVIEW_MUTATION = /* GraphQL */ `
mutation DeleteContentReviewMutation($id: ID!) {
apw {
deleteContentReview(id: $id) {
data
error ${ERROR_FIELDS}
}
}
}
`;
export const PROVIDE_SIGN_OFF_MUTATION = /* GraphQL */ `
mutation ProvideSignOffMutation($id: ID!, $step: String!) {
apw {
provideSignOff(id: $id, step: $step) {
data
error ${ERROR_FIELDS}
}
}
}
`;
export const RETRACT_SIGN_OFF_MUTATION = /* GraphQL */ `
mutation RetractSignOffMutation($id: ID!, $step: String!) {
apw {
retractSignOff(id: $id, step: $step) {
data
error ${ERROR_FIELDS}
}
}
}
`;
| 22.333333 | 79 | 0.479143 | 109 | 1 | 0 | 1 | 8 | 0 | 1 | 0 | 0 | 0 | 0 | 27 | 583 | 0.003431 | 0.013722 | 0 | 0 | 0 | 0 | 0 | 0.223229 | const ERROR_FIELDS = `{
message
code
data
}`;
/* Example usages of 'getDataFields' are shown below:
getDataFields();
*/
const getDataFields = (fields = "") => `{
id
createdOn
savedOn
createdBy {
id
displayName
type
}
status
steps {
status
slug
pendingChangeRequests
signOffProvidedOn
signOffProvidedBy {
id
displayName
}
}
content {
type
id
settings
}
${fields}
}`;
export const GET_CONTENT_REVIEW_QUERY = /* GraphQL */ `
query GetContentReview($id: ID!) {
apw {
getContentReview(id: $id) {
data ${getDataFields()}
error ${ERROR_FIELDS}
}
}
}
`;
export const LIST_CONTENT_REVIEWS_QUERY = /* GraphQL */ `
query ListContentReviews(
$where: ApwListContentReviewsWhereInput,
$limit: Int,
$after: String,
$sort: [ApwListContentReviewsSort!],
$search: ApwListContentReviewsSearchInput
) {
apw {
listContentReviews(
where: $where,
limit: $limit,
after: $after,
sort: $sort,
search: $search
) {
data ${getDataFields()}
error ${ERROR_FIELDS}
meta {
hasMoreItems
totalCount
cursor
}
}
}
}
`;
export const CREATE_CONTENT_REVIEW_MUTATION = /* GraphQL */ `
mutation CreateContentReviewMutation($data: ApwCreateContentReviewInput!) {
apw {
createContentReview(data: $data) {
data ${getDataFields()}
error ${ERROR_FIELDS}
}
}
}
`;
export const DELETE_CONTENT_REVIEW_MUTATION = /* GraphQL */ `
mutation DeleteContentReviewMutation($id: ID!) {
apw {
deleteContentReview(id: $id) {
data
error ${ERROR_FIELDS}
}
}
}
`;
export const PROVIDE_SIGN_OFF_MUTATION = /* GraphQL */ `
mutation ProvideSignOffMutation($id: ID!, $step: String!) {
apw {
provideSignOff(id: $id, step: $step) {
data
error ${ERROR_FIELDS}
}
}
}
`;
export const RETRACT_SIGN_OFF_MUTATION = /* GraphQL */ `
mutation RetractSignOffMutation($id: ID!, $step: String!) {
apw {
retractSignOff(id: $id, step: $step) {
data
error ${ERROR_FIELDS}
}
}
}
`;
|
5569fce94fce84ef6b91a4509fa4e15b99bd4ec2 | 1,085 | ts | TypeScript | src/models/database/DBRequest.ts | Sink-or-be-Sunk/Websocket_Server | a432935ee6fbf7e05d469cd983cbdd84da196c35 | [
"MIT"
] | null | null | null | src/models/database/DBRequest.ts | Sink-or-be-Sunk/Websocket_Server | a432935ee6fbf7e05d469cd983cbdd84da196c35 | [
"MIT"
] | 1 | 2022-01-24T01:23:45.000Z | 2022-01-24T01:23:45.000Z | src/models/database/DBRequest.ts | Sink-or-be-Sunk/Websocket_Server | a432935ee6fbf7e05d469cd983cbdd84da196c35 | [
"MIT"
] | null | null | null | export class DBRequest {
type: DB_REQ_TYPE;
data: string;
constructor(raw: unknown) {
this.type = DB_REQ_TYPE.INVALID;
this.data = "";
try {
if (isInstance(raw)) {
const req = raw as DBRequest;
this.data = req.data;
this.type = req.type;
} else {
this.type = DB_REQ_TYPE.INVALID;
}
} catch (err) {
this.type = DB_REQ_TYPE.BAD_FORMAT;
}
}
isValid(): boolean {
if (
this.type == DB_REQ_TYPE.BAD_FORMAT ||
this.type == DB_REQ_TYPE.INVALID
) {
return false;
} else {
return true;
}
}
toString(): string {
return JSON.stringify(this);
}
}
export function isInstance(object: unknown): boolean {
if (typeof object === "object" && object !== null) {
if ("type" in object) {
const instance = object as DBRequest;
if (
instance.type === DB_REQ_TYPE.GET_FRIENDS ||
instance.type == DB_REQ_TYPE.INVITE_TO_GAME
) {
return true;
}
}
}
return false;
}
export enum DB_REQ_TYPE {
GET_FRIENDS = "GET FRIENDS",
INVITE_TO_GAME = "INVITE TO GAME",
INVALID = "INVALID",
BAD_FORMAT = "BAD FORMAT",
}
| 18.706897 | 54 | 0.629493 | 52 | 4 | 0 | 2 | 2 | 2 | 1 | 0 | 6 | 1 | 3 | 8.5 | 401 | 0.014963 | 0.004988 | 0.004988 | 0.002494 | 0.007481 | 0 | 0.6 | 0.223721 | export class DBRequest {
type;
data;
constructor(raw) {
this.type = DB_REQ_TYPE.INVALID;
this.data = "";
try {
if (isInstance(raw)) {
const req = raw as DBRequest;
this.data = req.data;
this.type = req.type;
} else {
this.type = DB_REQ_TYPE.INVALID;
}
} catch (err) {
this.type = DB_REQ_TYPE.BAD_FORMAT;
}
}
isValid() {
if (
this.type == DB_REQ_TYPE.BAD_FORMAT ||
this.type == DB_REQ_TYPE.INVALID
) {
return false;
} else {
return true;
}
}
toString() {
return JSON.stringify(this);
}
}
export /* Example usages of 'isInstance' are shown below:
isInstance(raw);
*/
function isInstance(object) {
if (typeof object === "object" && object !== null) {
if ("type" in object) {
const instance = object as DBRequest;
if (
instance.type === DB_REQ_TYPE.GET_FRIENDS ||
instance.type == DB_REQ_TYPE.INVITE_TO_GAME
) {
return true;
}
}
}
return false;
}
export enum DB_REQ_TYPE {
GET_FRIENDS = "GET FRIENDS",
INVITE_TO_GAME = "INVITE TO GAME",
INVALID = "INVALID",
BAD_FORMAT = "BAD FORMAT",
}
|
55ca1837cce770e7e7f0bda123564f098fe3a486 | 8,925 | ts | TypeScript | mod.ts | alimo/jalaali-deno | 9a7533a43baac27992b30e595624562435de5820 | [
"MIT"
] | 2 | 2022-01-15T16:18:36.000Z | 2022-03-23T07:22:52.000Z | mod.ts | alimo/jalaali-deno | 9a7533a43baac27992b30e595624562435de5820 | [
"MIT"
] | null | null | null | mod.ts | alimo/jalaali-deno | 9a7533a43baac27992b30e595624562435de5820 | [
"MIT"
] | null | null | null | export type JalaaliDate = { jy: number; jm: number; jd: number };
export type GregorianDate = { gy: number; gm: number; gd: number };
/**
* Converts a Gregorian date to Jalaali.
*/
export function toJalaali(date: Date): JalaaliDate;
export function toJalaali(gy: number, gm: number, gd: number): JalaaliDate;
export function toJalaali(
gy: Date | number,
gm?: number,
gd?: number,
): JalaaliDate {
if (gy instanceof Date) {
gd = gy.getDate();
gm = gy.getMonth() + 1;
gy = gy.getFullYear();
}
return d2j(g2d(gy, gm!, gd!));
}
/**
* Converts a Jalaali date to Gregorian.
*/
export function toGregorian(jy: number, jm: number, jd: number): GregorianDate {
return d2g(j2d(jy, jm, jd));
}
/**
* Checks whether a Jalaali date is valid or not.
*/
export function isValidJalaaliDate(
jy: number,
jm: number,
jd: number,
): boolean {
return (
jy >= minJalaaliYear &&
jy <= maxJalaaliYear &&
jm >= 1 &&
jm <= 12 &&
jd >= 1 &&
jd <= jalaaliMonthLength(jy, jm)
);
}
/**
* Is this a leap year or not?
*/
export function isLeapJalaaliYear(jy: number): boolean {
return jalCalLeap(jy) === 0;
}
/**
* The number of days in a given month in a Jalaali year.
*/
export function jalaaliMonthLength(jy: number, jm: number): number {
if (jm <= 6) {
return 31;
}
if (jm <= 11) {
return 30;
}
if (isLeapJalaaliYear(jy)) {
return 30;
}
return 29;
}
/**
* This function determines if the Jalaali (Persian) year is
* leap (366-day long) or is the common year (365 days), and
* finds the day in March (Gregorian calendar) of the first
* day of the Jalaali year (jy).
*
* @param jy Jalaali calendar year (-61 to 3177)
* @param withoutLeap when don't need leap (true or false) default is false
* @returns
* leap: number of years since the last leap year (0 to 4)
* gy: Gregorian year of the beginning of Jalaali year
* march: the March day of Farvardin the 1st (1st day of jy)
* @see: http://www.astro.uni.torun.pl/~kb/Papers/EMP/PersianC-EMP.htm
* @see: http://www.fourmilab.ch/documents/calendar/
*/
export function jalCal(jy: number, withoutLeap = false): {
leap?: number;
gy: number;
march: number;
} {
validateJalaaliYear(jy);
let jump = 0;
let leapJ = -14;
let jp = minJalaaliYear;
// Find the limiting years for the Jalaali year jy.
for (const jm of breaks) {
jump = jm - jp;
if (jy >= jm) {
jp = jm;
leapJ = leapJ + div(jump, 33) * 8 + div(mod(jump, 33), 4);
}
}
let n = jy - jp;
// Find the number of leap years from AD 621 to the beginning
// of the current Jalaali year in the Persian calendar.
leapJ = leapJ + div(n, 33) * 8 + div(mod(n, 33) + 3, 4);
if (mod(jump, 33) === 4 && jump - n === 4) {
leapJ += 1;
}
const gy = jy + 621;
// And the same in the Gregorian calendar (until the year gy).
const leapG = div(gy, 4) - div((div(gy, 100) + 1) * 3, 4) - 150;
// Determine the Gregorian date of Farvardin the 1st.
const march = 20 + leapJ - leapG;
// return with gy and march when we don't need leap
if (withoutLeap) {
return {
gy,
march,
};
}
// Find how many years have passed since the last leap year.
if (jump - n < 6) {
n = n - jump + div(jump + 4, 33) * 33;
}
let leap = mod(mod(n + 1, 33) - 1, 4);
if (leap === -1) {
leap = 4;
}
return {
leap,
gy,
march,
};
}
/**
* Converts a date of the Jalaali calendar to the Julian Day number.
*
* @param jy Jalaali year (1 to 3100)
* @param jm Jalaali month (1 to 12)
* @param jd Jalaali day (1 to 29/31)
* @returns Julian Day number
*/
export function j2d(jy: number, jm: number, jd: number): number {
const { gy, march } = jalCal(jy, true);
return g2d(gy, 3, march) + (jm - 1) * 31 - div(jm, 7) * (jm - 7) + jd - 1;
}
/**
* Converts the Julian Day number to a date in the Jalaali calendar.
*
* @param jdn Julian Day number
* @returns
* jy: Jalaali year (1 to 3100)
* jm: Jalaali month (1 to 12)
* jd: Jalaali day (1 to 29/31)
*/
export function d2j(jdn: number): JalaaliDate {
const gy = d2g(jdn).gy; // Calculate Gregorian year (gy).
let jy = gy - 621;
const r = jalCal(jy, false);
const jdn1f = g2d(gy, 3, r.march);
let jd;
let jm;
let k;
// Find number of days that passed since 1 Farvardin.
k = jdn - jdn1f;
if (k >= 0) {
if (k <= 185) {
// The first 6 months.
jm = 1 + div(k, 31);
jd = mod(k, 31) + 1;
return { jy: jy, jm: jm, jd: jd };
} else {
// The remaining months.
k -= 186;
}
} else {
// Previous Jalaali year.
jy -= 1;
k += 179;
if (r.leap === 1) k += 1;
}
jm = 7 + div(k, 30);
jd = mod(k, 30) + 1;
return { jy: jy, jm: jm, jd: jd };
}
/**
* Calculates the Julian Day number from Gregorian or Julian
* calendar dates. This integer number corresponds to the noon of
* the date (i.e. 12 hours of Universal Time).
* The procedure was tested to be good since 1 March, -100100 (of both
* calendars) up to a few million years into the future.
*
* @param gy Calendar year (years BC numbered 0, -1, -2, ...)
* @param gm Calendar month (1 to 12)
* @param gd Calendar day of the month (1 to 28/29/30/31)
* @returns Julian Day number
*/
export function g2d(gy: number, gm: number, gd: number): number {
let d = div((gy + div(gm - 8, 6) + 100100) * 1461, 4) +
div(153 * mod(gm + 9, 12) + 2, 5) +
gd -
34840408;
d = d - div(div(gy + 100100 + div(gm - 8, 6), 100) * 3, 4) + 752;
return d;
}
/**
* Calculates Gregorian and Julian calendar dates from the Julian Day number
* (jdn) for the period since jdn=-34839655 (i.e. the year -100100 of both
* calendars) to some millions of years ahead of the present.
*
* @param jdn Julian Day number
* @returns
* gy: Calendar year (years BC numbered 0, -1, -2, ...)
* gm: Calendar month (1 to 12)
* gd: Calendar day of the month M (1 to 28/29/30/31)
*/
export function d2g(jdn: number): GregorianDate {
let j = 4 * jdn + 139361631;
j = j + div(div(4 * jdn + 183187720, 146097) * 3, 4) * 4 - 3908;
const i = div(mod(j, 1461), 4) * 5 + 308;
const gd = div(mod(i, 153), 5) + 1;
const gm = mod(div(i, 153), 12) + 1;
const gy = div(j, 1461) - 100100 + div(8 - gm, 6);
return { gy, gm, gd };
}
/**
* Returns Saturday and Friday day of the current week
* (week starts on Saturday)
*
* @param jy jalaali year
* @param jm jalaali month
* @param jd jalaali day
* @returns Saturday and Friday of the current week
*/
export function jalaaliWeek(jy: number, jm: number, jd: number): {
saturday: JalaaliDate;
friday: JalaaliDate;
} {
const dayOfWeek = jalaaliToDateObject(jy, jm, jd).getDay();
const startDayDifference = dayOfWeek == 6 ? 0 : -(dayOfWeek + 1);
const endDayDifference = 6 + startDayDifference;
return {
saturday: d2j(j2d(jy, jm, jd + startDayDifference)),
friday: d2j(j2d(jy, jm, jd + endDayDifference)),
};
}
/**
* Convert Jalaali calendar dates to javascript Date object
*
* @param jy jalaali year
* @param jm jalaali month
* @param jd jalaali day
* @param [h] hours
* @param [m] minutes
* @param [s] seconds
* @param [ms] milliseconds
* @returns Date object of the jalaali calendar dates
*/
export function jalaaliToDateObject(
jy: number,
jm: number,
jd: number,
h = 0,
m = 0,
s = 0,
ms = 0,
): Date {
const { gy, gm, gd } = toGregorian(jy, jm, jd);
return new Date(gy, gm - 1, gd, h, m, s, ms);
}
/**
* Checks wether the jalaali year is between min and max
*/
function validateJalaaliYear(jy: number) {
if (jy < minJalaaliYear || jy > maxJalaaliYear) {
throw new Error(`Invalid Jalaali year ${jy}`);
}
}
/**
* This function determines if the Jalaali (Persian) year is a leap
* (366-day long) or is the common year (365 days), and finds the day in March
* (Gregorian calendar) of the first day of the Jalaali year (jy).
*
* @param jy Jalaali calendar year (-61 to 3177)
* @returns number of years since the last leap year (0 to 4)
*/
function jalCalLeap(jy: number) {
validateJalaaliYear(jy);
let jump = 0;
let jp = minJalaaliYear;
for (const jm of breaks) {
jump = jm - jp;
if (jy >= jm) {
jp = jm;
}
}
let n = jy - jp;
if (jump - n < 6) {
n = n - jump + div(jump + 4, 33) * 33;
}
const leap = mod(mod(n + 1, 33) - 1, 4);
if (leap === -1) {
return 4;
}
return leap;
}
/**
* Utility helper functions.
*/
function div(a: number, b: number): number {
return ~~(a / b);
}
function mod(a: number, b: number): number {
return a - ~~(a / b) * b;
}
/**
* Jalaali years starting the 33-year rule.
*/
const breaks: number[] = [
-61,
9,
38,
199,
426,
686,
756,
818,
1111,
1181,
1210,
1635,
2060,
2097,
2192,
2262,
2324,
2394,
2456,
3178,
];
const minJalaaliYear = breaks[0];
const maxJalaaliYear = breaks[breaks.length - 1] - 1;
| 24.186992 | 80 | 0.606499 | 217 | 16 | 2 | 42 | 33 | 6 | 13 | 0 | 53 | 2 | 1 | 8.375 | 3,513 | 0.01651 | 0.009394 | 0.001708 | 0.000569 | 0.000285 | 0 | 0.535354 | 0.242874 | export type JalaaliDate = { jy; jm; jd };
export type GregorianDate = { gy; gm; gd };
/**
* Converts a Gregorian date to Jalaali.
*/
export function toJalaali(date);
export function toJalaali(gy, gm, gd);
export function toJalaali(
gy,
gm?,
gd?,
) {
if (gy instanceof Date) {
gd = gy.getDate();
gm = gy.getMonth() + 1;
gy = gy.getFullYear();
}
return d2j(g2d(gy, gm!, gd!));
}
/**
* Converts a Jalaali date to Gregorian.
*/
export /* Example usages of 'toGregorian' are shown below:
toGregorian(jy, jm, jd);
*/
function toGregorian(jy, jm, jd) {
return d2g(j2d(jy, jm, jd));
}
/**
* Checks whether a Jalaali date is valid or not.
*/
export function isValidJalaaliDate(
jy,
jm,
jd,
) {
return (
jy >= minJalaaliYear &&
jy <= maxJalaaliYear &&
jm >= 1 &&
jm <= 12 &&
jd >= 1 &&
jd <= jalaaliMonthLength(jy, jm)
);
}
/**
* Is this a leap year or not?
*/
export /* Example usages of 'isLeapJalaaliYear' are shown below:
isLeapJalaaliYear(jy);
*/
function isLeapJalaaliYear(jy) {
return jalCalLeap(jy) === 0;
}
/**
* The number of days in a given month in a Jalaali year.
*/
export /* Example usages of 'jalaaliMonthLength' are shown below:
jy >= minJalaaliYear &&
jy <= maxJalaaliYear &&
jm >= 1 &&
jm <= 12 &&
jd >= 1 &&
jd <= jalaaliMonthLength(jy, jm);
*/
function jalaaliMonthLength(jy, jm) {
if (jm <= 6) {
return 31;
}
if (jm <= 11) {
return 30;
}
if (isLeapJalaaliYear(jy)) {
return 30;
}
return 29;
}
/**
* This function determines if the Jalaali (Persian) year is
* leap (366-day long) or is the common year (365 days), and
* finds the day in March (Gregorian calendar) of the first
* day of the Jalaali year (jy).
*
* @param jy Jalaali calendar year (-61 to 3177)
* @param withoutLeap when don't need leap (true or false) default is false
* @returns
* leap: number of years since the last leap year (0 to 4)
* gy: Gregorian year of the beginning of Jalaali year
* march: the March day of Farvardin the 1st (1st day of jy)
* @see: http://www.astro.uni.torun.pl/~kb/Papers/EMP/PersianC-EMP.htm
* @see: http://www.fourmilab.ch/documents/calendar/
*/
export /* Example usages of 'jalCal' are shown below:
jalCal(jy, true);
jalCal(jy, false);
*/
function jalCal(jy, withoutLeap = false) {
validateJalaaliYear(jy);
let jump = 0;
let leapJ = -14;
let jp = minJalaaliYear;
// Find the limiting years for the Jalaali year jy.
for (const jm of breaks) {
jump = jm - jp;
if (jy >= jm) {
jp = jm;
leapJ = leapJ + div(jump, 33) * 8 + div(mod(jump, 33), 4);
}
}
let n = jy - jp;
// Find the number of leap years from AD 621 to the beginning
// of the current Jalaali year in the Persian calendar.
leapJ = leapJ + div(n, 33) * 8 + div(mod(n, 33) + 3, 4);
if (mod(jump, 33) === 4 && jump - n === 4) {
leapJ += 1;
}
const gy = jy + 621;
// And the same in the Gregorian calendar (until the year gy).
const leapG = div(gy, 4) - div((div(gy, 100) + 1) * 3, 4) - 150;
// Determine the Gregorian date of Farvardin the 1st.
const march = 20 + leapJ - leapG;
// return with gy and march when we don't need leap
if (withoutLeap) {
return {
gy,
march,
};
}
// Find how many years have passed since the last leap year.
if (jump - n < 6) {
n = n - jump + div(jump + 4, 33) * 33;
}
let leap = mod(mod(n + 1, 33) - 1, 4);
if (leap === -1) {
leap = 4;
}
return {
leap,
gy,
march,
};
}
/**
* Converts a date of the Jalaali calendar to the Julian Day number.
*
* @param jy Jalaali year (1 to 3100)
* @param jm Jalaali month (1 to 12)
* @param jd Jalaali day (1 to 29/31)
* @returns Julian Day number
*/
export /* Example usages of 'j2d' are shown below:
d2g(j2d(jy, jm, jd));
d2j(j2d(jy, jm, jd + startDayDifference));
d2j(j2d(jy, jm, jd + endDayDifference));
*/
function j2d(jy, jm, jd) {
const { gy, march } = jalCal(jy, true);
return g2d(gy, 3, march) + (jm - 1) * 31 - div(jm, 7) * (jm - 7) + jd - 1;
}
/**
* Converts the Julian Day number to a date in the Jalaali calendar.
*
* @param jdn Julian Day number
* @returns
* jy: Jalaali year (1 to 3100)
* jm: Jalaali month (1 to 12)
* jd: Jalaali day (1 to 29/31)
*/
export /* Example usages of 'd2j' are shown below:
d2j(g2d(gy, gm!, gd!));
d2j(j2d(jy, jm, jd + startDayDifference));
d2j(j2d(jy, jm, jd + endDayDifference));
*/
function d2j(jdn) {
const gy = d2g(jdn).gy; // Calculate Gregorian year (gy).
let jy = gy - 621;
const r = jalCal(jy, false);
const jdn1f = g2d(gy, 3, r.march);
let jd;
let jm;
let k;
// Find number of days that passed since 1 Farvardin.
k = jdn - jdn1f;
if (k >= 0) {
if (k <= 185) {
// The first 6 months.
jm = 1 + div(k, 31);
jd = mod(k, 31) + 1;
return { jy: jy, jm: jm, jd: jd };
} else {
// The remaining months.
k -= 186;
}
} else {
// Previous Jalaali year.
jy -= 1;
k += 179;
if (r.leap === 1) k += 1;
}
jm = 7 + div(k, 30);
jd = mod(k, 30) + 1;
return { jy: jy, jm: jm, jd: jd };
}
/**
* Calculates the Julian Day number from Gregorian or Julian
* calendar dates. This integer number corresponds to the noon of
* the date (i.e. 12 hours of Universal Time).
* The procedure was tested to be good since 1 March, -100100 (of both
* calendars) up to a few million years into the future.
*
* @param gy Calendar year (years BC numbered 0, -1, -2, ...)
* @param gm Calendar month (1 to 12)
* @param gd Calendar day of the month (1 to 28/29/30/31)
* @returns Julian Day number
*/
export /* Example usages of 'g2d' are shown below:
d2j(g2d(gy, gm!, gd!));
g2d(gy, 3, march) + (jm - 1) * 31 - div(jm, 7) * (jm - 7) + jd - 1;
g2d(gy, 3, r.march);
*/
function g2d(gy, gm, gd) {
let d = div((gy + div(gm - 8, 6) + 100100) * 1461, 4) +
div(153 * mod(gm + 9, 12) + 2, 5) +
gd -
34840408;
d = d - div(div(gy + 100100 + div(gm - 8, 6), 100) * 3, 4) + 752;
return d;
}
/**
* Calculates Gregorian and Julian calendar dates from the Julian Day number
* (jdn) for the period since jdn=-34839655 (i.e. the year -100100 of both
* calendars) to some millions of years ahead of the present.
*
* @param jdn Julian Day number
* @returns
* gy: Calendar year (years BC numbered 0, -1, -2, ...)
* gm: Calendar month (1 to 12)
* gd: Calendar day of the month M (1 to 28/29/30/31)
*/
export /* Example usages of 'd2g' are shown below:
d2g(j2d(jy, jm, jd));
d2g(jdn).gy;
*/
function d2g(jdn) {
let j = 4 * jdn + 139361631;
j = j + div(div(4 * jdn + 183187720, 146097) * 3, 4) * 4 - 3908;
const i = div(mod(j, 1461), 4) * 5 + 308;
const gd = div(mod(i, 153), 5) + 1;
const gm = mod(div(i, 153), 12) + 1;
const gy = div(j, 1461) - 100100 + div(8 - gm, 6);
return { gy, gm, gd };
}
/**
* Returns Saturday and Friday day of the current week
* (week starts on Saturday)
*
* @param jy jalaali year
* @param jm jalaali month
* @param jd jalaali day
* @returns Saturday and Friday of the current week
*/
export function jalaaliWeek(jy, jm, jd) {
const dayOfWeek = jalaaliToDateObject(jy, jm, jd).getDay();
const startDayDifference = dayOfWeek == 6 ? 0 : -(dayOfWeek + 1);
const endDayDifference = 6 + startDayDifference;
return {
saturday: d2j(j2d(jy, jm, jd + startDayDifference)),
friday: d2j(j2d(jy, jm, jd + endDayDifference)),
};
}
/**
* Convert Jalaali calendar dates to javascript Date object
*
* @param jy jalaali year
* @param jm jalaali month
* @param jd jalaali day
* @param [h] hours
* @param [m] minutes
* @param [s] seconds
* @param [ms] milliseconds
* @returns Date object of the jalaali calendar dates
*/
export /* Example usages of 'jalaaliToDateObject' are shown below:
jalaaliToDateObject(jy, jm, jd).getDay();
*/
function jalaaliToDateObject(
jy,
jm,
jd,
h = 0,
m = 0,
s = 0,
ms = 0,
) {
const { gy, gm, gd } = toGregorian(jy, jm, jd);
return new Date(gy, gm - 1, gd, h, m, s, ms);
}
/**
* Checks wether the jalaali year is between min and max
*/
/* Example usages of 'validateJalaaliYear' are shown below:
validateJalaaliYear(jy);
*/
function validateJalaaliYear(jy) {
if (jy < minJalaaliYear || jy > maxJalaaliYear) {
throw new Error(`Invalid Jalaali year ${jy}`);
}
}
/**
* This function determines if the Jalaali (Persian) year is a leap
* (366-day long) or is the common year (365 days), and finds the day in March
* (Gregorian calendar) of the first day of the Jalaali year (jy).
*
* @param jy Jalaali calendar year (-61 to 3177)
* @returns number of years since the last leap year (0 to 4)
*/
/* Example usages of 'jalCalLeap' are shown below:
jalCalLeap(jy) === 0;
*/
function jalCalLeap(jy) {
validateJalaaliYear(jy);
let jump = 0;
let jp = minJalaaliYear;
for (const jm of breaks) {
jump = jm - jp;
if (jy >= jm) {
jp = jm;
}
}
let n = jy - jp;
if (jump - n < 6) {
n = n - jump + div(jump + 4, 33) * 33;
}
const leap = mod(mod(n + 1, 33) - 1, 4);
if (leap === -1) {
return 4;
}
return leap;
}
/**
* Utility helper functions.
*/
/* Example usages of 'div' are shown below:
leapJ = leapJ + div(jump, 33) * 8 + div(mod(jump, 33), 4);
// Find the number of leap years from AD 621 to the beginning
// of the current Jalaali year in the Persian calendar.
leapJ = leapJ + div(n, 33) * 8 + div(mod(n, 33) + 3, 4);
div(gy, 4) - div((div(gy, 100) + 1) * 3, 4) - 150;
div(gy, 100) + 1;
n = n - jump + div(jump + 4, 33) * 33;
g2d(gy, 3, march) + (jm - 1) * 31 - div(jm, 7) * (jm - 7) + jd - 1;
// The first 6 months.
jm = 1 + div(k, 31);
jm = 7 + div(k, 30);
div((gy + div(gm - 8, 6) + 100100) * 1461, 4) +
div(153 * mod(gm + 9, 12) + 2, 5) +
gd -
34840408;
gy + div(gm - 8, 6) + 100100;
d = d - div(div(gy + 100100 + div(gm - 8, 6), 100) * 3, 4) + 752;
j = j + div(div(4 * jdn + 183187720, 146097) * 3, 4) * 4 - 3908;
div(mod(j, 1461), 4) * 5 + 308;
div(mod(i, 153), 5) + 1;
mod(div(i, 153), 12) + 1;
div(j, 1461) - 100100 + div(8 - gm, 6);
*/
function div(a, b) {
return ~~(a / b);
}
/* Example usages of 'mod' are shown below:
leapJ = leapJ + div(jump, 33) * 8 + div(mod(jump, 33), 4);
// Find the number of leap years from AD 621 to the beginning
// of the current Jalaali year in the Persian calendar.
leapJ = leapJ + div(n, 33) * 8 + div(mod(n, 33) + 3, 4);
mod(jump, 33) === 4 && jump - n === 4;
mod(mod(n + 1, 33) - 1, 4);
jd = mod(k, 31) + 1;
jd = mod(k, 30) + 1;
div((gy + div(gm - 8, 6) + 100100) * 1461, 4) +
div(153 * mod(gm + 9, 12) + 2, 5) +
gd -
34840408;
div(mod(j, 1461), 4) * 5 + 308;
div(mod(i, 153), 5) + 1;
mod(div(i, 153), 12) + 1;
*/
function mod(a, b) {
return a - ~~(a / b) * b;
}
/**
* Jalaali years starting the 33-year rule.
*/
const breaks = [
-61,
9,
38,
199,
426,
686,
756,
818,
1111,
1181,
1210,
1635,
2060,
2097,
2192,
2262,
2324,
2394,
2456,
3178,
];
const minJalaaliYear = breaks[0];
const maxJalaaliYear = breaks[breaks.length - 1] - 1;
|
0309871f42d30b3ffb004bda94aebef658553a5f | 10,843 | ts | TypeScript | packages/crypto/src/hashes/blake2b.ts | eike-hass/iota.js | 18ddf1ab7ffdd2ef59c6b345fe9ec70a4629bb48 | [
"Apache-2.0"
] | 1 | 2022-02-27T05:28:41.000Z | 2022-02-27T05:28:41.000Z | packages/crypto/src/hashes/blake2b.ts | eike-hass/iota.js | 18ddf1ab7ffdd2ef59c6b345fe9ec70a4629bb48 | [
"Apache-2.0"
] | null | null | null | packages/crypto/src/hashes/blake2b.ts | eike-hass/iota.js | 18ddf1ab7ffdd2ef59c6b345fe9ec70a4629bb48 | [
"Apache-2.0"
] | null | null | null | // Copyright 2020 IOTA Stiftung
// SPDX-License-Identifier: Apache-2.0
/* eslint-disable no-bitwise */
/* eslint-disable no-mixed-operators */
/**
* Class to help with Blake2B Signature scheme.
* TypeScript conversion from https://github.com/dcposch/blakejs.
*/
export class Blake2b {
/**
* Blake2b 256.
*/
public static SIZE_256: number = 32;
/**
* Blake2b 512.
*/
public static SIZE_512: number = 64;
/**
* Initialization Vector.
* @internal
*/
private static readonly BLAKE2B_IV32 = new Uint32Array([
0xf3bcc908, 0x6a09e667, 0x84caa73b, 0xbb67ae85, 0xfe94f82b, 0x3c6ef372, 0x5f1d36f1, 0xa54ff53a, 0xade682d1,
0x510e527f, 0x2b3e6c1f, 0x9b05688c, 0xfb41bd6b, 0x1f83d9ab, 0x137e2179, 0x5be0cd19
]);
/**
* Initialization Vector.
* @internal
*/
private static readonly SIGMA8 = [
0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 14, 10, 4, 8, 9, 15, 13, 6, 1, 12, 0, 2, 11, 7, 5, 3, 11,
8, 12, 0, 5, 2, 15, 13, 10, 14, 3, 6, 7, 1, 9, 4, 7, 9, 3, 1, 13, 12, 11, 14, 2, 6, 5, 10, 4, 0, 15, 8, 9, 0, 5,
7, 2, 4, 10, 15, 14, 1, 11, 12, 6, 8, 3, 13, 2, 12, 6, 10, 0, 11, 8, 3, 4, 13, 7, 5, 15, 14, 1, 9, 12, 5, 1, 15,
14, 13, 4, 10, 0, 7, 6, 3, 9, 2, 8, 11, 13, 11, 7, 14, 12, 1, 3, 9, 5, 0, 15, 4, 8, 6, 2, 10, 6, 15, 14, 9, 11,
3, 0, 8, 12, 2, 13, 7, 1, 4, 10, 5, 10, 2, 8, 4, 7, 6, 1, 5, 15, 11, 9, 14, 3, 12, 13, 0, 0, 1, 2, 3, 4, 5, 6,
7, 8, 9, 10, 11, 12, 13, 14, 15, 14, 10, 4, 8, 9, 15, 13, 6, 1, 12, 0, 2, 11, 7, 5, 3
];
/**
* These are offsets into a uint64 buffer.
* Multiply them all by 2 to make them offsets into a uint32 buffer,
* because this is Javascript and we don't have uint64s
* @internal
*/
private static readonly SIGMA82 = new Uint8Array(Blake2b.SIGMA8.map(x => x * 2));
/**
* The V vector.
* @internal
*/
private _v: Uint32Array;
/**
* The M vector.
* @internal
*/
private _m: Uint32Array;
/**
* The context for the current hash.
* @internal
*/
private _context: {
b: Uint8Array;
h: Uint32Array;
t: number;
c: number;
outlen: number;
};
/**
* Create a new instance of Blake2b.
* @param outlen Output length between 1 and 64 bytes.
* @param key Optional key.
*/
constructor(outlen: number, key?: Uint8Array) {
this._v = new Uint32Array(32);
this._m = new Uint32Array(32);
this._context = {
b: new Uint8Array(128),
h: new Uint32Array(16),
t: 0, // input count
c: 0, // pointer within buffer
outlen // output length in bytes
};
this.init(outlen, key);
}
/**
* Perform Sum 256 on the data.
* @param data The data to operate on.
* @param key Optional key for the hash.
* @returns The sum 256 of the data.
*/
public static sum256(data: Uint8Array, key?: Uint8Array): Uint8Array {
const b2b = new Blake2b(Blake2b.SIZE_256, key);
b2b.update(data);
return b2b.final();
}
/**
* Perform Sum 512 on the data.
* @param data The data to operate on.
* @param key Optional key for the hash.
* @returns The sum 512 of the data.
*/
public static sum512(data: Uint8Array, key?: Uint8Array): Uint8Array {
const b2b = new Blake2b(Blake2b.SIZE_512, key);
b2b.update(data);
return b2b.final();
}
/**
* Updates a BLAKE2b streaming hash.
* @param input The data to hash.
*/
public update(input: Uint8Array): void {
for (let i = 0; i < input.length; i++) {
if (this._context.c === 128) {
// buffer full ?
this._context.t += this._context.c; // add counters
this.compress(false); // compress (not last)
this._context.c = 0; // counter to zero
}
this._context.b[this._context.c++] = input[i];
}
}
/**
* Completes a BLAKE2b streaming hash.
* @returns The final data.
*/
public final(): Uint8Array {
this._context.t += this._context.c; // mark last block offset
while (this._context.c < 128) {
// fill up with zeros
this._context.b[this._context.c++] = 0;
}
this.compress(true); // final block flag = 1
// little endian convert and store
const out = new Uint8Array(this._context.outlen);
for (let i = 0; i < this._context.outlen; i++) {
out[i] = this._context.h[i >> 2] >> (8 * (i & 3));
}
return out;
}
/**
* Creates a BLAKE2b hashing context.
* @param outlen Output length between 1 and 64 bytes.
* @param key Optional key.
* @returns The initialized context.
* @internal
*/
private init(outlen: number, key?: Uint8Array): void {
if (outlen <= 0 || outlen > 64) {
throw new Error("Illegal output length, expected 0 < length <= 64");
}
if (key && key.length > 64) {
throw new Error("Illegal key, expected Uint8Array with 0 < length <= 64");
}
// initialize hash state
for (let i = 0; i < 16; i++) {
this._context.h[i] = Blake2b.BLAKE2B_IV32[i];
}
const keylen = key ? key.length : 0;
this._context.h[0] ^= 0x01010000 ^ (keylen << 8) ^ outlen;
// key the hash, if applicable
if (key) {
this.update(key);
// at the end
this._context.c = 128;
}
}
/**
* Compression.
* Note we're representing 16 uint64s as 32 uint32s
* @param last Is this the last block.
* @internal
*/
private compress(last: boolean): void {
let i = 0;
// init work variables
for (i = 0; i < 16; i++) {
this._v[i] = this._context.h[i];
this._v[i + 16] = Blake2b.BLAKE2B_IV32[i];
}
// low 64 bits of offset
this._v[24] ^= this._context.t;
this._v[25] ^= this._context.t / 0x100000000;
// high 64 bits not supported, offset may not be higher than 2**53-1
// last block flag set ?
if (last) {
this._v[28] = ~this._v[28];
this._v[29] = ~this._v[29];
}
// get little-endian words
for (i = 0; i < 32; i++) {
this._m[i] = this.b2bGet32(this._context.b, 4 * i);
}
// twelve rounds of mixing
for (i = 0; i < 12; i++) {
this.b2bG(0, 8, 16, 24, Blake2b.SIGMA82[i * 16 + 0], Blake2b.SIGMA82[i * 16 + 1]);
this.b2bG(2, 10, 18, 26, Blake2b.SIGMA82[i * 16 + 2], Blake2b.SIGMA82[i * 16 + 3]);
this.b2bG(4, 12, 20, 28, Blake2b.SIGMA82[i * 16 + 4], Blake2b.SIGMA82[i * 16 + 5]);
this.b2bG(6, 14, 22, 30, Blake2b.SIGMA82[i * 16 + 6], Blake2b.SIGMA82[i * 16 + 7]);
this.b2bG(0, 10, 20, 30, Blake2b.SIGMA82[i * 16 + 8], Blake2b.SIGMA82[i * 16 + 9]);
this.b2bG(2, 12, 22, 24, Blake2b.SIGMA82[i * 16 + 10], Blake2b.SIGMA82[i * 16 + 11]);
this.b2bG(4, 14, 16, 26, Blake2b.SIGMA82[i * 16 + 12], Blake2b.SIGMA82[i * 16 + 13]);
this.b2bG(6, 8, 18, 28, Blake2b.SIGMA82[i * 16 + 14], Blake2b.SIGMA82[i * 16 + 15]);
}
for (i = 0; i < 16; i++) {
this._context.h[i] = this._context.h[i] ^ this._v[i] ^ this._v[i + 16];
}
}
/**
* 64-bit unsigned addition
* Sets v[a,a+1] += v[b,b+1]
* @param v The array.
* @param a The a index.
* @param b The b index.
* @internal
*/
private add64AA(v: Uint32Array, a: number, b: number): void {
const o0 = v[a] + v[b];
let o1 = v[a + 1] + v[b + 1];
if (o0 >= 0x100000000) {
o1++;
}
v[a] = o0;
v[a + 1] = o1;
}
/**
* 64-bit unsigned addition.
* Sets v[a,a+1] += b.
* @param v The array of data to work on.
* @param a The index to use.
* @param b0 Is the low 32 bits.
* @param b1 Represents the high 32 bits.
* @internal
*/
private add64AC(v: Uint32Array, a: number, b0: number, b1: number): void {
let o0 = v[a] + b0;
if (b0 < 0) {
o0 += 0x100000000;
}
let o1 = v[a + 1] + b1;
if (o0 >= 0x100000000) {
o1++;
}
v[a] = o0;
v[a + 1] = o1;
}
/**
* Little endian read byte 32;
* @param arr The array to read from .
* @param i The index to start reading from.
* @returns The value.
* @internal
*/
private b2bGet32(arr: ArrayLike<number>, i: number): number {
return arr[i] ^ (arr[i + 1] << 8) ^ (arr[i + 2] << 16) ^ (arr[i + 3] << 24);
}
/**
* G Mixing function.
* The ROTRs are inlined for speed.
* @param a The a value.
* @param b The b value.
* @param c The c value.
* @param d The d value.
* @param ix The ix value.
* @param iy The iy value.
* @internal
*/
private b2bG(a: number, b: number, c: number, d: number, ix: number, iy: number): void {
const x0 = this._m[ix];
const x1 = this._m[ix + 1];
const y0 = this._m[iy];
const y1 = this._m[iy + 1];
this.add64AA(this._v, a, b); // v[a,a+1] += v[b,b+1] ... in JS we must store a uint64 as two uint32s
this.add64AC(this._v, a, x0, x1); // v[a, a+1] += x ... x0 is the low 32 bits of x, x1 is the high 32 bits
// v[d,d+1] = (v[d,d+1] xor v[a,a+1]) rotated to the right by 32 bits
let xor0 = this._v[d] ^ this._v[a];
let xor1 = this._v[d + 1] ^ this._v[a + 1];
this._v[d] = xor1;
this._v[d + 1] = xor0;
this.add64AA(this._v, c, d);
// v[b,b+1] = (v[b,b+1] xor v[c,c+1]) rotated right by 24 bits
xor0 = this._v[b] ^ this._v[c];
xor1 = this._v[b + 1] ^ this._v[c + 1];
this._v[b] = (xor0 >>> 24) ^ (xor1 << 8);
this._v[b + 1] = (xor1 >>> 24) ^ (xor0 << 8);
this.add64AA(this._v, a, b);
this.add64AC(this._v, a, y0, y1);
// v[d,d+1] = (v[d,d+1] xor v[a,a+1]) rotated right by 16 bits
xor0 = this._v[d] ^ this._v[a];
xor1 = this._v[d + 1] ^ this._v[a + 1];
this._v[d] = (xor0 >>> 16) ^ (xor1 << 16);
this._v[d + 1] = (xor1 >>> 16) ^ (xor0 << 16);
this.add64AA(this._v, c, d);
// v[b,b+1] = (v[b,b+1] xor v[c,c+1]) rotated right by 63 bits
xor0 = this._v[b] ^ this._v[c];
xor1 = this._v[b + 1] ^ this._v[c + 1];
this._v[b] = (xor1 >>> 31) ^ (xor0 << 1);
this._v[b + 1] = (xor0 >>> 31) ^ (xor1 << 1);
}
}
| 32.367164 | 120 | 0.504288 | 168 | 12 | 0 | 26 | 18 | 8 | 8 | 0 | 28 | 1 | 0 | 10.083333 | 4,444 | 0.008551 | 0.00405 | 0.0018 | 0.000225 | 0 | 0 | 0.4375 | 0.205121 | // Copyright 2020 IOTA Stiftung
// SPDX-License-Identifier: Apache-2.0
/* eslint-disable no-bitwise */
/* eslint-disable no-mixed-operators */
/**
* Class to help with Blake2B Signature scheme.
* TypeScript conversion from https://github.com/dcposch/blakejs.
*/
export class Blake2b {
/**
* Blake2b 256.
*/
public static SIZE_256 = 32;
/**
* Blake2b 512.
*/
public static SIZE_512 = 64;
/**
* Initialization Vector.
* @internal
*/
private static readonly BLAKE2B_IV32 = new Uint32Array([
0xf3bcc908, 0x6a09e667, 0x84caa73b, 0xbb67ae85, 0xfe94f82b, 0x3c6ef372, 0x5f1d36f1, 0xa54ff53a, 0xade682d1,
0x510e527f, 0x2b3e6c1f, 0x9b05688c, 0xfb41bd6b, 0x1f83d9ab, 0x137e2179, 0x5be0cd19
]);
/**
* Initialization Vector.
* @internal
*/
private static readonly SIGMA8 = [
0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 14, 10, 4, 8, 9, 15, 13, 6, 1, 12, 0, 2, 11, 7, 5, 3, 11,
8, 12, 0, 5, 2, 15, 13, 10, 14, 3, 6, 7, 1, 9, 4, 7, 9, 3, 1, 13, 12, 11, 14, 2, 6, 5, 10, 4, 0, 15, 8, 9, 0, 5,
7, 2, 4, 10, 15, 14, 1, 11, 12, 6, 8, 3, 13, 2, 12, 6, 10, 0, 11, 8, 3, 4, 13, 7, 5, 15, 14, 1, 9, 12, 5, 1, 15,
14, 13, 4, 10, 0, 7, 6, 3, 9, 2, 8, 11, 13, 11, 7, 14, 12, 1, 3, 9, 5, 0, 15, 4, 8, 6, 2, 10, 6, 15, 14, 9, 11,
3, 0, 8, 12, 2, 13, 7, 1, 4, 10, 5, 10, 2, 8, 4, 7, 6, 1, 5, 15, 11, 9, 14, 3, 12, 13, 0, 0, 1, 2, 3, 4, 5, 6,
7, 8, 9, 10, 11, 12, 13, 14, 15, 14, 10, 4, 8, 9, 15, 13, 6, 1, 12, 0, 2, 11, 7, 5, 3
];
/**
* These are offsets into a uint64 buffer.
* Multiply them all by 2 to make them offsets into a uint32 buffer,
* because this is Javascript and we don't have uint64s
* @internal
*/
private static readonly SIGMA82 = new Uint8Array(Blake2b.SIGMA8.map(x => x * 2));
/**
* The V vector.
* @internal
*/
private _v;
/**
* The M vector.
* @internal
*/
private _m;
/**
* The context for the current hash.
* @internal
*/
private _context;
/**
* Create a new instance of Blake2b.
* @param outlen Output length between 1 and 64 bytes.
* @param key Optional key.
*/
constructor(outlen, key?) {
this._v = new Uint32Array(32);
this._m = new Uint32Array(32);
this._context = {
b: new Uint8Array(128),
h: new Uint32Array(16),
t: 0, // input count
c: 0, // pointer within buffer
outlen // output length in bytes
};
this.init(outlen, key);
}
/**
* Perform Sum 256 on the data.
* @param data The data to operate on.
* @param key Optional key for the hash.
* @returns The sum 256 of the data.
*/
public static sum256(data, key?) {
const b2b = new Blake2b(Blake2b.SIZE_256, key);
b2b.update(data);
return b2b.final();
}
/**
* Perform Sum 512 on the data.
* @param data The data to operate on.
* @param key Optional key for the hash.
* @returns The sum 512 of the data.
*/
public static sum512(data, key?) {
const b2b = new Blake2b(Blake2b.SIZE_512, key);
b2b.update(data);
return b2b.final();
}
/**
* Updates a BLAKE2b streaming hash.
* @param input The data to hash.
*/
public update(input) {
for (let i = 0; i < input.length; i++) {
if (this._context.c === 128) {
// buffer full ?
this._context.t += this._context.c; // add counters
this.compress(false); // compress (not last)
this._context.c = 0; // counter to zero
}
this._context.b[this._context.c++] = input[i];
}
}
/**
* Completes a BLAKE2b streaming hash.
* @returns The final data.
*/
public final() {
this._context.t += this._context.c; // mark last block offset
while (this._context.c < 128) {
// fill up with zeros
this._context.b[this._context.c++] = 0;
}
this.compress(true); // final block flag = 1
// little endian convert and store
const out = new Uint8Array(this._context.outlen);
for (let i = 0; i < this._context.outlen; i++) {
out[i] = this._context.h[i >> 2] >> (8 * (i & 3));
}
return out;
}
/**
* Creates a BLAKE2b hashing context.
* @param outlen Output length between 1 and 64 bytes.
* @param key Optional key.
* @returns The initialized context.
* @internal
*/
private init(outlen, key?) {
if (outlen <= 0 || outlen > 64) {
throw new Error("Illegal output length, expected 0 < length <= 64");
}
if (key && key.length > 64) {
throw new Error("Illegal key, expected Uint8Array with 0 < length <= 64");
}
// initialize hash state
for (let i = 0; i < 16; i++) {
this._context.h[i] = Blake2b.BLAKE2B_IV32[i];
}
const keylen = key ? key.length : 0;
this._context.h[0] ^= 0x01010000 ^ (keylen << 8) ^ outlen;
// key the hash, if applicable
if (key) {
this.update(key);
// at the end
this._context.c = 128;
}
}
/**
* Compression.
* Note we're representing 16 uint64s as 32 uint32s
* @param last Is this the last block.
* @internal
*/
private compress(last) {
let i = 0;
// init work variables
for (i = 0; i < 16; i++) {
this._v[i] = this._context.h[i];
this._v[i + 16] = Blake2b.BLAKE2B_IV32[i];
}
// low 64 bits of offset
this._v[24] ^= this._context.t;
this._v[25] ^= this._context.t / 0x100000000;
// high 64 bits not supported, offset may not be higher than 2**53-1
// last block flag set ?
if (last) {
this._v[28] = ~this._v[28];
this._v[29] = ~this._v[29];
}
// get little-endian words
for (i = 0; i < 32; i++) {
this._m[i] = this.b2bGet32(this._context.b, 4 * i);
}
// twelve rounds of mixing
for (i = 0; i < 12; i++) {
this.b2bG(0, 8, 16, 24, Blake2b.SIGMA82[i * 16 + 0], Blake2b.SIGMA82[i * 16 + 1]);
this.b2bG(2, 10, 18, 26, Blake2b.SIGMA82[i * 16 + 2], Blake2b.SIGMA82[i * 16 + 3]);
this.b2bG(4, 12, 20, 28, Blake2b.SIGMA82[i * 16 + 4], Blake2b.SIGMA82[i * 16 + 5]);
this.b2bG(6, 14, 22, 30, Blake2b.SIGMA82[i * 16 + 6], Blake2b.SIGMA82[i * 16 + 7]);
this.b2bG(0, 10, 20, 30, Blake2b.SIGMA82[i * 16 + 8], Blake2b.SIGMA82[i * 16 + 9]);
this.b2bG(2, 12, 22, 24, Blake2b.SIGMA82[i * 16 + 10], Blake2b.SIGMA82[i * 16 + 11]);
this.b2bG(4, 14, 16, 26, Blake2b.SIGMA82[i * 16 + 12], Blake2b.SIGMA82[i * 16 + 13]);
this.b2bG(6, 8, 18, 28, Blake2b.SIGMA82[i * 16 + 14], Blake2b.SIGMA82[i * 16 + 15]);
}
for (i = 0; i < 16; i++) {
this._context.h[i] = this._context.h[i] ^ this._v[i] ^ this._v[i + 16];
}
}
/**
* 64-bit unsigned addition
* Sets v[a,a+1] += v[b,b+1]
* @param v The array.
* @param a The a index.
* @param b The b index.
* @internal
*/
private add64AA(v, a, b) {
const o0 = v[a] + v[b];
let o1 = v[a + 1] + v[b + 1];
if (o0 >= 0x100000000) {
o1++;
}
v[a] = o0;
v[a + 1] = o1;
}
/**
* 64-bit unsigned addition.
* Sets v[a,a+1] += b.
* @param v The array of data to work on.
* @param a The index to use.
* @param b0 Is the low 32 bits.
* @param b1 Represents the high 32 bits.
* @internal
*/
private add64AC(v, a, b0, b1) {
let o0 = v[a] + b0;
if (b0 < 0) {
o0 += 0x100000000;
}
let o1 = v[a + 1] + b1;
if (o0 >= 0x100000000) {
o1++;
}
v[a] = o0;
v[a + 1] = o1;
}
/**
* Little endian read byte 32;
* @param arr The array to read from .
* @param i The index to start reading from.
* @returns The value.
* @internal
*/
private b2bGet32(arr, i) {
return arr[i] ^ (arr[i + 1] << 8) ^ (arr[i + 2] << 16) ^ (arr[i + 3] << 24);
}
/**
* G Mixing function.
* The ROTRs are inlined for speed.
* @param a The a value.
* @param b The b value.
* @param c The c value.
* @param d The d value.
* @param ix The ix value.
* @param iy The iy value.
* @internal
*/
private b2bG(a, b, c, d, ix, iy) {
const x0 = this._m[ix];
const x1 = this._m[ix + 1];
const y0 = this._m[iy];
const y1 = this._m[iy + 1];
this.add64AA(this._v, a, b); // v[a,a+1] += v[b,b+1] ... in JS we must store a uint64 as two uint32s
this.add64AC(this._v, a, x0, x1); // v[a, a+1] += x ... x0 is the low 32 bits of x, x1 is the high 32 bits
// v[d,d+1] = (v[d,d+1] xor v[a,a+1]) rotated to the right by 32 bits
let xor0 = this._v[d] ^ this._v[a];
let xor1 = this._v[d + 1] ^ this._v[a + 1];
this._v[d] = xor1;
this._v[d + 1] = xor0;
this.add64AA(this._v, c, d);
// v[b,b+1] = (v[b,b+1] xor v[c,c+1]) rotated right by 24 bits
xor0 = this._v[b] ^ this._v[c];
xor1 = this._v[b + 1] ^ this._v[c + 1];
this._v[b] = (xor0 >>> 24) ^ (xor1 << 8);
this._v[b + 1] = (xor1 >>> 24) ^ (xor0 << 8);
this.add64AA(this._v, a, b);
this.add64AC(this._v, a, y0, y1);
// v[d,d+1] = (v[d,d+1] xor v[a,a+1]) rotated right by 16 bits
xor0 = this._v[d] ^ this._v[a];
xor1 = this._v[d + 1] ^ this._v[a + 1];
this._v[d] = (xor0 >>> 16) ^ (xor1 << 16);
this._v[d + 1] = (xor1 >>> 16) ^ (xor0 << 16);
this.add64AA(this._v, c, d);
// v[b,b+1] = (v[b,b+1] xor v[c,c+1]) rotated right by 63 bits
xor0 = this._v[b] ^ this._v[c];
xor1 = this._v[b + 1] ^ this._v[c + 1];
this._v[b] = (xor1 >>> 31) ^ (xor0 << 1);
this._v[b + 1] = (xor0 >>> 31) ^ (xor1 << 1);
}
}
|
03401821cf21625757bc23c31fa91dbf3518110e | 1,930 | ts | TypeScript | src/lib/SFSymbol.ts | notcome/figma-custom-sf-symbols | d9efd89b137a0a55e502b3a64bf0eb457f445ba9 | [
"MIT"
] | 1 | 2022-03-09T20:33:10.000Z | 2022-03-09T20:33:10.000Z | src/lib/SFSymbol.ts | notcome/figma-custom-sf-symbols | d9efd89b137a0a55e502b3a64bf0eb457f445ba9 | [
"MIT"
] | null | null | null | src/lib/SFSymbol.ts | notcome/figma-custom-sf-symbols | d9efd89b137a0a55e502b3a64bf0eb457f445ba9 | [
"MIT"
] | null | null | null | export type Weight = 'Ultralight' | 'Thin' | 'Light' | 'Regular' | 'Medium' | 'Semibold' | 'Bold' | 'Heavy' | 'Black';
export type Scale = 'S' | 'M' | 'L';
export type Type = {
weight: Weight;
scale: Scale;
};
export type Hierarchy = 'primary' | 'secondary' | 'tertiary';
export type Variant = {
type: Type;
paths: string[];
width: number;
height: number;
};
type Group = {
pathIndices: number[];
hierarchy?: Hierarchy;
};
export type Symbol = {
name: string;
symbols: Variant[];
groups?: Group[];
};
export const weights: Weight[] = [
'Ultralight',
'Thin',
'Light',
'Regular',
'Medium',
'Semibold',
'Bold',
'Heavy',
'Black',
];
export const scales: Scale[] = ['S', 'M', 'L'];
export function closestVariant(symbol: Symbol, weight: Weight, scale: Scale): Variant {
let variant = symbol.symbols[0];
let cost = 10000;
const w1 = weights.indexOf(weight);
const s1 = scales.indexOf(scale);
for (const candidate of symbol.symbols) {
const w2 = weights.indexOf(candidate.type.weight);
const s2 = scales.indexOf(candidate.type.scale);
const total = Math.abs(w1 - w2) + Math.abs(s1 - s2);
if (total < cost) {
cost = total;
variant = candidate;
}
if (cost == 0) {
break;
}
}
return variant;
}
export function getPathsByHierarchy(groups: Group[], variant: Variant): [Hierarchy, string][] {
const list: [Hierarchy, string][] = [];
for (const group of groups) {
const path = group.pathIndices.map((i) => variant.paths[i]).join(' ');
const hierarchy = group.hierarchy ?? 'primary';
const index = list.findIndex((x) => x[0] == hierarchy);
if (index == -1) {
list.push([hierarchy, path]);
continue;
}
list[index][1] += ' ' + path;
}
return list;
}
| 25.064935 | 118 | 0.559067 | 67 | 4 | 0 | 7 | 13 | 11 | 0 | 0 | 7 | 7 | 0 | 7.75 | 553 | 0.019892 | 0.023508 | 0.019892 | 0.012658 | 0 | 0 | 0.2 | 0.313573 | export type Weight = 'Ultralight' | 'Thin' | 'Light' | 'Regular' | 'Medium' | 'Semibold' | 'Bold' | 'Heavy' | 'Black';
export type Scale = 'S' | 'M' | 'L';
export type Type = {
weight;
scale;
};
export type Hierarchy = 'primary' | 'secondary' | 'tertiary';
export type Variant = {
type;
paths;
width;
height;
};
type Group = {
pathIndices;
hierarchy?;
};
export type Symbol = {
name;
symbols;
groups?;
};
export const weights = [
'Ultralight',
'Thin',
'Light',
'Regular',
'Medium',
'Semibold',
'Bold',
'Heavy',
'Black',
];
export const scales = ['S', 'M', 'L'];
export function closestVariant(symbol, weight, scale) {
let variant = symbol.symbols[0];
let cost = 10000;
const w1 = weights.indexOf(weight);
const s1 = scales.indexOf(scale);
for (const candidate of symbol.symbols) {
const w2 = weights.indexOf(candidate.type.weight);
const s2 = scales.indexOf(candidate.type.scale);
const total = Math.abs(w1 - w2) + Math.abs(s1 - s2);
if (total < cost) {
cost = total;
variant = candidate;
}
if (cost == 0) {
break;
}
}
return variant;
}
export function getPathsByHierarchy(groups, variant) {
const list = [];
for (const group of groups) {
const path = group.pathIndices.map((i) => variant.paths[i]).join(' ');
const hierarchy = group.hierarchy ?? 'primary';
const index = list.findIndex((x) => x[0] == hierarchy);
if (index == -1) {
list.push([hierarchy, path]);
continue;
}
list[index][1] += ' ' + path;
}
return list;
}
|
1f2f2487f7f88bf87e6700f3a15415f1c549403e | 4,027 | ts | TypeScript | src/index.ts | gibatronic/TheStorage | 8a77bdda03a02041b22f976ff1205a3e2c7ed0c8 | [
"MIT"
] | 8 | 2022-02-10T16:36:12.000Z | 2022-02-14T22:06:56.000Z | src/index.ts | gibatronic/TheStorage | 8a77bdda03a02041b22f976ff1205a3e2c7ed0c8 | [
"MIT"
] | null | null | null | src/index.ts | gibatronic/TheStorage | 8a77bdda03a02041b22f976ff1205a3e2c7ed0c8 | [
"MIT"
] | 1 | 2022-02-10T16:35:03.000Z | 2022-02-10T16:35:03.000Z | type DataType<T> = {
persistent: boolean,
value: T,
};
export default class Dadado<T> {
capacity: number;
private cache: Map<T, DataType<T>>;
/*
* @param {number} capacity - Defines the maximum of items that can be in the cache
*/
constructor(capacity: number) {
if (!Number.isInteger(capacity)) {
throw Error('Expected an integer number');
}
if (Math.sign(capacity) <= 0) {
throw Error('Expected a positive number greater or equal to 1');
}
this.capacity = capacity;
this.cache = new Map();
}
/*
* Returns the cache size.
*
* @returns {number}
*/
size() {
return this.cache.size;
}
/*
* Removes all elements from the cache.
*
* @returns {void}
*/
clear() {
this.cache.clear();
}
/*
* Checks if the given key exist within the cache.
*
* @param {T} key - The cache key
* @returns {boolean}
*/
contains(key: T) {
return this.cache.has(key);
}
/*
* Adds the key-value pair to the cache if the key is not in the cache yet.
* Otherwise, if the key exists, updates the value of the key.
* In case the current number of keys exceeds the `capacity`, then it evicts the least recently used key.
*
* @param {T} key - The cache key
* @param {T} value - The value associated with the key
* @returns {boolean}
*/
setItem(key: T, value: T) {
if (this.cache.has(key)) {
const data = this.cache.get(key) as DataType<T>;
this.cache.delete(key);
data.value = value;
this.cache.set(key, data);
} else {
this.cache.set(key, {
value,
persistent: false
});
}
if (this.cache.size > this.capacity) {
const keys = this.cache.keys();
let wasDeleted = false;
if (!this.cache.size) {
return false;
}
while (!wasDeleted && this.cache.size) {
const key = keys.next().value;
const item = this.cache.get(key as T) as DataType<T>;
if (!item.persistent) {
wasDeleted = true;
this.cache.delete(key as T);
}
}
}
if (!this.cache.has(key)) {
return false;
}
return true;
}
/*
* Retrieves the value associated with the given key.
* If the key is not in the cache, it returns `undefined`.
*
* @param {T} key - The cache key
* @returns {T}
*/
getItem(key: T) {
if (!this.cache.has(key)) {
return;
}
const data = this.cache.get(key) as DataType<T>;
this.cache.delete(key);
this.cache.set(key, data);
return data.value;
}
/*
* Deletes item and returns true if the item existed in the storage.
* Returns false if the element doesn't exist.
*
* @param {T} key - The cache key
* @returns {boolean}
*/
removeItem(key: T) {
return this.cache.delete(key);
}
/*
* Makes item persistent, i.e the item can no longer be automatically evicted.
*
* @param {T} key - The cache key
* @returns {void}
*/
setPersistent(key: T) {
if (this.cache.has(key)) {
(this.cache.get(key) as DataType<T>).persistent = true;
}
}
/*
* Makes item no longer a persistent item if it was one.
*
* @param {T} key - The cache key
* @returns {void}
*/
removePersistent(key: T) {
if (this.cache.has(key)) {
(this.cache.get(key) as DataType<T>).persistent = false;
}
}
/*
* Makes item persistent if it was not yet, or otherwise undo the persistent flag.
*
* @param {T} key - The cache key
* @returns {void}
*/
togglePersistent(key: T) {
if (this.cache.has(key)) {
const data = this.cache.get(key) as DataType<T>;
data.persistent = !data.persistent;
}
}
/*
* Returns an Array based in the current cache with each key-value pair sorted by least-recently-used.
*
* @returns {T[][]}
*/
toArray() {
return Array.from(this.cache.entries()).reduce((acc, [key, item]) => {
acc.push([key, item.value])
return acc;
}, [] as T[][]);
}
}
| 22.248619 | 107 | 0.578594 | 93 | 12 | 0 | 11 | 7 | 4 | 1 | 0 | 3 | 2 | 9 | 5.416667 | 1,169 | 0.019675 | 0.005988 | 0.003422 | 0.001711 | 0.007699 | 0 | 0.088235 | 0.237367 | type DataType<T> = {
persistent,
value,
};
export default class Dadado<T> {
capacity;
private cache;
/*
* @param {number} capacity - Defines the maximum of items that can be in the cache
*/
constructor(capacity) {
if (!Number.isInteger(capacity)) {
throw Error('Expected an integer number');
}
if (Math.sign(capacity) <= 0) {
throw Error('Expected a positive number greater or equal to 1');
}
this.capacity = capacity;
this.cache = new Map();
}
/*
* Returns the cache size.
*
* @returns {number}
*/
size() {
return this.cache.size;
}
/*
* Removes all elements from the cache.
*
* @returns {void}
*/
clear() {
this.cache.clear();
}
/*
* Checks if the given key exist within the cache.
*
* @param {T} key - The cache key
* @returns {boolean}
*/
contains(key) {
return this.cache.has(key);
}
/*
* Adds the key-value pair to the cache if the key is not in the cache yet.
* Otherwise, if the key exists, updates the value of the key.
* In case the current number of keys exceeds the `capacity`, then it evicts the least recently used key.
*
* @param {T} key - The cache key
* @param {T} value - The value associated with the key
* @returns {boolean}
*/
setItem(key, value) {
if (this.cache.has(key)) {
const data = this.cache.get(key) as DataType<T>;
this.cache.delete(key);
data.value = value;
this.cache.set(key, data);
} else {
this.cache.set(key, {
value,
persistent: false
});
}
if (this.cache.size > this.capacity) {
const keys = this.cache.keys();
let wasDeleted = false;
if (!this.cache.size) {
return false;
}
while (!wasDeleted && this.cache.size) {
const key = keys.next().value;
const item = this.cache.get(key as T) as DataType<T>;
if (!item.persistent) {
wasDeleted = true;
this.cache.delete(key as T);
}
}
}
if (!this.cache.has(key)) {
return false;
}
return true;
}
/*
* Retrieves the value associated with the given key.
* If the key is not in the cache, it returns `undefined`.
*
* @param {T} key - The cache key
* @returns {T}
*/
getItem(key) {
if (!this.cache.has(key)) {
return;
}
const data = this.cache.get(key) as DataType<T>;
this.cache.delete(key);
this.cache.set(key, data);
return data.value;
}
/*
* Deletes item and returns true if the item existed in the storage.
* Returns false if the element doesn't exist.
*
* @param {T} key - The cache key
* @returns {boolean}
*/
removeItem(key) {
return this.cache.delete(key);
}
/*
* Makes item persistent, i.e the item can no longer be automatically evicted.
*
* @param {T} key - The cache key
* @returns {void}
*/
setPersistent(key) {
if (this.cache.has(key)) {
(this.cache.get(key) as DataType<T>).persistent = true;
}
}
/*
* Makes item no longer a persistent item if it was one.
*
* @param {T} key - The cache key
* @returns {void}
*/
removePersistent(key) {
if (this.cache.has(key)) {
(this.cache.get(key) as DataType<T>).persistent = false;
}
}
/*
* Makes item persistent if it was not yet, or otherwise undo the persistent flag.
*
* @param {T} key - The cache key
* @returns {void}
*/
togglePersistent(key) {
if (this.cache.has(key)) {
const data = this.cache.get(key) as DataType<T>;
data.persistent = !data.persistent;
}
}
/*
* Returns an Array based in the current cache with each key-value pair sorted by least-recently-used.
*
* @returns {T[][]}
*/
toArray() {
return Array.from(this.cache.entries()).reduce((acc, [key, item]) => {
acc.push([key, item.value])
return acc;
}, [] as T[][]);
}
}
|
1f34faf92f5fee669c5ca22bef34054f606f4019 | 21,942 | ts | TypeScript | src/index.ts | dfhoughton/list-matcher-js | 97a2448dd0e11c3fa26c2a7aa1f4fead64f65232 | [
"MIT"
] | 8 | 2022-02-14T14:03:35.000Z | 2022-02-27T22:41:25.000Z | src/index.ts | dfhoughton/list-matcher-js | 97a2448dd0e11c3fa26c2a7aa1f4fead64f65232 | [
"MIT"
] | null | null | null | src/index.ts | dfhoughton/list-matcher-js | 97a2448dd0e11c3fa26c2a7aa1f4fead64f65232 | [
"MIT"
] | null | null | null | // Copyright (c) David F. Houghton. All rights reserved. Licensed under the MIT license.
/**
* A library for making non-backtracking regular expressions from lists of phrases.
*
* @remarks
* The chief export of this library is {@link regex}. In addition there is the function
* {@link qw}, which makes it slightly easier to make lists of phrases to give to {@link regex}.
*
* This library also provides polyfills for various String.prototype functions for javascript engines
* that don't yet implement them. These are `String.prototype.repeat`, `String.prototype.includes`,
* `String.prototype.codePointAt`, and `String.prototype.fromCodePoint`. All polyfills were borrowed from
* {@link https://developer.mozilla.org|MDN}.
*
* Some regular expression features, in particular {@link https://caniuse.com/js-regexp-lookbehind|lookbehinds}, and
* {@link https://caniuse.com/mdn-javascript_builtins_regexp_property_escapes|property escapes}, are used to
* discover word boundaries in strings with code points above the ASCII range. These cannot be polyfilled,
* so marking word boundaries will not work on certain browsers.
*
* @packageDocumentation
*/
/**
* Options you can pass to {@link regex}.
*
* @export
* @typedef {ListMatcherOptions}
*/
export type ListMatcherOptions = {
bound?: boolean
capture?: boolean
normalizeWhitespace?: boolean
flags?: string
substitutions?: Record<string, string>
}
/**
* Generates a regular expression matching a list of strings.
*
* @example
* ```ts
* regex(qw('cat camel coulomb dog e f g h i'))
* => /(?:c(?:a(?:mel|t)|oulomb)|dog|[e-i])/
*
* // telephone numbers
* regex(['+## #### ######b', 'b###-####b', '(###) ###-####b'],{substitutions: {'b': '\\b', '#': '\\d'}})
* => /(?:\(\d{3}\) \d{3}-|\+\d\d \d{4} \d\d|\b\d{3}-)\d{4}\b/
* ```
*
* @param {string[]} words - phrases to match
* @param {ListMatcherOptions} [opts={}] - flags and directives for how to construct the expression
* @returns {RegExp} regular expression matching `words`
*/
export function regex(words: string[], opts: ListMatcherOptions = {}): RegExp {
words = [...words]
const options = adjustOptions(words, opts)
const slices = toSlices(words, options)
let rx = condense(slices, options)
if (options.capture) rx = `(${rx})`
return new RegExp(rx, flags(options))
}
/**
* Turns a string into an array of non-empty strings.
*
* @param {string} s - the string to split
* @param {(string | RegExp)} [splitter=/\s+/] - the expression used to split `s`
* @returns {string[]} the non-empty pieces of `s` after splitting
*/
export function qw(s: string, splitter: string | RegExp = /\s+/): string[] {
return s.split(splitter).filter((p) => p)
}
type Opts = {
bound: boolean
capture: boolean
normalizeWhitespace: boolean
subtitutions?: Record<number, string>
global: boolean
caseInsensitive: boolean
unicode: boolean
sticky: boolean
multiline: boolean
dotall: boolean
}
// the block from -1 to -127 is reserved for special substitutions like this
const SPECIAL_CODE_POINTS = {
whiteSpace: -1,
asciiBoundary: -2,
unicodeLeftBoundary: -3,
unicodeRightBoundary: -4,
} as const
const CHAR_CLASS_META = '-\\]^'.split('').map((c) => c.codePointAt(0))
const META = '^$+*?.|()[{\\'.split('').map((c) => c.codePointAt(0))
type Slice = {
codePoints: number[]
start: number
end: number
}
// convert options back into the flags that RegExp supports
function flags(options: Opts): string {
const ar = []
if (options.global) ar.push('g')
if (options.caseInsensitive) ar.push('i')
if (options.multiline) ar.push('m')
if (options.dotall) ar.push('s')
if (options.unicode) ar.push('u')
if (options.sticky) ar.push('y')
return ar.join('')
}
// adjust options to those relevant to internal operations
// normalize words by deduping, normalizing case, etc.
function adjustOptions(words: string[], opts: ListMatcherOptions): Opts {
const flags = opts.flags || ''
const options: Opts = {
bound: !!opts.bound,
capture: !!opts.capture,
normalizeWhitespace: !!opts.normalizeWhitespace,
global: flags.includes('g'),
caseInsensitive: flags.includes('i'),
unicode: flags.includes('u'),
multiline: flags.includes('m'),
dotall: flags.includes('s'),
sticky: flags.includes('y'),
}
const doSubstitutions = prepareSubstitutions(opts, options, words)
const ignore = options.subtitutions ? Object.keys(options.subtitutions).map((s) => Number(s)) : []
const seen = new Set()
const newWords: string[] = []
for (let i = 0; i < words.length; i++) {
let w = doSubstitutions(words[i])
if (seen.has(w)) continue
seen.add(w)
if (w.length === 0) continue
if (!options.unicode) {
for (let j = 0; j < w.length; j++) {
const c = w.codePointAt(j)
if (c && ignore.includes(c)) continue
if (c === undefined || c > 127) {
options.unicode = true
break
}
}
}
if (options.normalizeWhitespace) {
let w2 = w.trim().replace(/\s+/g, ' ')
if (w2.length === 0) continue
if (w2 !== w) {
if (seen.has(w2)) continue
seen.add(w2)
w = w2
}
}
if (options.caseInsensitive) {
let w2 = w.toLowerCase()
if (w2 !== w) {
if (seen.has(w2)) continue
seen.add(w2)
w = w2
}
}
newWords.push(w)
}
// so the same set of words, however ordered, always produces the same regex for a given set of options
newWords.sort()
words.length = 0
words.unshift(...newWords)
return options
}
function condense(slices: Slice[], opts: Opts): string {
if (slices.length === 0) return '(?!)'
const [slcs1, prefix] = extractPrefix(slices, opts)
// if this was everything, just return the prefix
if (slcs1.length === 1 && sliceLength(slcs1[0]) === 0) return prefix
const [slcs2, suffix] = extractSuffix(slcs1, opts)
const slcs3 = slcs2.filter((sl) => sliceLength(sl))
const anyOptional = slcs3.length < slices.length ? '?' : ''
// separate single characters and sequences
const chars: Slice[] = []
const sequences: Slice[] = []
for (const sl of slcs3) {
;(sliceLength(sl) === 1 ? chars : sequences).push(sl)
}
let middle
if (sequences.length) {
const parts = groupByFirst(sequences).map((slcs) => condense(slcs, opts))
parts.sort()
if (chars.length)
parts.push(
charClass(
chars.map((sl) => firstChar(sl)!),
true,
opts,
),
)
middle = `(?:${parts.join('|')})`
} else {
// if we've gotten here we necessarily have some chars
middle = charClass(
chars.map((sl) => firstChar(sl)!),
false,
opts,
)
}
return `${prefix}${middle}${anyOptional}${suffix}`
}
// groups slices by first character
function groupByFirst(slices: Slice[]): Slice[][] {
const groups: Record<string, Slice[]> = {}
for (const sl of slices) {
const ar = (groups[firstChar(sl)!] ??= [])
ar.push(sl)
}
return Object.values(groups)
}
// extracts common prefix of all slices, if any
function extractPrefix(slices: Slice[], options: Opts): [Slice[], string] {
if (slices.length === 1) {
const sl = slices[0]
const prefix = sl.codePoints.slice(sl.start, sl.end)
sl.start = sl.end
return [[sl], reduceDuplicates(prefix, options)]
}
let c = firstChar(slices[0])
const prefix = []
outer: while (c) {
for (const sl of slices) {
if (sliceLength(sl) === 0) break outer
if (firstChar(sl) !== c) break outer
}
for (const sl of slices) sl.start++
prefix.push(c)
c = firstChar(slices[0])
}
return [slices, reduceDuplicates(prefix, options)]
}
// extracts common suffix of all slices, if any
function extractSuffix(slices: Slice[], options: Opts): [Slice[], string] {
if (slices.length === 1) {
const sl = slices[0]
const suffix = sl.codePoints.slice(sl.start, sl.end)
sl.start = sl.end
return [[sl], reduceDuplicates(suffix, options)]
}
let c = lastChar(slices[0])
const suffix = []
outer: while (c) {
for (const sl of slices) {
if (sliceLength(sl) === 0) break outer
if (lastChar(sl) !== c) break outer
}
for (const sl of slices) sl.end--
suffix.push(c)
c = lastChar(slices[0])
}
return [slices, reduceDuplicates(suffix.reverse(), options)]
}
// look for repeating characters and maybe use a repetition count -- a{5}, e.g.
function reduceDuplicates(sequence: number[], options: Opts): string {
if (sequence.length === 0) return ''
let dupCount = 1
let unit = sequence[0]
let reduced = ''
for (let i = 1; i < sequence.length; i++) {
const p = sequence[i]
if (p === unit) {
dupCount += 1
} else {
reduced += maybeReduce(dupCount, toAtom(unit, false, options))
unit = p
dupCount = 1
}
}
reduced += maybeReduce(dupCount, toAtom(unit, false, options))
return reduced
}
// converts aaaaa into a{5}, etc.
// cannot return a pattern longer than the input sequence
function maybeReduce(dc: number, unit: string): string {
return dc === 1 ? unit : dc * unit.length > unit.length + 3 ? `${unit}{${dc}}` : unit.repeat(dc)
}
function firstChar(slice: Slice): number | undefined {
return sliceLength(slice) > 0 ? slice.codePoints[slice.start] : undefined
}
function lastChar(slice: Slice): number | undefined {
return sliceLength(slice) > 0 ? slice.codePoints[slice.end - 1] : undefined
}
function sliceLength(slice: Slice) {
return slice.end - slice.start
}
function prepareSubstitutions(opts: ListMatcherOptions, options: Opts, words: string[]): (w: string) => string {
if (!opts.substitutions) return (w) => w
const count = Object.keys(opts.substitutions).length
if (count) {
const unused = getUnusedCharacters(count, words)
const substitutions: Record<number, string> = {}
const replacementHash: Record<string, string> = {}
for (const [from, to] of Object.entries(opts.substitutions)) {
const [cp, char] = unused.shift()!
replacementHash[from] = char
substitutions[cp] = to
}
options.subtitutions = substitutions
const rx = regex(Object.keys(opts.substitutions), { flags: 'g' })
return (w) => w.replace(rx, (s) => replacementHash[s]!)
} else {
return (w) => w
}
}
// get characters and codepoints that can be used for substitution
function getUnusedCharacters(count: number, words: string[]): [number, string][] {
if (count === 0) return []
const found: (undefined | boolean)[] = []
for (const w of words) {
for (let i = 0; i < w.length; i++) {
const n = w.codePointAt(i)
if (n !== undefined) found[n] = true
}
}
const unused: [number, string][] = []
let i = 128 // skip ascii to avoid metacharacters and common characters
while (unused.length < count) {
if (!found[i]) {
const c = String.fromCodePoint(i)
if (c.toLowerCase() === c && !/\s/.test(c)) unused.push([i, c])
}
i++
}
return unused
}
// converts remaining characters to "codepoints" (real codepoints and special negative ones)
// adds boundaries
// fixes substitution map so its keys are negative
function toSlices(words: string[], options: Opts): Slice[] {
const substitutionCodepoints = Object.keys(options.subtitutions || {}).map((n) => Number(n))
const slices = words.map((w) => {
// to accelerate other code, we store subtitution codepoints as negative numbers
let codePoints = w
.split('')
.map((c) => c.codePointAt(0) || 0)
.map((c) => (substitutionCodepoints.includes(c) ? -c : c))
if (options.normalizeWhitespace) codePoints = codePoints.map((c) => (c === 32 ? SPECIAL_CODE_POINTS.whiteSpace : c))
if (options.bound) {
if (options.unicode) {
if (codePoints[0] > 0 && /^[\p{L}\p{N}_]/u.test(w)) codePoints.unshift(SPECIAL_CODE_POINTS.unicodeLeftBoundary)
if (codePoints[codePoints.length - 1] > 0 && /[\p{L}\p{N}_]$/u.test(w))
codePoints.push(SPECIAL_CODE_POINTS.unicodeRightBoundary)
} else {
if (codePoints[0] > 0 && /^\w/.test(w)) codePoints.unshift(SPECIAL_CODE_POINTS.asciiBoundary)
if (codePoints[codePoints.length - 1] > 0 && /\w$/.test(w)) codePoints.push(SPECIAL_CODE_POINTS.asciiBoundary)
}
}
return { codePoints, start: 0, end: codePoints.length }
})
if (options.subtitutions) {
Object.entries(options.subtitutions).forEach(([k, v]) => {
options.subtitutions![-Number(k)] = v
delete options.subtitutions![Number(k)]
})
}
return slices
}
// take a collection of code points and try to make a character class expressions
// this might be impossible -- some things represented as code points are actually more complex
// if we cannot make a character class, it is useful to know whether this sub-expression is to be embedded in a list of alternates
function charClass(codePoints: number[], embedded: boolean, opts: Opts): string {
codePoints.sort((a, b) => a - b)
if (codePoints[0] < 0) {
// some of these things can't go in a character class
const problems = []
while (codePoints.length) {
if (codePoints[0] >= 0) break
problems.push(codePoints.shift()!)
}
const parts = problems.map((c) => toAtom(c, false, opts))
if (codePoints.length > 1) {
const cc = safeCharClass(codePoints, opts)
if (cc.length < codePoints.length * 2 - 1) {
parts.push(cc)
} else {
parts.unshift(...codePoints.map((c) => toAtom(c, false)))
}
} else {
parts.unshift(...codePoints.map((c) => toAtom(c, false)))
}
const middle = parts.join('|')
return embedded ? middle : `(?:${middle})`
} else {
return safeCharClass(codePoints, opts)
}
}
// make a character class expression
// at this point the code points should be filtered to just those that can live in a character class
function safeCharClass(codePoints: number[], opts: Opts): string {
if (codePoints.length === 1) return toAtom(codePoints[0], false)
let skipping = false
let start = null
let current = -2
let chars = ''
for (const n of codePoints) {
if (n == current + 1) {
skipping = true
} else {
if (skipping) {
if (current > start! + 1) chars += '-'
chars += toAtom(current, true)
}
start = n
chars += toAtom(start, true)
skipping = false
}
current = n
}
if (skipping) {
if (current > start! + 1) chars += '-'
chars += toAtom(current, true)
}
// condense a few of the more common character classes
// we might extend this list in the future
if (opts.caseInsensitive) {
chars = chars.replace(/0-9(.*)_(.*)a-z/, '\\w$1$2')
} else {
chars = chars.replace(/0-9(.*)A-Z(.*)_(.*)a-z/, '\\w$1$2$3')
}
chars = chars.replace('0-9', '\\d')
return /^\\\w$/.test(chars) ? chars : `[${chars}]`
}
// convert a code point back into a fragment of a regular expression
function toAtom(codePoint: number, inCharClass: boolean, options?: Opts): string {
if (codePoint < 0 && codePoint > -127) {
// substitutions are < -127
switch (codePoint) {
case SPECIAL_CODE_POINTS.asciiBoundary:
return '\\b'
case SPECIAL_CODE_POINTS.unicodeLeftBoundary:
return '(?<![\\p{L}\\p{N}_])'
case SPECIAL_CODE_POINTS.unicodeRightBoundary:
return '(?![\\p{L}\\p{N}_])'
case SPECIAL_CODE_POINTS.whiteSpace:
return '\\s+'
default:
throw new Error(`unexpected code point: ${codePoint}`)
}
} else {
if (options?.subtitutions) {
const rx = options.subtitutions[codePoint]
if (rx !== undefined) return rx
}
return quotemeta(codePoint, inCharClass)
}
}
// escape regular expression meta-characters as necessary given the context
// character classes have different meta-characters
function quotemeta(codePoint: number, inCharClass: boolean): string {
if (codePoint < 14) {
if (codePoint > 8) {
if (codePoint === 9) return '\\t'
if (codePoint === 10) return '\\n'
if (codePoint === 11) return '\\v'
if (codePoint === 12) return '\\f'
if (codePoint === 13) return '\\r'
} else if (codePoint === 0) {
return '\\0'
}
return String.fromCodePoint(codePoint)
}
const c = String.fromCodePoint(codePoint)
if (codePoint > 124) return c
const escape = (inCharClass ? CHAR_CLASS_META : META).includes(codePoint)
return escape ? '\\' + c : c
}
/**
* Patch IE to provide String.prototype.repeat, String.prototype.includes, String.codePointAt, and String.fromCodePoint
*/
/*! https://mths.be/codepointat v0.2.0 by @mathias */
// @ts-ignore
if (!String.prototype.codePointAt) {
;(function () {
'use strict' // needed to support `apply`/`call` with `undefined`/`null`
var defineProperty = (function () {
// IE 8 only supports `Object.defineProperty` on DOM elements
try {
var object = {}
var $defineProperty = Object.defineProperty
// @ts-ignore
var result = $defineProperty(object, object, object) && $defineProperty
} catch (error) {}
// @ts-ignore
return result
})()
// @ts-ignore
var codePointAt = function (position) {
// @ts-ignore
if (this == null) {
throw TypeError()
}
// @ts-ignore
var string = String(this)
var size = string.length
// `ToInteger`
var index = position ? Number(position) : 0
if (index != index) {
// better `isNaN`
index = 0
}
// Account for out-of-bounds indices:
if (index < 0 || index >= size) {
return undefined
}
// Get the first code unit
var first = string.charCodeAt(index)
var second
if (
// check if it’s the start of a surrogate pair
first >= 0xd800 &&
first <= 0xdbff && // high surrogate
size > index + 1 // there is a next code unit
) {
second = string.charCodeAt(index + 1)
if (second >= 0xdc00 && second <= 0xdfff) {
// low surrogate
// https://mathiasbynens.be/notes/javascript-encoding#surrogate-formulae
return (first - 0xd800) * 0x400 + second - 0xdc00 + 0x10000
}
}
return first
}
if (defineProperty) {
defineProperty(String.prototype, 'codePointAt', {
value: codePointAt,
configurable: true,
writable: true,
})
} else {
String.prototype.codePointAt = codePointAt
}
})()
}
/*! https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/fromCodePoint */
if (!String.fromCodePoint) {
;(function (stringFromCharCode) {
// @ts-ignore
var fromCodePoint = function (_) {
var codeUnits = [],
codeLen = 0,
result = ''
for (var index = 0, len = arguments.length; index !== len; ++index) {
var codePoint = +arguments[index]
// correctly handles all cases including `NaN`, `-Infinity`, `+Infinity`
// The surrounding `!(...)` is required to correctly handle `NaN` cases
// The (codePoint>>>0) === codePoint clause handles decimals and negatives
if (!(codePoint < 0x10ffff && codePoint >>> 0 === codePoint))
throw RangeError('Invalid code point: ' + codePoint)
if (codePoint <= 0xffff) {
// BMP code point
codeLen = codeUnits.push(codePoint)
} else {
// Astral code point; split in surrogate halves
// https://mathiasbynens.be/notes/javascript-encoding#surrogate-formulae
codePoint -= 0x10000
codeLen = codeUnits.push(
(codePoint >> 10) + 0xd800, // highSurrogate
(codePoint % 0x400) + 0xdc00, // lowSurrogate
)
}
if (codeLen >= 0x3fff) {
result += stringFromCharCode.apply(null, codeUnits)
codeUnits.length = 0
}
}
return result + stringFromCharCode.apply(null, codeUnits)
}
try {
// IE 8 only supports `Object.defineProperty` on DOM elements
Object.defineProperty(String, 'fromCodePoint', {
value: fromCodePoint,
configurable: true,
writable: true,
})
} catch (e) {
String.fromCodePoint = fromCodePoint
}
})(String.fromCharCode)
}
/*! https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/includes */
if (!String.prototype.includes) {
String.prototype.includes = function (search, start) {
'use strict'
// @ts-ignore
if (search instanceof RegExp) {
throw TypeError('first argument must not be a RegExp')
}
if (start === undefined) {
start = 0
}
return this.indexOf(search, start) !== -1
}
}
/*! https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/repeat */
if (!String.prototype.repeat) {
String.prototype.repeat = function (count) {
'use strict'
if (this == null) throw new TypeError("can't convert " + this + ' to object')
var str = '' + this
// To convert string to integer.
count = +count
// Check NaN
if (count != count) count = 0
if (count < 0) throw new RangeError('repeat count must be non-negative')
if (count == Infinity) throw new RangeError('repeat count must be less than infinity')
count = Math.floor(count)
if (str.length == 0 || count == 0) return ''
// Ensuring count is a 31-bit integer allows us to heavily optimize the
// main part. But anyway, most current (August 2014) browsers can't handle
// strings 1 << 28 chars or longer, so:
if (str.length * count >= 1 << 28) throw new RangeError('repeat count must not overflow maximum string size')
var maxCount = str.length * count
count = Math.floor(Math.log(count) / Math.log(2))
while (count) {
str += str
count--
}
str += str.substring(0, maxCount - str.length)
return str
}
}
| 33.245455 | 130 | 0.624784 | 505 | 49 | 0 | 67 | 87 | 18 | 23 | 0 | 64 | 3 | 2 | 10.367347 | 6,307 | 0.018392 | 0.013794 | 0.002854 | 0.000476 | 0.000317 | 0 | 0.289593 | 0.264388 | // Copyright (c) David F. Houghton. All rights reserved. Licensed under the MIT license.
/**
* A library for making non-backtracking regular expressions from lists of phrases.
*
* @remarks
* The chief export of this library is {@link regex}. In addition there is the function
* {@link qw}, which makes it slightly easier to make lists of phrases to give to {@link regex}.
*
* This library also provides polyfills for various String.prototype functions for javascript engines
* that don't yet implement them. These are `String.prototype.repeat`, `String.prototype.includes`,
* `String.prototype.codePointAt`, and `String.prototype.fromCodePoint`. All polyfills were borrowed from
* {@link https://developer.mozilla.org|MDN}.
*
* Some regular expression features, in particular {@link https://caniuse.com/js-regexp-lookbehind|lookbehinds}, and
* {@link https://caniuse.com/mdn-javascript_builtins_regexp_property_escapes|property escapes}, are used to
* discover word boundaries in strings with code points above the ASCII range. These cannot be polyfilled,
* so marking word boundaries will not work on certain browsers.
*
* @packageDocumentation
*/
/**
* Options you can pass to {@link regex}.
*
* @export
* @typedef {ListMatcherOptions}
*/
export type ListMatcherOptions = {
bound?
capture?
normalizeWhitespace?
flags?
substitutions?
}
/**
* Generates a regular expression matching a list of strings.
*
* @example
* ```ts
* regex(qw('cat camel coulomb dog e f g h i'))
* => /(?:c(?:a(?:mel|t)|oulomb)|dog|[e-i])/
*
* // telephone numbers
* regex(['+## #### ######b', 'b###-####b', '(###) ###-####b'],{substitutions: {'b': '\\b', '#': '\\d'}})
* => /(?:\(\d{3}\) \d{3}-|\+\d\d \d{4} \d\d|\b\d{3}-)\d{4}\b/
* ```
*
* @param {string[]} words - phrases to match
* @param {ListMatcherOptions} [opts={}] - flags and directives for how to construct the expression
* @returns {RegExp} regular expression matching `words`
*/
export /* Example usages of 'regex' are shown below:
regex(Object.keys(opts.substitutions), { flags: 'g' });
*/
function regex(words, opts = {}) {
words = [...words]
const options = adjustOptions(words, opts)
const slices = toSlices(words, options)
let rx = condense(slices, options)
if (options.capture) rx = `(${rx})`
return new RegExp(rx, flags(options))
}
/**
* Turns a string into an array of non-empty strings.
*
* @param {string} s - the string to split
* @param {(string | RegExp)} [splitter=/\s+/] - the expression used to split `s`
* @returns {string[]} the non-empty pieces of `s` after splitting
*/
export function qw(s, splitter = /\s+/) {
return s.split(splitter).filter((p) => p)
}
type Opts = {
bound
capture
normalizeWhitespace
subtitutions?
global
caseInsensitive
unicode
sticky
multiline
dotall
}
// the block from -1 to -127 is reserved for special substitutions like this
const SPECIAL_CODE_POINTS = {
whiteSpace: -1,
asciiBoundary: -2,
unicodeLeftBoundary: -3,
unicodeRightBoundary: -4,
} as const
const CHAR_CLASS_META = '-\\]^'.split('').map((c) => c.codePointAt(0))
const META = '^$+*?.|()[{\\'.split('').map((c) => c.codePointAt(0))
type Slice = {
codePoints
start
end
}
// convert options back into the flags that RegExp supports
/* Example usages of 'flags' are shown below:
;
new RegExp(rx, flags(options));
var flags = opts.flags || '';
opts.flags || '';
flags.includes('g');
flags.includes('i');
flags.includes('u');
flags.includes('m');
flags.includes('s');
flags.includes('y');
*/
function flags(options) {
const ar = []
if (options.global) ar.push('g')
if (options.caseInsensitive) ar.push('i')
if (options.multiline) ar.push('m')
if (options.dotall) ar.push('s')
if (options.unicode) ar.push('u')
if (options.sticky) ar.push('y')
return ar.join('')
}
// adjust options to those relevant to internal operations
// normalize words by deduping, normalizing case, etc.
/* Example usages of 'adjustOptions' are shown below:
adjustOptions(words, opts);
*/
function adjustOptions(words, opts) {
const flags = opts.flags || ''
const options = {
bound: !!opts.bound,
capture: !!opts.capture,
normalizeWhitespace: !!opts.normalizeWhitespace,
global: flags.includes('g'),
caseInsensitive: flags.includes('i'),
unicode: flags.includes('u'),
multiline: flags.includes('m'),
dotall: flags.includes('s'),
sticky: flags.includes('y'),
}
const doSubstitutions = prepareSubstitutions(opts, options, words)
const ignore = options.subtitutions ? Object.keys(options.subtitutions).map((s) => Number(s)) : []
const seen = new Set()
const newWords = []
for (let i = 0; i < words.length; i++) {
let w = doSubstitutions(words[i])
if (seen.has(w)) continue
seen.add(w)
if (w.length === 0) continue
if (!options.unicode) {
for (let j = 0; j < w.length; j++) {
const c = w.codePointAt(j)
if (c && ignore.includes(c)) continue
if (c === undefined || c > 127) {
options.unicode = true
break
}
}
}
if (options.normalizeWhitespace) {
let w2 = w.trim().replace(/\s+/g, ' ')
if (w2.length === 0) continue
if (w2 !== w) {
if (seen.has(w2)) continue
seen.add(w2)
w = w2
}
}
if (options.caseInsensitive) {
let w2 = w.toLowerCase()
if (w2 !== w) {
if (seen.has(w2)) continue
seen.add(w2)
w = w2
}
}
newWords.push(w)
}
// so the same set of words, however ordered, always produces the same regex for a given set of options
newWords.sort()
words.length = 0
words.unshift(...newWords)
return options
}
/* Example usages of 'condense' are shown below:
condense(slices, options);
condense(slcs, opts);
*/
function condense(slices, opts) {
if (slices.length === 0) return '(?!)'
const [slcs1, prefix] = extractPrefix(slices, opts)
// if this was everything, just return the prefix
if (slcs1.length === 1 && sliceLength(slcs1[0]) === 0) return prefix
const [slcs2, suffix] = extractSuffix(slcs1, opts)
const slcs3 = slcs2.filter((sl) => sliceLength(sl))
const anyOptional = slcs3.length < slices.length ? '?' : ''
// separate single characters and sequences
const chars = []
const sequences = []
for (const sl of slcs3) {
;(sliceLength(sl) === 1 ? chars : sequences).push(sl)
}
let middle
if (sequences.length) {
const parts = groupByFirst(sequences).map((slcs) => condense(slcs, opts))
parts.sort()
if (chars.length)
parts.push(
charClass(
chars.map((sl) => firstChar(sl)!),
true,
opts,
),
)
middle = `(?:${parts.join('|')})`
} else {
// if we've gotten here we necessarily have some chars
middle = charClass(
chars.map((sl) => firstChar(sl)!),
false,
opts,
)
}
return `${prefix}${middle}${anyOptional}${suffix}`
}
// groups slices by first character
/* Example usages of 'groupByFirst' are shown below:
groupByFirst(sequences).map((slcs) => condense(slcs, opts));
*/
function groupByFirst(slices) {
const groups = {}
for (const sl of slices) {
const ar = (groups[firstChar(sl)!] ??= [])
ar.push(sl)
}
return Object.values(groups)
}
// extracts common prefix of all slices, if any
/* Example usages of 'extractPrefix' are shown below:
extractPrefix(slices, opts);
*/
function extractPrefix(slices, options) {
if (slices.length === 1) {
const sl = slices[0]
const prefix = sl.codePoints.slice(sl.start, sl.end)
sl.start = sl.end
return [[sl], reduceDuplicates(prefix, options)]
}
let c = firstChar(slices[0])
const prefix = []
outer: while (c) {
for (const sl of slices) {
if (sliceLength(sl) === 0) break outer
if (firstChar(sl) !== c) break outer
}
for (const sl of slices) sl.start++
prefix.push(c)
c = firstChar(slices[0])
}
return [slices, reduceDuplicates(prefix, options)]
}
// extracts common suffix of all slices, if any
/* Example usages of 'extractSuffix' are shown below:
extractSuffix(slcs1, opts);
*/
function extractSuffix(slices, options) {
if (slices.length === 1) {
const sl = slices[0]
const suffix = sl.codePoints.slice(sl.start, sl.end)
sl.start = sl.end
return [[sl], reduceDuplicates(suffix, options)]
}
let c = lastChar(slices[0])
const suffix = []
outer: while (c) {
for (const sl of slices) {
if (sliceLength(sl) === 0) break outer
if (lastChar(sl) !== c) break outer
}
for (const sl of slices) sl.end--
suffix.push(c)
c = lastChar(slices[0])
}
return [slices, reduceDuplicates(suffix.reverse(), options)]
}
// look for repeating characters and maybe use a repetition count -- a{5}, e.g.
/* Example usages of 'reduceDuplicates' are shown below:
reduceDuplicates(prefix, options);
reduceDuplicates(suffix, options);
reduceDuplicates(suffix.reverse(), options);
*/
function reduceDuplicates(sequence, options) {
if (sequence.length === 0) return ''
let dupCount = 1
let unit = sequence[0]
let reduced = ''
for (let i = 1; i < sequence.length; i++) {
const p = sequence[i]
if (p === unit) {
dupCount += 1
} else {
reduced += maybeReduce(dupCount, toAtom(unit, false, options))
unit = p
dupCount = 1
}
}
reduced += maybeReduce(dupCount, toAtom(unit, false, options))
return reduced
}
// converts aaaaa into a{5}, etc.
// cannot return a pattern longer than the input sequence
/* Example usages of 'maybeReduce' are shown below:
reduced += maybeReduce(dupCount, toAtom(unit, false, options));
*/
function maybeReduce(dc, unit) {
return dc === 1 ? unit : dc * unit.length > unit.length + 3 ? `${unit}{${dc}}` : unit.repeat(dc)
}
/* Example usages of 'firstChar' are shown below:
firstChar(sl);
firstChar(slices[0]);
firstChar(sl) !== c;
c = firstChar(slices[0]);
*/
function firstChar(slice) {
return sliceLength(slice) > 0 ? slice.codePoints[slice.start] : undefined
}
/* Example usages of 'lastChar' are shown below:
lastChar(slices[0]);
lastChar(sl) !== c;
c = lastChar(slices[0]);
*/
function lastChar(slice) {
return sliceLength(slice) > 0 ? slice.codePoints[slice.end - 1] : undefined
}
/* Example usages of 'sliceLength' are shown below:
slcs1.length === 1 && sliceLength(slcs1[0]) === 0;
sliceLength(sl);
sliceLength(sl) === 1 ? chars : sequences;
sliceLength(sl) === 0;
sliceLength(slice) > 0 ? slice.codePoints[slice.start] : undefined;
sliceLength(slice) > 0 ? slice.codePoints[slice.end - 1] : undefined;
*/
function sliceLength(slice) {
return slice.end - slice.start
}
/* Example usages of 'prepareSubstitutions' are shown below:
prepareSubstitutions(opts, options, words);
*/
function prepareSubstitutions(opts, options, words) {
if (!opts.substitutions) return (w) => w
const count = Object.keys(opts.substitutions).length
if (count) {
const unused = getUnusedCharacters(count, words)
const substitutions = {}
const replacementHash = {}
for (const [from, to] of Object.entries(opts.substitutions)) {
const [cp, char] = unused.shift()!
replacementHash[from] = char
substitutions[cp] = to
}
options.subtitutions = substitutions
const rx = regex(Object.keys(opts.substitutions), { flags: 'g' })
return (w) => w.replace(rx, (s) => replacementHash[s]!)
} else {
return (w) => w
}
}
// get characters and codepoints that can be used for substitution
/* Example usages of 'getUnusedCharacters' are shown below:
getUnusedCharacters(count, words);
*/
function getUnusedCharacters(count, words) {
if (count === 0) return []
const found = []
for (const w of words) {
for (let i = 0; i < w.length; i++) {
const n = w.codePointAt(i)
if (n !== undefined) found[n] = true
}
}
const unused = []
let i = 128 // skip ascii to avoid metacharacters and common characters
while (unused.length < count) {
if (!found[i]) {
const c = String.fromCodePoint(i)
if (c.toLowerCase() === c && !/\s/.test(c)) unused.push([i, c])
}
i++
}
return unused
}
// converts remaining characters to "codepoints" (real codepoints and special negative ones)
// adds boundaries
// fixes substitution map so its keys are negative
/* Example usages of 'toSlices' are shown below:
toSlices(words, options);
*/
function toSlices(words, options) {
const substitutionCodepoints = Object.keys(options.subtitutions || {}).map((n) => Number(n))
const slices = words.map((w) => {
// to accelerate other code, we store subtitution codepoints as negative numbers
let codePoints = w
.split('')
.map((c) => c.codePointAt(0) || 0)
.map((c) => (substitutionCodepoints.includes(c) ? -c : c))
if (options.normalizeWhitespace) codePoints = codePoints.map((c) => (c === 32 ? SPECIAL_CODE_POINTS.whiteSpace : c))
if (options.bound) {
if (options.unicode) {
if (codePoints[0] > 0 && /^[\p{L}\p{N}_]/u.test(w)) codePoints.unshift(SPECIAL_CODE_POINTS.unicodeLeftBoundary)
if (codePoints[codePoints.length - 1] > 0 && /[\p{L}\p{N}_]$/u.test(w))
codePoints.push(SPECIAL_CODE_POINTS.unicodeRightBoundary)
} else {
if (codePoints[0] > 0 && /^\w/.test(w)) codePoints.unshift(SPECIAL_CODE_POINTS.asciiBoundary)
if (codePoints[codePoints.length - 1] > 0 && /\w$/.test(w)) codePoints.push(SPECIAL_CODE_POINTS.asciiBoundary)
}
}
return { codePoints, start: 0, end: codePoints.length }
})
if (options.subtitutions) {
Object.entries(options.subtitutions).forEach(([k, v]) => {
options.subtitutions![-Number(k)] = v
delete options.subtitutions![Number(k)]
})
}
return slices
}
// take a collection of code points and try to make a character class expressions
// this might be impossible -- some things represented as code points are actually more complex
// if we cannot make a character class, it is useful to know whether this sub-expression is to be embedded in a list of alternates
/* Example usages of 'charClass' are shown below:
parts.push(charClass(chars.map((sl) => firstChar(sl)!), true, opts));
// if we've gotten here we necessarily have some chars
middle = charClass(chars.map((sl) => firstChar(sl)!), false, opts);
*/
function charClass(codePoints, embedded, opts) {
codePoints.sort((a, b) => a - b)
if (codePoints[0] < 0) {
// some of these things can't go in a character class
const problems = []
while (codePoints.length) {
if (codePoints[0] >= 0) break
problems.push(codePoints.shift()!)
}
const parts = problems.map((c) => toAtom(c, false, opts))
if (codePoints.length > 1) {
const cc = safeCharClass(codePoints, opts)
if (cc.length < codePoints.length * 2 - 1) {
parts.push(cc)
} else {
parts.unshift(...codePoints.map((c) => toAtom(c, false)))
}
} else {
parts.unshift(...codePoints.map((c) => toAtom(c, false)))
}
const middle = parts.join('|')
return embedded ? middle : `(?:${middle})`
} else {
return safeCharClass(codePoints, opts)
}
}
// make a character class expression
// at this point the code points should be filtered to just those that can live in a character class
/* Example usages of 'safeCharClass' are shown below:
safeCharClass(codePoints, opts);
*/
function safeCharClass(codePoints, opts) {
if (codePoints.length === 1) return toAtom(codePoints[0], false)
let skipping = false
let start = null
let current = -2
let chars = ''
for (const n of codePoints) {
if (n == current + 1) {
skipping = true
} else {
if (skipping) {
if (current > start! + 1) chars += '-'
chars += toAtom(current, true)
}
start = n
chars += toAtom(start, true)
skipping = false
}
current = n
}
if (skipping) {
if (current > start! + 1) chars += '-'
chars += toAtom(current, true)
}
// condense a few of the more common character classes
// we might extend this list in the future
if (opts.caseInsensitive) {
chars = chars.replace(/0-9(.*)_(.*)a-z/, '\\w$1$2')
} else {
chars = chars.replace(/0-9(.*)A-Z(.*)_(.*)a-z/, '\\w$1$2$3')
}
chars = chars.replace('0-9', '\\d')
return /^\\\w$/.test(chars) ? chars : `[${chars}]`
}
// convert a code point back into a fragment of a regular expression
/* Example usages of 'toAtom' are shown below:
reduced += maybeReduce(dupCount, toAtom(unit, false, options));
toAtom(c, false, opts);
toAtom(c, false);
toAtom(codePoints[0], false);
chars += toAtom(current, true);
chars += toAtom(start, true);
*/
function toAtom(codePoint, inCharClass, options?) {
if (codePoint < 0 && codePoint > -127) {
// substitutions are < -127
switch (codePoint) {
case SPECIAL_CODE_POINTS.asciiBoundary:
return '\\b'
case SPECIAL_CODE_POINTS.unicodeLeftBoundary:
return '(?<![\\p{L}\\p{N}_])'
case SPECIAL_CODE_POINTS.unicodeRightBoundary:
return '(?![\\p{L}\\p{N}_])'
case SPECIAL_CODE_POINTS.whiteSpace:
return '\\s+'
default:
throw new Error(`unexpected code point: ${codePoint}`)
}
} else {
if (options?.subtitutions) {
const rx = options.subtitutions[codePoint]
if (rx !== undefined) return rx
}
return quotemeta(codePoint, inCharClass)
}
}
// escape regular expression meta-characters as necessary given the context
// character classes have different meta-characters
/* Example usages of 'quotemeta' are shown below:
quotemeta(codePoint, inCharClass);
*/
function quotemeta(codePoint, inCharClass) {
if (codePoint < 14) {
if (codePoint > 8) {
if (codePoint === 9) return '\\t'
if (codePoint === 10) return '\\n'
if (codePoint === 11) return '\\v'
if (codePoint === 12) return '\\f'
if (codePoint === 13) return '\\r'
} else if (codePoint === 0) {
return '\\0'
}
return String.fromCodePoint(codePoint)
}
const c = String.fromCodePoint(codePoint)
if (codePoint > 124) return c
const escape = (inCharClass ? CHAR_CLASS_META : META).includes(codePoint)
return escape ? '\\' + c : c
}
/**
* Patch IE to provide String.prototype.repeat, String.prototype.includes, String.codePointAt, and String.fromCodePoint
*/
/*! https://mths.be/codepointat v0.2.0 by @mathias */
// @ts-ignore
if (!String.prototype.codePointAt) {
;(function () {
'use strict' // needed to support `apply`/`call` with `undefined`/`null`
var defineProperty = (function () {
// IE 8 only supports `Object.defineProperty` on DOM elements
try {
var object = {}
var $defineProperty = Object.defineProperty
// @ts-ignore
var result = $defineProperty(object, object, object) && $defineProperty
} catch (error) {}
// @ts-ignore
return result
})()
// @ts-ignore
/* Example usages of 'codePointAt' are shown below:
c.codePointAt(0);
w.codePointAt(j);
w.codePointAt(i);
c.codePointAt(0) || 0;
!String.prototype.codePointAt;
;
String.prototype.codePointAt = codePointAt;
*/
var codePointAt = function (position) {
// @ts-ignore
if (this == null) {
throw TypeError()
}
// @ts-ignore
var string = String(this)
var size = string.length
// `ToInteger`
var index = position ? Number(position) : 0
if (index != index) {
// better `isNaN`
index = 0
}
// Account for out-of-bounds indices:
if (index < 0 || index >= size) {
return undefined
}
// Get the first code unit
var first = string.charCodeAt(index)
var second
if (
// check if it’s the start of a surrogate pair
first >= 0xd800 &&
first <= 0xdbff && // high surrogate
size > index + 1 // there is a next code unit
) {
second = string.charCodeAt(index + 1)
if (second >= 0xdc00 && second <= 0xdfff) {
// low surrogate
// https://mathiasbynens.be/notes/javascript-encoding#surrogate-formulae
return (first - 0xd800) * 0x400 + second - 0xdc00 + 0x10000
}
}
return first
}
if (defineProperty) {
defineProperty(String.prototype, 'codePointAt', {
value: codePointAt,
configurable: true,
writable: true,
})
} else {
String.prototype.codePointAt = codePointAt
}
})()
}
/*! https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/fromCodePoint */
if (!String.fromCodePoint) {
;(function (stringFromCharCode) {
// @ts-ignore
/* Example usages of 'fromCodePoint' are shown below:
String.fromCodePoint(i);
String.fromCodePoint(codePoint);
!String.fromCodePoint;
;
String.fromCodePoint = fromCodePoint;
*/
var fromCodePoint = function (_) {
var codeUnits = [],
codeLen = 0,
result = ''
for (var index = 0, len = arguments.length; index !== len; ++index) {
var codePoint = +arguments[index]
// correctly handles all cases including `NaN`, `-Infinity`, `+Infinity`
// The surrounding `!(...)` is required to correctly handle `NaN` cases
// The (codePoint>>>0) === codePoint clause handles decimals and negatives
if (!(codePoint < 0x10ffff && codePoint >>> 0 === codePoint))
throw RangeError('Invalid code point: ' + codePoint)
if (codePoint <= 0xffff) {
// BMP code point
codeLen = codeUnits.push(codePoint)
} else {
// Astral code point; split in surrogate halves
// https://mathiasbynens.be/notes/javascript-encoding#surrogate-formulae
codePoint -= 0x10000
codeLen = codeUnits.push(
(codePoint >> 10) + 0xd800, // highSurrogate
(codePoint % 0x400) + 0xdc00, // lowSurrogate
)
}
if (codeLen >= 0x3fff) {
result += stringFromCharCode.apply(null, codeUnits)
codeUnits.length = 0
}
}
return result + stringFromCharCode.apply(null, codeUnits)
}
try {
// IE 8 only supports `Object.defineProperty` on DOM elements
Object.defineProperty(String, 'fromCodePoint', {
value: fromCodePoint,
configurable: true,
writable: true,
})
} catch (e) {
String.fromCodePoint = fromCodePoint
}
})(String.fromCharCode)
}
/*! https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/includes */
if (!String.prototype.includes) {
String.prototype.includes = function (search, start) {
'use strict'
// @ts-ignore
if (search instanceof RegExp) {
throw TypeError('first argument must not be a RegExp')
}
if (start === undefined) {
start = 0
}
return this.indexOf(search, start) !== -1
}
}
/*! https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/repeat */
if (!String.prototype.repeat) {
String.prototype.repeat = function (count) {
'use strict'
if (this == null) throw new TypeError("can't convert " + this + ' to object')
var str = '' + this
// To convert string to integer.
count = +count
// Check NaN
if (count != count) count = 0
if (count < 0) throw new RangeError('repeat count must be non-negative')
if (count == Infinity) throw new RangeError('repeat count must be less than infinity')
count = Math.floor(count)
if (str.length == 0 || count == 0) return ''
// Ensuring count is a 31-bit integer allows us to heavily optimize the
// main part. But anyway, most current (August 2014) browsers can't handle
// strings 1 << 28 chars or longer, so:
if (str.length * count >= 1 << 28) throw new RangeError('repeat count must not overflow maximum string size')
var maxCount = str.length * count
count = Math.floor(Math.log(count) / Math.log(2))
while (count) {
str += str
count--
}
str += str.substring(0, maxCount - str.length)
return str
}
}
|
1f47b970a94bd8e2ee161a13a3e6336b23739348 | 4,496 | ts | TypeScript | src/gesture/gesture.ts | mrhegemon/human | 2e9e489369c3b70a2195b827dbab84268eaee303 | [
"MIT"
] | null | null | null | src/gesture/gesture.ts | mrhegemon/human | 2e9e489369c3b70a2195b827dbab84268eaee303 | [
"MIT"
] | null | null | null | src/gesture/gesture.ts | mrhegemon/human | 2e9e489369c3b70a2195b827dbab84268eaee303 | [
"MIT"
] | 1 | 2022-01-05T23:18:23.000Z | 2022-01-05T23:18:23.000Z | export const body = (res) => {
if (!res) return [];
const gestures: Array<{ body: number, gesture: string }> = [];
for (let i = 0; i < res.length; i++) {
// raising hands
const leftWrist = res[i].keypoints.find((a) => (a.part === 'leftWrist'));
const rightWrist = res[i].keypoints.find((a) => (a.part === 'rightWrist'));
const nose = res[i].keypoints.find((a) => (a.part === 'nose'));
if (nose && leftWrist && rightWrist && (leftWrist.position.y < nose.position.y) && (rightWrist.position.y < nose.position.y)) gestures.push({ body: i, gesture: 'i give up' });
else if (nose && leftWrist && (leftWrist.position.y < nose.position.y)) gestures.push({ body: i, gesture: 'raise left hand' });
else if (nose && rightWrist && (rightWrist.position.y < nose.position.y)) gestures.push({ body: i, gesture: 'raise right hand' });
// leaning
const leftShoulder = res[i].keypoints.find((a) => (a.part === 'leftShoulder'));
const rightShoulder = res[i].keypoints.find((a) => (a.part === 'rightShoulder'));
if (leftShoulder && rightShoulder) gestures.push({ body: i, gesture: `leaning ${(leftShoulder.position.y > rightShoulder.position.y) ? 'left' : 'right'}` });
}
return gestures;
};
export const face = (res) => {
if (!res) return [];
const gestures: Array<{ face: number, gesture: string }> = [];
for (let i = 0; i < res.length; i++) {
if (res[i].mesh && res[i].mesh.length > 0) {
const eyeFacing = res[i].mesh[35][2] - res[i].mesh[263][2];
if (Math.abs(eyeFacing) < 10) gestures.push({ face: i, gesture: 'facing camera' });
else gestures.push({ face: i, gesture: `facing ${eyeFacing < 0 ? 'right' : 'left'}` });
const openLeft = Math.abs(res[i].mesh[374][1] - res[i].mesh[386][1]) / Math.abs(res[i].mesh[443][1] - res[i].mesh[450][1]); // center of eye inner lid y coord div center of wider eye border y coord
if (openLeft < 0.2) gestures.push({ face: i, gesture: 'blink left eye' });
const openRight = Math.abs(res[i].mesh[145][1] - res[i].mesh[159][1]) / Math.abs(res[i].mesh[223][1] - res[i].mesh[230][1]); // center of eye inner lid y coord div center of wider eye border y coord
if (openRight < 0.2) gestures.push({ face: i, gesture: 'blink right eye' });
const mouthOpen = Math.min(100, 500 * Math.abs(res[i].mesh[13][1] - res[i].mesh[14][1]) / Math.abs(res[i].mesh[10][1] - res[i].mesh[152][1]));
if (mouthOpen > 10) gestures.push({ face: i, gesture: `mouth ${Math.trunc(mouthOpen)}% open` });
const chinDepth = res[i].mesh[152][2];
if (Math.abs(chinDepth) > 10) gestures.push({ face: i, gesture: `head ${chinDepth < 0 ? 'up' : 'down'}` });
}
}
return gestures;
};
export const iris = (res) => {
if (!res) return [];
const gestures: Array<{ iris: number, gesture: string }> = [];
for (let i = 0; i < res.length; i++) {
if (!res[i].annotations || !res[i].annotations.leftEyeIris || !res[i].annotations.rightEyeIris) continue;
const sizeXLeft = res[i].annotations.leftEyeIris[3][0] - res[i].annotations.leftEyeIris[1][0];
const sizeYLeft = res[i].annotations.leftEyeIris[4][1] - res[i].annotations.leftEyeIris[2][1];
const areaLeft = Math.abs(sizeXLeft * sizeYLeft);
const sizeXRight = res[i].annotations.rightEyeIris[3][0] - res[i].annotations.rightEyeIris[1][0];
const sizeYRight = res[i].annotations.rightEyeIris[4][1] - res[i].annotations.rightEyeIris[2][1];
const areaRight = Math.abs(sizeXRight * sizeYRight);
const difference = Math.abs(areaLeft - areaRight) / Math.max(areaLeft, areaRight);
if (difference < 0.25) gestures.push({ iris: i, gesture: 'looking at camera' });
}
return gestures;
};
export const hand = (res) => {
if (!res) return [];
const gestures: Array<{ hand: number, gesture: string }> = [];
for (let i = 0; i < res.length; i++) {
const fingers: Array<{ name: string, position: number }> = [];
for (const [finger, pos] of Object.entries(res[i]['annotations'])) {
// @ts-ignore
if (finger !== 'palmBase') fingers.push({ name: finger.toLowerCase(), position: pos[0] }); // get tip of each finger
}
if (fingers && fingers.length > 0) {
const closest = fingers.reduce((best, a) => (best.position[2] < a.position[2] ? best : a));
const highest = fingers.reduce((best, a) => (best.position[1] < a.position[1] ? best : a));
gestures.push({ hand: i, gesture: `${closest.name} forward ${highest.name} up` });
}
}
return gestures;
};
| 57.641026 | 204 | 0.61677 | 68 | 11 | 0 | 13 | 32 | 0 | 0 | 0 | 10 | 0 | 0 | 6.090909 | 1,550 | 0.015484 | 0.020645 | 0 | 0 | 0 | 0 | 0.178571 | 0.273487 | export /* Example usages of 'body' are shown below:
;
*/
const body = (res) => {
if (!res) return [];
const gestures = [];
for (let i = 0; i < res.length; i++) {
// raising hands
const leftWrist = res[i].keypoints.find((a) => (a.part === 'leftWrist'));
const rightWrist = res[i].keypoints.find((a) => (a.part === 'rightWrist'));
const nose = res[i].keypoints.find((a) => (a.part === 'nose'));
if (nose && leftWrist && rightWrist && (leftWrist.position.y < nose.position.y) && (rightWrist.position.y < nose.position.y)) gestures.push({ body: i, gesture: 'i give up' });
else if (nose && leftWrist && (leftWrist.position.y < nose.position.y)) gestures.push({ body: i, gesture: 'raise left hand' });
else if (nose && rightWrist && (rightWrist.position.y < nose.position.y)) gestures.push({ body: i, gesture: 'raise right hand' });
// leaning
const leftShoulder = res[i].keypoints.find((a) => (a.part === 'leftShoulder'));
const rightShoulder = res[i].keypoints.find((a) => (a.part === 'rightShoulder'));
if (leftShoulder && rightShoulder) gestures.push({ body: i, gesture: `leaning ${(leftShoulder.position.y > rightShoulder.position.y) ? 'left' : 'right'}` });
}
return gestures;
};
export /* Example usages of 'face' are shown below:
;
*/
const face = (res) => {
if (!res) return [];
const gestures = [];
for (let i = 0; i < res.length; i++) {
if (res[i].mesh && res[i].mesh.length > 0) {
const eyeFacing = res[i].mesh[35][2] - res[i].mesh[263][2];
if (Math.abs(eyeFacing) < 10) gestures.push({ face: i, gesture: 'facing camera' });
else gestures.push({ face: i, gesture: `facing ${eyeFacing < 0 ? 'right' : 'left'}` });
const openLeft = Math.abs(res[i].mesh[374][1] - res[i].mesh[386][1]) / Math.abs(res[i].mesh[443][1] - res[i].mesh[450][1]); // center of eye inner lid y coord div center of wider eye border y coord
if (openLeft < 0.2) gestures.push({ face: i, gesture: 'blink left eye' });
const openRight = Math.abs(res[i].mesh[145][1] - res[i].mesh[159][1]) / Math.abs(res[i].mesh[223][1] - res[i].mesh[230][1]); // center of eye inner lid y coord div center of wider eye border y coord
if (openRight < 0.2) gestures.push({ face: i, gesture: 'blink right eye' });
const mouthOpen = Math.min(100, 500 * Math.abs(res[i].mesh[13][1] - res[i].mesh[14][1]) / Math.abs(res[i].mesh[10][1] - res[i].mesh[152][1]));
if (mouthOpen > 10) gestures.push({ face: i, gesture: `mouth ${Math.trunc(mouthOpen)}% open` });
const chinDepth = res[i].mesh[152][2];
if (Math.abs(chinDepth) > 10) gestures.push({ face: i, gesture: `head ${chinDepth < 0 ? 'up' : 'down'}` });
}
}
return gestures;
};
export /* Example usages of 'iris' are shown below:
;
*/
const iris = (res) => {
if (!res) return [];
const gestures = [];
for (let i = 0; i < res.length; i++) {
if (!res[i].annotations || !res[i].annotations.leftEyeIris || !res[i].annotations.rightEyeIris) continue;
const sizeXLeft = res[i].annotations.leftEyeIris[3][0] - res[i].annotations.leftEyeIris[1][0];
const sizeYLeft = res[i].annotations.leftEyeIris[4][1] - res[i].annotations.leftEyeIris[2][1];
const areaLeft = Math.abs(sizeXLeft * sizeYLeft);
const sizeXRight = res[i].annotations.rightEyeIris[3][0] - res[i].annotations.rightEyeIris[1][0];
const sizeYRight = res[i].annotations.rightEyeIris[4][1] - res[i].annotations.rightEyeIris[2][1];
const areaRight = Math.abs(sizeXRight * sizeYRight);
const difference = Math.abs(areaLeft - areaRight) / Math.max(areaLeft, areaRight);
if (difference < 0.25) gestures.push({ iris: i, gesture: 'looking at camera' });
}
return gestures;
};
export /* Example usages of 'hand' are shown below:
;
*/
const hand = (res) => {
if (!res) return [];
const gestures = [];
for (let i = 0; i < res.length; i++) {
const fingers = [];
for (const [finger, pos] of Object.entries(res[i]['annotations'])) {
// @ts-ignore
if (finger !== 'palmBase') fingers.push({ name: finger.toLowerCase(), position: pos[0] }); // get tip of each finger
}
if (fingers && fingers.length > 0) {
const closest = fingers.reduce((best, a) => (best.position[2] < a.position[2] ? best : a));
const highest = fingers.reduce((best, a) => (best.position[1] < a.position[1] ? best : a));
gestures.push({ hand: i, gesture: `${closest.name} forward ${highest.name} up` });
}
}
return gestures;
};
|
1f562060eca011131a232aeab4be3f95cb3f4ab3 | 7,814 | tsx | TypeScript | src/util/api/requests.tsx | bcc-code/bcc-activechristianity | f15e6eb3f9b7c3ee8bd668791bf7f0114565af90 | [
"MIT"
] | null | null | null | src/util/api/requests.tsx | bcc-code/bcc-activechristianity | f15e6eb3f9b7c3ee8bd668791bf7f0114565af90 | [
"MIT"
] | 8 | 2022-02-15T00:58:32.000Z | 2022-03-23T06:44:34.000Z | src/util/api/requests.tsx | bcc-code/bcc-activechristianity | f15e6eb3f9b7c3ee8bd668791bf7f0114565af90 | [
"MIT"
] | null | null | null | const topicQuery = `
id
name
slug
noOfPosts
group {
id
name
}
image {
src
srcset
dataUri
}
`;
const postQuery = `
id
title
slug
excerpt
image {
src
srcset
dataUri
colors
}
readtime
track {
url
title
duration
post {
title
slug
}
playlists {
slug
title
}
}
authors {
name
slug
pivot {
as
}
id
}
topics {
name
slug
id
group {
name
slug
id
}
}
published
likes
views
`;
export interface IGetPostsAndTopics {
postsIds: string[];
topicsIds: string[];
}
export const loginMutation = (username: string, password: string, remember: boolean) => {
return `
mutation {
signIn(input:{
username:"${username}"
password:"${password}"
remember:${remember}
}){
success
user {
name
email
meta {
consented
notify
}
}
}
}
`;
};
export const registerMutation = (email: string, password: string, remember: boolean) => `
mutation {
signUp(input:{
name:"${email}",
email:"${email}",
password:"${password}",
remember:${remember}
}) {
success
user {
name
email
meta {
consented
notify
}
}
}
}
`;
export const forgotPasswordMutation = (email: string) => `
mutation {
forgotPassword(input:{email:"${email}"}) {
success
message
}
}
`;
export const toggleNotifyAndGiveConsent = (agree: boolean) => `
mutation ToggleNotify {
notifications(allow: ${agree}) {
success
message
}
consent(agreed: true) {
success
message
}
}
`;
export const toggleNotify = (agree: boolean) => `
mutation ToggleNotify {
notifications(allow: ${agree}) {
success
message
}
}
`;
export const giveConsent = `
mutation {
consent(agreed: true) {
success
message
}
}
`;
export const logoutMutation = `
mutation {
signOut {
status
}
}
`;
export const bookmarkPostMutation = (id: string, toggle: boolean) => `
mutation {
bookmarkPost(postId:${id}, toggle:${toggle}){
success
message
}
}
`;
export const followTopicMutation = (id: number, toggle: boolean) => `
mutation {
follow (type:TOPIC,id:${id},toggle:${toggle}){
success
message
}
}
`;
export const followPlaylistMutation = (id: number, toggle: boolean) => `
mutation {
follow (type:PLAYLIST,id:${id},toggle:${toggle}){
success
message
}
}
`;
export const readingPostMutation = (id: string) => `
mutation {
readingPost(postId:${id}){
success
timeRead
message
}
}
`;
export const visitsPostMutation = (id: string) => `
mutation {
visitsPost(postId:${id}){
success
message
}
}
`;
export const biblePostsQuery = (bookId: number, ch: number) => `
query {
biblePosts(id:"${bookId}", ch:${ch}){
slug
}
}
`;
export const recommendedByPostQuery = (postId: number | string) => `
query {
recommendedByPost(postId:${postId}){
slug
}
}
`;
export const recommendedPostsAndPopularTopic = () => `
query {
recommended(count:10){
slug
}
popularTopics{
slug
id
}
featuredTopics:topics(featured:true) {
slug
id
}
}
`;
export const topicReommendedPostsQuery = (topicId: number) => `
query {
rankingTopicPosts(topicId:${topicId}){
slug
}
}
`;
export const bookmarkedPostQuery = `
query {
bookmarked {
id
slug
}
}
`;
export const followingQuery = `
query {
following {
topics {
id
slug
}
playlists {
id
slug
}
authors {
id
slug
}
}
}
`;
export const latestHistoryQuery = `
query {
history(limit:10) {
id
slug
}
}
`;
export const unfinishedQuery = `
query {
unfinishedPosts {
id
slug
}
}
`;
export const profileQuery = `
query {
me {
name
email
id
meta {
consented
notify
}
subscriber {
email
locale
sent
unsubscribed_at
}
}
}
`;
export const getOnePostByIdQuery = (id: string) => {
return `
query {
post(id: ${id}) {
${postQuery}
content
langs {
lang
slug
}
readMorePosts:posts {
slug
}
seo {
title
desc
}
meta {
credits
no_dict
url
}
updated_at
}
}
`;
};
export const getOnePreviewPostByIdQuery = (id: string) => {
return `
query {
previewPost(id: ${id}) {
${postQuery}
content
langs {
lang
slug
}
readMorePosts:posts {
slug
}
seo {
title
desc
}
meta {
credits
no_dict
url
}
updated_at
}
}
`;
};
export const getOnePageByIdQuery = (id: string) => {
return `
query {
page(id:${id}){
title
slug
flexibleContent
}
}
`;
};
export const getOnePreviewPageByIdQuery = (id: string) => {
return `
query {
previewPage(id:${id}){
title
slug
flexibleContent
}
}
`;
};
export const getPostsByIds = (ids: IGetPostsAndTopics) => {
const { postsIds, topicsIds } = ids;
return `
query {
posts(ids: [${postsIds.join(',')}]) {
data {
${postQuery}
}
}
topics(ids:[${topicsIds.join(',')}]){
${topicQuery}
}
}
`;
};
export const getScriptChapterPostsQuery = (bookId: string, ch: string) => `
query {
biblePosts(id:"${bookId}", ch:${ch}){
slug
}
}
`;
export const getPostsPerPageQuery = (id: string, page: number) => `{
topic(id:${id}) {
somePosts(first:12,page:${page}){
data{
${postQuery}
}
}
}
}`;
export const getPostsPerPageBySubtopicId = (id: string, subtopicId: string, page: number) => `{
topic(id:${id}) {
id
name
somePosts (hasTopics: { value: ${subtopicId}, column: ID },first:12,page:${page}){
data {
${postQuery}
}
}
}
}
`;
export const checkUserSubscription = `
query GetUserAndSubscription {
me {
name
email
subscriber {
email
locale
sent
unsubscribed_at
}
}
}
`;
export const subscribeMutation = (email: string) => `
mutation subscribeNewOrUpdate {
subscribe(input: {email: "${email}"}) {
success
message
}
}
`;
export const unsubscribeMutation = (email: string) => `
mutation Unsubscribe {
unsubscribe(input: {email: ${email}}) {
success
message
}
}
`;
interface IUpdateProfile {
email?: string;
lang?: string;
name?: string;
}
export const updateProfileMutation = (props: IUpdateProfile) => {
const toAdd = Object.keys(props).map(key => `${key}:"${props[key]}"`);
const inputString = toAdd.join(',');
return `
mutation updateProfile {
profile(input: {${inputString}}) {
success
message
}
}`;
};
| 15.565737 | 95 | 0.490914 | 453 | 26 | 0 | 37 | 38 | 5 | 0 | 0 | 40 | 2 | 0 | 10.730769 | 1,934 | 0.032575 | 0.019648 | 0.002585 | 0.001034 | 0 | 0 | 0.377358 | 0.311675 | const topicQuery = `
id
name
slug
noOfPosts
group {
id
name
}
image {
src
srcset
dataUri
}
`;
const postQuery = `
id
title
slug
excerpt
image {
src
srcset
dataUri
colors
}
readtime
track {
url
title
duration
post {
title
slug
}
playlists {
slug
title
}
}
authors {
name
slug
pivot {
as
}
id
}
topics {
name
slug
id
group {
name
slug
id
}
}
published
likes
views
`;
export interface IGetPostsAndTopics {
postsIds;
topicsIds;
}
export const loginMutation = (username, password, remember) => {
return `
mutation {
signIn(input:{
username:"${username}"
password:"${password}"
remember:${remember}
}){
success
user {
name
email
meta {
consented
notify
}
}
}
}
`;
};
export const registerMutation = (email, password, remember) => `
mutation {
signUp(input:{
name:"${email}",
email:"${email}",
password:"${password}",
remember:${remember}
}) {
success
user {
name
email
meta {
consented
notify
}
}
}
}
`;
export const forgotPasswordMutation = (email) => `
mutation {
forgotPassword(input:{email:"${email}"}) {
success
message
}
}
`;
export const toggleNotifyAndGiveConsent = (agree) => `
mutation ToggleNotify {
notifications(allow: ${agree}) {
success
message
}
consent(agreed: true) {
success
message
}
}
`;
export const toggleNotify = (agree) => `
mutation ToggleNotify {
notifications(allow: ${agree}) {
success
message
}
}
`;
export const giveConsent = `
mutation {
consent(agreed: true) {
success
message
}
}
`;
export const logoutMutation = `
mutation {
signOut {
status
}
}
`;
export const bookmarkPostMutation = (id, toggle) => `
mutation {
bookmarkPost(postId:${id}, toggle:${toggle}){
success
message
}
}
`;
export const followTopicMutation = (id, toggle) => `
mutation {
follow (type:TOPIC,id:${id},toggle:${toggle}){
success
message
}
}
`;
export const followPlaylistMutation = (id, toggle) => `
mutation {
follow (type:PLAYLIST,id:${id},toggle:${toggle}){
success
message
}
}
`;
export const readingPostMutation = (id) => `
mutation {
readingPost(postId:${id}){
success
timeRead
message
}
}
`;
export const visitsPostMutation = (id) => `
mutation {
visitsPost(postId:${id}){
success
message
}
}
`;
export const biblePostsQuery = (bookId, ch) => `
query {
biblePosts(id:"${bookId}", ch:${ch}){
slug
}
}
`;
export const recommendedByPostQuery = (postId) => `
query {
recommendedByPost(postId:${postId}){
slug
}
}
`;
export const recommendedPostsAndPopularTopic = () => `
query {
recommended(count:10){
slug
}
popularTopics{
slug
id
}
featuredTopics:topics(featured:true) {
slug
id
}
}
`;
export const topicReommendedPostsQuery = (topicId) => `
query {
rankingTopicPosts(topicId:${topicId}){
slug
}
}
`;
export const bookmarkedPostQuery = `
query {
bookmarked {
id
slug
}
}
`;
export const followingQuery = `
query {
following {
topics {
id
slug
}
playlists {
id
slug
}
authors {
id
slug
}
}
}
`;
export const latestHistoryQuery = `
query {
history(limit:10) {
id
slug
}
}
`;
export const unfinishedQuery = `
query {
unfinishedPosts {
id
slug
}
}
`;
export const profileQuery = `
query {
me {
name
email
id
meta {
consented
notify
}
subscriber {
email
locale
sent
unsubscribed_at
}
}
}
`;
export const getOnePostByIdQuery = (id) => {
return `
query {
post(id: ${id}) {
${postQuery}
content
langs {
lang
slug
}
readMorePosts:posts {
slug
}
seo {
title
desc
}
meta {
credits
no_dict
url
}
updated_at
}
}
`;
};
export const getOnePreviewPostByIdQuery = (id) => {
return `
query {
previewPost(id: ${id}) {
${postQuery}
content
langs {
lang
slug
}
readMorePosts:posts {
slug
}
seo {
title
desc
}
meta {
credits
no_dict
url
}
updated_at
}
}
`;
};
export const getOnePageByIdQuery = (id) => {
return `
query {
page(id:${id}){
title
slug
flexibleContent
}
}
`;
};
export const getOnePreviewPageByIdQuery = (id) => {
return `
query {
previewPage(id:${id}){
title
slug
flexibleContent
}
}
`;
};
export const getPostsByIds = (ids) => {
const { postsIds, topicsIds } = ids;
return `
query {
posts(ids: [${postsIds.join(',')}]) {
data {
${postQuery}
}
}
topics(ids:[${topicsIds.join(',')}]){
${topicQuery}
}
}
`;
};
export const getScriptChapterPostsQuery = (bookId, ch) => `
query {
biblePosts(id:"${bookId}", ch:${ch}){
slug
}
}
`;
export const getPostsPerPageQuery = (id, page) => `{
topic(id:${id}) {
somePosts(first:12,page:${page}){
data{
${postQuery}
}
}
}
}`;
export const getPostsPerPageBySubtopicId = (id, subtopicId, page) => `{
topic(id:${id}) {
id
name
somePosts (hasTopics: { value: ${subtopicId}, column: ID },first:12,page:${page}){
data {
${postQuery}
}
}
}
}
`;
export const checkUserSubscription = `
query GetUserAndSubscription {
me {
name
email
subscriber {
email
locale
sent
unsubscribed_at
}
}
}
`;
export const subscribeMutation = (email) => `
mutation subscribeNewOrUpdate {
subscribe(input: {email: "${email}"}) {
success
message
}
}
`;
export const unsubscribeMutation = (email) => `
mutation Unsubscribe {
unsubscribe(input: {email: ${email}}) {
success
message
}
}
`;
interface IUpdateProfile {
email?;
lang?;
name?;
}
export const updateProfileMutation = (props) => {
const toAdd = Object.keys(props).map(key => `${key}:"${props[key]}"`);
const inputString = toAdd.join(',');
return `
mutation updateProfile {
profile(input: {${inputString}}) {
success
message
}
}`;
};
|
27135192e7c937d7bf130d060f315b29ce17fd9a | 4,643 | ts | TypeScript | src/helpers/pipes.ts | NikolasRoger/react-native-md-components | 2789132fbe42af74acdbc9212cdb0fde619d892f | [
"MIT"
] | null | null | null | src/helpers/pipes.ts | NikolasRoger/react-native-md-components | 2789132fbe42af74acdbc9212cdb0fde619d892f | [
"MIT"
] | null | null | null | src/helpers/pipes.ts | NikolasRoger/react-native-md-components | 2789132fbe42af74acdbc9212cdb0fde619d892f | [
"MIT"
] | 1 | 2022-01-07T12:53:21.000Z | 2022-01-07T12:53:21.000Z | const formatMoney = (n: any) => {
if (n === 0 || n === null) {
return 'R$ 0,00'
}
if (typeof n === 'string' && n.includes('R$')) {
let newNumber: any = n.substr(2).trim()
newNumber = newNumber.replace(/\./g, '')
newNumber = newNumber.replace(',', '.')
newNumber = parseFloat(newNumber)
return newNumber
}
return (
'R$ ' +
parseFloat(n)
.toFixed(2)
.replace('.', ',')
.replace(/(\d)(?=(\d{3})+\,)/g, '$1.')
)
}
const formatDate = (date: string) => {
if (!date) {
return false
}
if (date.includes('T')) {
date = date.split('T')[0]
}
if (date.includes('/')) {
const year = date.split('/')[2],
month = date.split('/')[1],
day = date.split('/')[0],
newDate = year + '/' + month + '/' + day
return newDate
}
if (date.length >= 9) {
const year = date.split('-')[0],
month = date.split('-')[1],
day = date.split('-')[2],
newDate = day + '/' + month + '/' + year
return newDate
}
const year = date.substr(0, 4),
month = date.substr(4, 2),
day = date.substr(6, 2),
newDate = day + '/' + month + '/' + year
return newDate
}
const addDaysToDate = (date: string, days: number) => {
var result: any = new Date(date)
result.setDate(result.getDate() + days)
return result
}
const subDaysToDate = (date: string, days: number) => {
var result: any = new Date(date)
result.setDate(result.getDate() - days)
return result
}
const dateToISOString = (date: string) => {
const year = date.split('/')[2],
month = date.split('/')[1],
day = date.split('/')[0],
newDate = new Date(year + '-' + month + '-' + day).toISOString()
return newDate
}
const formatAccountDigit = (string: string) => {
if (!string) return ''
string = string.replace(/\-/g, '')
let newString = string
if (string.length > 1) {
newString = string.substr(0, string.length - 1) + '-' + string.substr(-1)
}
return newString
}
const formatCnpj = (cnpj: string) => {
return cnpj.replace(/^(\d{2})(\d{3})(\d{3})(\d{4})(\d{2})/, '$1.$2.$3/$4-$5')
}
const formatCpf = (cpf: string) => {
return cpf.replace(/^(\d{3})(\d{3})(\d{3})(\d{2})/, '$1.$2.$3-$4')
}
const formatCpfCnpj = (text: string) => {
if (text.length === 11) {
return formatCpf(text)
} else if (text.length === 14) {
return formatCnpj(text)
} else {
return ''
}
}
const getDbDate = () => {
const date = new Date(),
y = date.getFullYear(),
m = date.getMonth() + 1,
d = date.getDate(),
h = date.getHours() < 10 ? '0' + date.getHours() : date.getHours(),
min = date.getMinutes() < 10 ? '0' + date.getMinutes() : date.getMinutes(),
s = date.getSeconds() < 10 ? '0' + date.getSeconds() : date.getSeconds()
return `${y}-${m}-${d} ${h}:${min}:${s}`
}
const cardMask = (number: string) => {
return number.replace(/^(.{4})(.{4})(.{4})(.{4})/, '$1 $2 $3 $4')
}
const contactMask = (contact: string) => {
return contact.replace(/^(\d{2})(\d{5})(\d{4})/, '($1) $2-$3')
}
const cepMask = (cep: string) => {
return cep.replace(/^(\d{4})(\d{4})/, '$1-$2')
}
const formatDateTime = (date: Date, isToDb = false) => {
date = new Date(date)
const d = date.getDate() < 10 ? '0' + date.getDate() : date.getDate()
const m = date.getMonth() + 1 < 10 ? '0' + (date.getMonth() + 1) : date.getMonth() + 1
const y = date.getFullYear()
const h = date.getUTCHours() < 10 ? '0' + date.getUTCHours() : date.getUTCHours()
const min = date.getUTCMinutes() < 10 ? '0' + date.getUTCMinutes() : date.getUTCMinutes()
const s = date.getUTCSeconds() < 10 ? '0' + date.getUTCSeconds() : date.getUTCSeconds()
if (isToDb) return `${y}-${m}-${d} ${h}:${min}:${s}`
return `${d}/${m}/${y} ${h}:${min}`
}
const removeHtmlFromText = (text: string): string => {
if(!text) return ""
return Array.from(text.replace(/<[^>]*>?/gm, ' ')).filter((i, index, arr) => {
if(index > 0 && arr[index - 1] === " " && i === " ") {
return false
} else {
return true
}
}).join("").trim()
}
export default {
formatMoney,
formatDate,
addDaysToDate,
subDaysToDate,
dateToISOString,
formatAccountDigit,
formatCnpj,
formatCpf,
formatCpfCnpj,
getDbDate,
cardMask,
contactMask,
cepMask,
formatDateTime,
removeHtmlFromText
}
| 26.994186 | 93 | 0.510877 | 144 | 16 | 0 | 20 | 48 | 0 | 2 | 4 | 15 | 0 | 1 | 6.375 | 1,474 | 0.024423 | 0.032564 | 0 | 0 | 0.000678 | 0.047619 | 0.178571 | 0.333021 | /* Example usages of 'formatMoney' are shown below:
;
*/
const formatMoney = (n) => {
if (n === 0 || n === null) {
return 'R$ 0,00'
}
if (typeof n === 'string' && n.includes('R$')) {
let newNumber = n.substr(2).trim()
newNumber = newNumber.replace(/\./g, '')
newNumber = newNumber.replace(',', '.')
newNumber = parseFloat(newNumber)
return newNumber
}
return (
'R$ ' +
parseFloat(n)
.toFixed(2)
.replace('.', ',')
.replace(/(\d)(?=(\d{3})+\,)/g, '$1.')
)
}
/* Example usages of 'formatDate' are shown below:
;
*/
const formatDate = (date) => {
if (!date) {
return false
}
if (date.includes('T')) {
date = date.split('T')[0]
}
if (date.includes('/')) {
const year = date.split('/')[2],
month = date.split('/')[1],
day = date.split('/')[0],
newDate = year + '/' + month + '/' + day
return newDate
}
if (date.length >= 9) {
const year = date.split('-')[0],
month = date.split('-')[1],
day = date.split('-')[2],
newDate = day + '/' + month + '/' + year
return newDate
}
const year = date.substr(0, 4),
month = date.substr(4, 2),
day = date.substr(6, 2),
newDate = day + '/' + month + '/' + year
return newDate
}
/* Example usages of 'addDaysToDate' are shown below:
;
*/
const addDaysToDate = (date, days) => {
var result = new Date(date)
result.setDate(result.getDate() + days)
return result
}
/* Example usages of 'subDaysToDate' are shown below:
;
*/
const subDaysToDate = (date, days) => {
var result = new Date(date)
result.setDate(result.getDate() - days)
return result
}
/* Example usages of 'dateToISOString' are shown below:
;
*/
const dateToISOString = (date) => {
const year = date.split('/')[2],
month = date.split('/')[1],
day = date.split('/')[0],
newDate = new Date(year + '-' + month + '-' + day).toISOString()
return newDate
}
/* Example usages of 'formatAccountDigit' are shown below:
;
*/
const formatAccountDigit = (string) => {
if (!string) return ''
string = string.replace(/\-/g, '')
let newString = string
if (string.length > 1) {
newString = string.substr(0, string.length - 1) + '-' + string.substr(-1)
}
return newString
}
/* Example usages of 'formatCnpj' are shown below:
formatCnpj(text);
;
*/
const formatCnpj = (cnpj) => {
return cnpj.replace(/^(\d{2})(\d{3})(\d{3})(\d{4})(\d{2})/, '$1.$2.$3/$4-$5')
}
/* Example usages of 'formatCpf' are shown below:
formatCpf(text);
;
*/
const formatCpf = (cpf) => {
return cpf.replace(/^(\d{3})(\d{3})(\d{3})(\d{2})/, '$1.$2.$3-$4')
}
/* Example usages of 'formatCpfCnpj' are shown below:
;
*/
const formatCpfCnpj = (text) => {
if (text.length === 11) {
return formatCpf(text)
} else if (text.length === 14) {
return formatCnpj(text)
} else {
return ''
}
}
/* Example usages of 'getDbDate' are shown below:
;
*/
const getDbDate = () => {
const date = new Date(),
y = date.getFullYear(),
m = date.getMonth() + 1,
d = date.getDate(),
h = date.getHours() < 10 ? '0' + date.getHours() : date.getHours(),
min = date.getMinutes() < 10 ? '0' + date.getMinutes() : date.getMinutes(),
s = date.getSeconds() < 10 ? '0' + date.getSeconds() : date.getSeconds()
return `${y}-${m}-${d} ${h}:${min}:${s}`
}
/* Example usages of 'cardMask' are shown below:
;
*/
const cardMask = (number) => {
return number.replace(/^(.{4})(.{4})(.{4})(.{4})/, '$1 $2 $3 $4')
}
/* Example usages of 'contactMask' are shown below:
;
*/
const contactMask = (contact) => {
return contact.replace(/^(\d{2})(\d{5})(\d{4})/, '($1) $2-$3')
}
/* Example usages of 'cepMask' are shown below:
;
*/
const cepMask = (cep) => {
return cep.replace(/^(\d{4})(\d{4})/, '$1-$2')
}
/* Example usages of 'formatDateTime' are shown below:
;
*/
const formatDateTime = (date, isToDb = false) => {
date = new Date(date)
const d = date.getDate() < 10 ? '0' + date.getDate() : date.getDate()
const m = date.getMonth() + 1 < 10 ? '0' + (date.getMonth() + 1) : date.getMonth() + 1
const y = date.getFullYear()
const h = date.getUTCHours() < 10 ? '0' + date.getUTCHours() : date.getUTCHours()
const min = date.getUTCMinutes() < 10 ? '0' + date.getUTCMinutes() : date.getUTCMinutes()
const s = date.getUTCSeconds() < 10 ? '0' + date.getUTCSeconds() : date.getUTCSeconds()
if (isToDb) return `${y}-${m}-${d} ${h}:${min}:${s}`
return `${d}/${m}/${y} ${h}:${min}`
}
/* Example usages of 'removeHtmlFromText' are shown below:
;
*/
const removeHtmlFromText = (text) => {
if(!text) return ""
return Array.from(text.replace(/<[^>]*>?/gm, ' ')).filter((i, index, arr) => {
if(index > 0 && arr[index - 1] === " " && i === " ") {
return false
} else {
return true
}
}).join("").trim()
}
export default {
formatMoney,
formatDate,
addDaysToDate,
subDaysToDate,
dateToISOString,
formatAccountDigit,
formatCnpj,
formatCpf,
formatCpfCnpj,
getDbDate,
cardMask,
contactMask,
cepMask,
formatDateTime,
removeHtmlFromText
}
|
271bbf8cd3e3581fd22fedc75089c2f448d88905 | 1,774 | ts | TypeScript | RecommenederSystem/api/controllers/RecommenderModule/LinkPublicationController.ts | JonathanPachacama/AplicacionFer | 3a606e22b7c6a8d777e251f695e8dd6d12a54352 | [
"MIT"
] | null | null | null | RecommenederSystem/api/controllers/RecommenderModule/LinkPublicationController.ts | JonathanPachacama/AplicacionFer | 3a606e22b7c6a8d777e251f695e8dd6d12a54352 | [
"MIT"
] | 1 | 2022-02-10T19:23:59.000Z | 2022-02-10T19:23:59.000Z | RecommenederSystem/api/controllers/RecommenderModule/LinkPublicationController.ts | JonathanPachacama/recommendation-system-scientific-articles-linked-data | 3a606e22b7c6a8d777e251f695e8dd6d12a54352 | [
"MIT"
] | null | null | null | declare var module;
declare var sails;
declare var LinkPublication;
declare var Articulo;
declare var Wkx_resource;
module.exports = {
TEST:(req, res) =>{
let parametros = req.allParams();
sails.log.info("Parametros", parametros);
Wkx_resource
.find()
.where({
resourceTitle: {
contains: parametros.busqueda
}
})
.exec((err, resourceFound) => {
if (err) return res.negotiate(err);
return res.json( {
resource: resourceFound
})
});
},
result:(req, res) =>{
return res.view('recommenderLinkedData', {
})
},
result1:(req, res) =>{
return res.view('RecommenderModule/byLink', {
})
},
result2:(req, res) =>{
return res.view('RecommenderModule/byAuthor', {
})
},
result3:(req, res) =>{
return res.view('RecommenderModule/byTitleSameAuthor', {
})
},
result4:(req, res) =>{
return res.view('RecommenderModule/bySameAreaOfinterest', {
})
},
ranking:(req, res) =>{
return res.view('RecommenderModule/ranking', {
})
},
createLinkToAPublication: (req, res) => {
let parameters = req.allParams();
let newLinks = {
links_Value: parameters.links_Value,
link_Type: parameters.link_Type,
o_Value: parameters.o_Value,
o_Type: parameters.o_Type,
};
LinkPublication.create(newLinks)
.exec(
(error,linkcreated)=>{
if(error){
return res.serverError(error);
}else{
// return res.ok(linkCreado);
//return res.created('Nuevo articulo creado.');
return res.view('RecommenderModule/byLink', {
link:linkcreated
})
}
}
)
},
}
| 18.673684 | 63 | 0.563134 | 69 | 10 | 0 | 20 | 8 | 0 | 0 | 0 | 0 | 0 | 0 | 5.7 | 472 | 0.063559 | 0.016949 | 0 | 0 | 0 | 0 | 0 | 0.374178 | declare var module;
declare var sails;
declare var LinkPublication;
declare var Articulo;
declare var Wkx_resource;
module.exports = {
TEST:(req, res) =>{
let parametros = req.allParams();
sails.log.info("Parametros", parametros);
Wkx_resource
.find()
.where({
resourceTitle: {
contains: parametros.busqueda
}
})
.exec((err, resourceFound) => {
if (err) return res.negotiate(err);
return res.json( {
resource: resourceFound
})
});
},
result:(req, res) =>{
return res.view('recommenderLinkedData', {
})
},
result1:(req, res) =>{
return res.view('RecommenderModule/byLink', {
})
},
result2:(req, res) =>{
return res.view('RecommenderModule/byAuthor', {
})
},
result3:(req, res) =>{
return res.view('RecommenderModule/byTitleSameAuthor', {
})
},
result4:(req, res) =>{
return res.view('RecommenderModule/bySameAreaOfinterest', {
})
},
ranking:(req, res) =>{
return res.view('RecommenderModule/ranking', {
})
},
createLinkToAPublication: (req, res) => {
let parameters = req.allParams();
let newLinks = {
links_Value: parameters.links_Value,
link_Type: parameters.link_Type,
o_Value: parameters.o_Value,
o_Type: parameters.o_Type,
};
LinkPublication.create(newLinks)
.exec(
(error,linkcreated)=>{
if(error){
return res.serverError(error);
}else{
// return res.ok(linkCreado);
//return res.created('Nuevo articulo creado.');
return res.view('RecommenderModule/byLink', {
link:linkcreated
})
}
}
)
},
}
|
27a493ada994b85fc1ed438e2a30a8ce7eab7c21 | 1,981 | ts | TypeScript | packages/eventemitter/src/index.ts | ue007/hello-series | 3108d4e6b3d1c8cb41014e0fcda0d14d4a70e57a | [
"MIT"
] | 1 | 2022-01-08T08:15:08.000Z | 2022-01-08T08:15:08.000Z | packages/eventemitter/src/index.ts | ue007/hello-series | 3108d4e6b3d1c8cb41014e0fcda0d14d4a70e57a | [
"MIT"
] | null | null | null | packages/eventemitter/src/index.ts | ue007/hello-series | 3108d4e6b3d1c8cb41014e0fcda0d14d4a70e57a | [
"MIT"
] | null | null | null | /**
* EventType
*/
interface EventType {
readonly callback: Function;
readonly once: boolean;
}
type EventsType = Record<string, EventType[]>;
const WILDCARD = '*';
/* event-emitter */
export default class EventEmitter {
private _events: EventsType = {};
/**
* 监听一个事件
* @param evt
* @param callback
* @param once
*/
on(evt: string, callback: Function, once?: boolean) {
if (!this._events[evt]) {
this._events[evt] = [];
}
this._events[evt].push({
callback,
once: !!once,
});
return this;
}
/**
* 监听一个事件一次
* @param evt
* @param callback
*/
once(evt: string, callback: Function) {
return this.on(evt, callback, true);
}
/**
* 触发一个事件
* @param evt
* @param args
*/
emit(evt: string, ...args: any[]) {
const events = this._events[evt] || [];
const wildcardEvents = this._events[WILDCARD] || [];
// 实际的处理 emit 方法
const doEmit = (es: EventType[]) => {
let length = es.length;
for (let i = 0; i < length; i++) {
if (!es[i]) {
continue;
}
const { callback, once } = es[i];
if (once) {
es.splice(i, 1);
if (es.length === 0) {
delete this._events[evt];
}
length--;
i--;
}
callback.apply(this, args);
}
};
doEmit(events);
doEmit(wildcardEvents);
}
/**
* 取消监听一个事件,或者一个channel
* @param evt
* @param callback
*/
off(evt?: string, callback?: Function) {
if (!evt) {
// evt 为空全部清除
this._events = {};
} else {
if (!callback) {
// evt 存在,callback 为空,清除事件所有方法
delete this._events[evt];
} else {
// evt 存在,callback 存在,清除匹配的
const events = this._events[evt] || [];
let length = events.length;
for (let i = 0; i < length; i++) {
if (events[i].callback === callback) {
events.splice(i, 1);
length--;
i--;
}
}
if (events.length === 0) {
delete this._events[evt];
}
}
}
return this;
}
/* 当前所有的事件 */
getEvents() {
return this._events;
}
}
| 16.508333 | 54 | 0.549722 | 72 | 6 | 0 | 10 | 10 | 3 | 2 | 5 | 7 | 3 | 0 | 11.5 | 712 | 0.022472 | 0.014045 | 0.004213 | 0.004213 | 0 | 0.172414 | 0.241379 | 0.272791 | /**
* EventType
*/
interface EventType {
readonly callback;
readonly once;
}
type EventsType = Record<string, EventType[]>;
const WILDCARD = '*';
/* event-emitter */
export default class EventEmitter {
private _events = {};
/**
* 监听一个事件
* @param evt
* @param callback
* @param once
*/
on(evt, callback, once?) {
if (!this._events[evt]) {
this._events[evt] = [];
}
this._events[evt].push({
callback,
once: !!once,
});
return this;
}
/**
* 监听一个事件一次
* @param evt
* @param callback
*/
once(evt, callback) {
return this.on(evt, callback, true);
}
/**
* 触发一个事件
* @param evt
* @param args
*/
emit(evt, ...args) {
const events = this._events[evt] || [];
const wildcardEvents = this._events[WILDCARD] || [];
// 实际的处理 emit 方法
/* Example usages of 'doEmit' are shown below:
doEmit(events);
doEmit(wildcardEvents);
*/
const doEmit = (es) => {
let length = es.length;
for (let i = 0; i < length; i++) {
if (!es[i]) {
continue;
}
const { callback, once } = es[i];
if (once) {
es.splice(i, 1);
if (es.length === 0) {
delete this._events[evt];
}
length--;
i--;
}
callback.apply(this, args);
}
};
doEmit(events);
doEmit(wildcardEvents);
}
/**
* 取消监听一个事件,或者一个channel
* @param evt
* @param callback
*/
off(evt?, callback?) {
if (!evt) {
// evt 为空全部清除
this._events = {};
} else {
if (!callback) {
// evt 存在,callback 为空,清除事件所有方法
delete this._events[evt];
} else {
// evt 存在,callback 存在,清除匹配的
const events = this._events[evt] || [];
let length = events.length;
for (let i = 0; i < length; i++) {
if (events[i].callback === callback) {
events.splice(i, 1);
length--;
i--;
}
}
if (events.length === 0) {
delete this._events[evt];
}
}
}
return this;
}
/* 当前所有的事件 */
getEvents() {
return this._events;
}
}
|
27b16bf17472c5bf350e61f974cdde739d4372f3 | 9,766 | ts | TypeScript | src/index.ts | hirishu10/simple-date-time | 5c68d3d9fa807585728e48b3fce9082aa0857a90 | [
"MIT"
] | 1 | 2022-03-15T16:26:04.000Z | 2022-03-15T16:26:04.000Z | src/index.ts | hirishu10/simple-date-time | 5c68d3d9fa807585728e48b3fce9082aa0857a90 | [
"MIT"
] | null | null | null | src/index.ts | hirishu10/simple-date-time | 5c68d3d9fa807585728e48b3fce9082aa0857a90 | [
"MIT"
] | null | null | null | /**
*
* @param capsOnFlag By default False | If Provide True then return the String in UpperCase else in LowerCase
* @param properCaseFlag By default True | Providing this the String will return in Proper structure
* @returns - `String`
*/
export const getCustomDayNameFull = (
capsOnFlag?: boolean | undefined | null,
properCaseFlag?: boolean | undefined | null
) => {
const date = new Date();
const properCase = properCaseFlag === false ? false : true;
switch (date.getDay()) {
case 0:
return capsOnFlag ? "SUNDAY" : properCase ? "Sunday" : "sunday";
case 1:
return capsOnFlag ? "MONDAY" : properCase ? "Monday" : "monday";
case 2:
return capsOnFlag ? "TUESDAY" : properCase ? "Tuesday" : "tuesday";
case 3:
return capsOnFlag ? "WEDNESDAY" : properCase ? "Wednesday" : "wednesday";
case 4:
return capsOnFlag ? "THURSDAY" : properCase ? "Thursday" : "thursday";
case 5:
return capsOnFlag ? "FRIDAY" : properCase ? "Friday" : "friday";
case 6:
return capsOnFlag ? "SATURDAY" : properCase ? "Saturday" : "saturday";
default:
return null;
}
};
/**
*
* @param capsOnFlag By default False | If Provide True then return the String in UpperCase else in LowerCase
* @param properCaseFlag By default True | Providing this the String will return in Proper structure
* @returns - `String`
*/
export const getCustomDayNameShort = (
capsOnFlag?: boolean | undefined | null,
properCaseFlag?: boolean | undefined | null
) => {
const date = new Date();
const properCase = properCaseFlag === false ? false : true;
switch (date.getDay()) {
case 0:
return capsOnFlag ? "SUN" : properCase ? "Sun" : "sun";
case 1:
return capsOnFlag ? "MON" : properCase ? "Mon" : "mon";
case 2:
return capsOnFlag ? "TUE" : properCase ? "Tue" : "tue";
case 3:
return capsOnFlag ? "WED" : properCase ? "Wed" : "wed";
case 4:
return capsOnFlag ? "THU" : properCase ? "Thu" : "thu";
case 5:
return capsOnFlag ? "FRI" : properCase ? "Fri" : "fri";
case 6:
return capsOnFlag ? "SAT" : properCase ? "Sat" : "sat";
default:
return null;
}
};
/**
*
* @param capsOnFlag By default False | If Provide True then return the String in UpperCase else in LowerCase
* @param properCaseFlag By default True | Providing this the String will return in Proper structure
* @returns - `String`
*/
export const getCustomMonthNameFull = (
capsOnFlag?: boolean | undefined | null,
properCaseFlag?: boolean | undefined | null
) => {
const date = new Date();
const properCase = properCaseFlag === false ? false : true;
switch (date.getMonth()) {
case 0:
return capsOnFlag ? "JANUARY" : properCase ? "January" : "january";
case 1:
return capsOnFlag ? "FEBRUARY" : properCase ? "February" : "february";
case 2:
return capsOnFlag ? "MARCH" : properCase ? "March" : "march";
case 3:
return capsOnFlag ? "APRIL" : properCase ? "April" : "april";
case 4:
return capsOnFlag ? "MAY" : properCase ? "May" : "may";
case 5:
return capsOnFlag ? "JUNE" : properCase ? "June" : "june";
case 6:
return capsOnFlag ? "JULY" : properCase ? "July" : "july";
case 7:
return capsOnFlag ? "AUGUST" : properCase ? "August" : "august";
case 8:
return capsOnFlag ? "SEPTEMBER" : properCase ? "September" : "september";
case 9:
return capsOnFlag ? "OCTOBER" : properCase ? "October" : "october";
case 10:
return capsOnFlag ? "NOVEMBER" : properCase ? "November" : "november";
case 11:
return capsOnFlag ? "DECEMBER" : properCase ? "December" : "december";
default:
return null;
}
};
/**
*
* @param capsOnFlag By default False | If Provide True then return the String in UpperCase else in LowerCase
* @param properCaseFlag By default True | Providing this the String will return in Proper structure
* @returns - `String`
*/
export const getCustomMonthNameShort = (
capsOnFlag?: boolean | undefined | null,
properCaseFlag?: boolean | undefined | null
) => {
const date = new Date();
const properCase = properCaseFlag === false ? false : true;
switch (date.getMonth()) {
case 0:
return capsOnFlag ? "JAN" : properCase ? "Jan" : "jan";
case 1:
return capsOnFlag ? "FEB" : properCase ? "Feb" : "feb";
case 2:
return capsOnFlag ? "MAR" : properCase ? "Mar" : "mar";
case 3:
return capsOnFlag ? "APR" : properCase ? "Apr" : "apr";
case 4:
return capsOnFlag ? "MAY" : properCase ? "May" : "may";
case 5:
return capsOnFlag ? "JUN" : properCase ? "Jun" : "jun";
case 6:
return capsOnFlag ? "JUL" : properCase ? "Jul" : "jul";
case 7:
return capsOnFlag ? "AUG" : properCase ? "Aug" : "aug";
case 8:
return capsOnFlag ? "SEP" : properCase ? "Sep" : "sep";
case 9:
return capsOnFlag ? "OCT" : properCase ? "Oct" : "oct";
case 10:
return capsOnFlag ? "NOV" : properCase ? "Nov" : "nov";
case 11:
return capsOnFlag ? "DEC" : properCase ? "Dec" : "dec";
default:
return null;
}
};
/**
*
* @param changeToStringFlag Totally Optional if you need in String make true the flag else ignore
* @returns Today Date from (1 - 30 or 1 - 31) <= Default `Number` else you can change to `String`
*/
export const getCustomDate = (
changeToStringFlag?: boolean | undefined | null
) => {
const d = new Date();
const date = d.getDate();
return date ? (changeToStringFlag ? String(date) : date) : null;
};
/**
*
* @param changeToStringFlag Totally Optional if you need in String make true the flag else ignore
* @returns Current hour in number (1 - 12) <= Default `Number` else you can change to `String`
*/
export const getCustomHour = (
changeToStringFlag?: boolean | undefined | null
) => {
const d = new Date();
const hour = d.getHours() > 12 ? d.getHours() - 12 : d.getHours();
return hour === 0
? changeToStringFlag
? String(12)
: 12
: hour
? changeToStringFlag
? String(hour)
: hour
: null;
};
/**
*
* @param changeToStringFlag Totally Optional if you need in String make true the flag else ignore
* @returns Current minute in number (1 - 60) <= Default `Number` else you can change to `String`
*/
export const getCustomMinute = (
changeToStringFlag?: boolean | undefined | null
) => {
const d = new Date();
const minute =
d.getMinutes() >= 10
? changeToStringFlag
? String(d.getMinutes())
: d.getMinutes()
: `0${d.getMinutes()}`;
return minute ? minute : null;
};
/**
*
* @param changeToStringFlag Totally Optional if you need in String make true the flag else ignore
* @returns Current minute in number (1 - 60) <= Default `Number` else you can change to `String`
*/
export const getCustomSecond = (
changeToStringFlag?: boolean | undefined | null
) => {
const d = new Date();
const seconds =
d.getSeconds() >= 10
? changeToStringFlag
? String(d.getSeconds())
: d.getSeconds()
: `0${d.getSeconds()}`;
return seconds ? seconds : null;
};
/**
*
* @param capsOnFlag By default False | If Provide True then return the String in UpperCase else in LowerCase
* @returns `String` (Check `capsOnFlag` to return like AM or am | PM or pm)
*/
export const getCustomAmPm = (capsOnFlag: boolean | undefined | null) => {
const d = new Date();
const amPm = d.getHours() >= 12 ? "pm" : "am";
return amPm ? (capsOnFlag ? amPm.toUpperCase() : amPm) : null;
};
/**
*
* @param shortOrFullFlag By Default False which return the Day, Month in Short else Make True to return in Full
* @param lowerOrUpperFlag By Default False which return the Day, Month in lowerCase else Make True to return in UpperCase
* @returns The Full TimeStamp in `String` --> ( 10 OCT TUE 10:10AM - 10 Oct Tue 10:10am ) | ( 10 OCTOBER TUESDAY 10:10AM - 10 October Tuesday 10:10am )
*/
export const getCustomFullDateAndTimeWithAmPm = (
shortOrFullFlag?: boolean,
lowerOrUpperFlag?: boolean
) => {
const timeStamp = `${getCustomDate()} ${
shortOrFullFlag
? getCustomMonthNameShort(lowerOrUpperFlag ? lowerOrUpperFlag : false)
: getCustomMonthNameFull(lowerOrUpperFlag ? lowerOrUpperFlag : false)
} ${
shortOrFullFlag
? getCustomDayNameShort(lowerOrUpperFlag ? lowerOrUpperFlag : false)
: getCustomDayNameFull(lowerOrUpperFlag ? lowerOrUpperFlag : false)
} ${getCustomHour()}:${getCustomMinute()}${getCustomAmPm(
lowerOrUpperFlag ? lowerOrUpperFlag : false
)}`;
return timeStamp ? timeStamp : null;
};
/**
*
* @param shortOrFullFlag By Default False which return the Day, Month in Short else Make True to return in Full
* @param lowerOrUpperFlag By Default False which return the Day, Month in lowerCase else Make True to return in UpperCase
* @returns The Full TimeStamp in `String` --> ( 10 OCT TUE 10:10:00AM - 10 Oct Tue 10:10:00am ) | ( 10 OCTOBER TUESDAY 10:10:00AM - 10 October Tuesday 10:10:00am )
*/
export const getCustomFullDateAndTimeWithAmPmIncludingSeconds = (
shortOrFullFlag?: boolean,
lowerOrUpperFlag?: boolean
) => {
const timeStamp = `${getCustomDate()} ${
shortOrFullFlag
? getCustomMonthNameShort(lowerOrUpperFlag ? lowerOrUpperFlag : false)
: getCustomMonthNameFull(lowerOrUpperFlag ? lowerOrUpperFlag : false)
} ${
shortOrFullFlag
? getCustomDayNameShort(lowerOrUpperFlag ? lowerOrUpperFlag : false)
: getCustomDayNameFull(lowerOrUpperFlag ? lowerOrUpperFlag : false)
} ${getCustomHour()}:${getCustomMinute()}:${getCustomSecond()}${getCustomAmPm(
lowerOrUpperFlag ? lowerOrUpperFlag : false
)}`;
return timeStamp ? timeStamp : null;
};
| 34.878571 | 164 | 0.650727 | 205 | 11 | 0 | 17 | 31 | 0 | 9 | 0 | 17 | 0 | 0 | 14.272727 | 2,904 | 0.009642 | 0.010675 | 0 | 0 | 0 | 0 | 0.288136 | 0.229428 | /**
*
* @param capsOnFlag By default False | If Provide True then return the String in UpperCase else in LowerCase
* @param properCaseFlag By default True | Providing this the String will return in Proper structure
* @returns - `String`
*/
export /* Example usages of 'getCustomDayNameFull' are shown below:
shortOrFullFlag
? getCustomDayNameShort(lowerOrUpperFlag ? lowerOrUpperFlag : false)
: getCustomDayNameFull(lowerOrUpperFlag ? lowerOrUpperFlag : false);
*/
const getCustomDayNameFull = (
capsOnFlag?,
properCaseFlag?
) => {
const date = new Date();
const properCase = properCaseFlag === false ? false : true;
switch (date.getDay()) {
case 0:
return capsOnFlag ? "SUNDAY" : properCase ? "Sunday" : "sunday";
case 1:
return capsOnFlag ? "MONDAY" : properCase ? "Monday" : "monday";
case 2:
return capsOnFlag ? "TUESDAY" : properCase ? "Tuesday" : "tuesday";
case 3:
return capsOnFlag ? "WEDNESDAY" : properCase ? "Wednesday" : "wednesday";
case 4:
return capsOnFlag ? "THURSDAY" : properCase ? "Thursday" : "thursday";
case 5:
return capsOnFlag ? "FRIDAY" : properCase ? "Friday" : "friday";
case 6:
return capsOnFlag ? "SATURDAY" : properCase ? "Saturday" : "saturday";
default:
return null;
}
};
/**
*
* @param capsOnFlag By default False | If Provide True then return the String in UpperCase else in LowerCase
* @param properCaseFlag By default True | Providing this the String will return in Proper structure
* @returns - `String`
*/
export /* Example usages of 'getCustomDayNameShort' are shown below:
shortOrFullFlag
? getCustomDayNameShort(lowerOrUpperFlag ? lowerOrUpperFlag : false)
: getCustomDayNameFull(lowerOrUpperFlag ? lowerOrUpperFlag : false);
*/
const getCustomDayNameShort = (
capsOnFlag?,
properCaseFlag?
) => {
const date = new Date();
const properCase = properCaseFlag === false ? false : true;
switch (date.getDay()) {
case 0:
return capsOnFlag ? "SUN" : properCase ? "Sun" : "sun";
case 1:
return capsOnFlag ? "MON" : properCase ? "Mon" : "mon";
case 2:
return capsOnFlag ? "TUE" : properCase ? "Tue" : "tue";
case 3:
return capsOnFlag ? "WED" : properCase ? "Wed" : "wed";
case 4:
return capsOnFlag ? "THU" : properCase ? "Thu" : "thu";
case 5:
return capsOnFlag ? "FRI" : properCase ? "Fri" : "fri";
case 6:
return capsOnFlag ? "SAT" : properCase ? "Sat" : "sat";
default:
return null;
}
};
/**
*
* @param capsOnFlag By default False | If Provide True then return the String in UpperCase else in LowerCase
* @param properCaseFlag By default True | Providing this the String will return in Proper structure
* @returns - `String`
*/
export /* Example usages of 'getCustomMonthNameFull' are shown below:
shortOrFullFlag
? getCustomMonthNameShort(lowerOrUpperFlag ? lowerOrUpperFlag : false)
: getCustomMonthNameFull(lowerOrUpperFlag ? lowerOrUpperFlag : false);
*/
const getCustomMonthNameFull = (
capsOnFlag?,
properCaseFlag?
) => {
const date = new Date();
const properCase = properCaseFlag === false ? false : true;
switch (date.getMonth()) {
case 0:
return capsOnFlag ? "JANUARY" : properCase ? "January" : "january";
case 1:
return capsOnFlag ? "FEBRUARY" : properCase ? "February" : "february";
case 2:
return capsOnFlag ? "MARCH" : properCase ? "March" : "march";
case 3:
return capsOnFlag ? "APRIL" : properCase ? "April" : "april";
case 4:
return capsOnFlag ? "MAY" : properCase ? "May" : "may";
case 5:
return capsOnFlag ? "JUNE" : properCase ? "June" : "june";
case 6:
return capsOnFlag ? "JULY" : properCase ? "July" : "july";
case 7:
return capsOnFlag ? "AUGUST" : properCase ? "August" : "august";
case 8:
return capsOnFlag ? "SEPTEMBER" : properCase ? "September" : "september";
case 9:
return capsOnFlag ? "OCTOBER" : properCase ? "October" : "october";
case 10:
return capsOnFlag ? "NOVEMBER" : properCase ? "November" : "november";
case 11:
return capsOnFlag ? "DECEMBER" : properCase ? "December" : "december";
default:
return null;
}
};
/**
*
* @param capsOnFlag By default False | If Provide True then return the String in UpperCase else in LowerCase
* @param properCaseFlag By default True | Providing this the String will return in Proper structure
* @returns - `String`
*/
export /* Example usages of 'getCustomMonthNameShort' are shown below:
shortOrFullFlag
? getCustomMonthNameShort(lowerOrUpperFlag ? lowerOrUpperFlag : false)
: getCustomMonthNameFull(lowerOrUpperFlag ? lowerOrUpperFlag : false);
*/
const getCustomMonthNameShort = (
capsOnFlag?,
properCaseFlag?
) => {
const date = new Date();
const properCase = properCaseFlag === false ? false : true;
switch (date.getMonth()) {
case 0:
return capsOnFlag ? "JAN" : properCase ? "Jan" : "jan";
case 1:
return capsOnFlag ? "FEB" : properCase ? "Feb" : "feb";
case 2:
return capsOnFlag ? "MAR" : properCase ? "Mar" : "mar";
case 3:
return capsOnFlag ? "APR" : properCase ? "Apr" : "apr";
case 4:
return capsOnFlag ? "MAY" : properCase ? "May" : "may";
case 5:
return capsOnFlag ? "JUN" : properCase ? "Jun" : "jun";
case 6:
return capsOnFlag ? "JUL" : properCase ? "Jul" : "jul";
case 7:
return capsOnFlag ? "AUG" : properCase ? "Aug" : "aug";
case 8:
return capsOnFlag ? "SEP" : properCase ? "Sep" : "sep";
case 9:
return capsOnFlag ? "OCT" : properCase ? "Oct" : "oct";
case 10:
return capsOnFlag ? "NOV" : properCase ? "Nov" : "nov";
case 11:
return capsOnFlag ? "DEC" : properCase ? "Dec" : "dec";
default:
return null;
}
};
/**
*
* @param changeToStringFlag Totally Optional if you need in String make true the flag else ignore
* @returns Today Date from (1 - 30 or 1 - 31) <= Default `Number` else you can change to `String`
*/
export /* Example usages of 'getCustomDate' are shown below:
getCustomDate();
*/
const getCustomDate = (
changeToStringFlag?
) => {
const d = new Date();
const date = d.getDate();
return date ? (changeToStringFlag ? String(date) : date) : null;
};
/**
*
* @param changeToStringFlag Totally Optional if you need in String make true the flag else ignore
* @returns Current hour in number (1 - 12) <= Default `Number` else you can change to `String`
*/
export /* Example usages of 'getCustomHour' are shown below:
getCustomHour();
*/
const getCustomHour = (
changeToStringFlag?
) => {
const d = new Date();
const hour = d.getHours() > 12 ? d.getHours() - 12 : d.getHours();
return hour === 0
? changeToStringFlag
? String(12)
: 12
: hour
? changeToStringFlag
? String(hour)
: hour
: null;
};
/**
*
* @param changeToStringFlag Totally Optional if you need in String make true the flag else ignore
* @returns Current minute in number (1 - 60) <= Default `Number` else you can change to `String`
*/
export /* Example usages of 'getCustomMinute' are shown below:
getCustomMinute();
*/
const getCustomMinute = (
changeToStringFlag?
) => {
const d = new Date();
const minute =
d.getMinutes() >= 10
? changeToStringFlag
? String(d.getMinutes())
: d.getMinutes()
: `0${d.getMinutes()}`;
return minute ? minute : null;
};
/**
*
* @param changeToStringFlag Totally Optional if you need in String make true the flag else ignore
* @returns Current minute in number (1 - 60) <= Default `Number` else you can change to `String`
*/
export /* Example usages of 'getCustomSecond' are shown below:
getCustomSecond();
*/
const getCustomSecond = (
changeToStringFlag?
) => {
const d = new Date();
const seconds =
d.getSeconds() >= 10
? changeToStringFlag
? String(d.getSeconds())
: d.getSeconds()
: `0${d.getSeconds()}`;
return seconds ? seconds : null;
};
/**
*
* @param capsOnFlag By default False | If Provide True then return the String in UpperCase else in LowerCase
* @returns `String` (Check `capsOnFlag` to return like AM or am | PM or pm)
*/
export /* Example usages of 'getCustomAmPm' are shown below:
getCustomAmPm(lowerOrUpperFlag ? lowerOrUpperFlag : false);
*/
const getCustomAmPm = (capsOnFlag) => {
const d = new Date();
const amPm = d.getHours() >= 12 ? "pm" : "am";
return amPm ? (capsOnFlag ? amPm.toUpperCase() : amPm) : null;
};
/**
*
* @param shortOrFullFlag By Default False which return the Day, Month in Short else Make True to return in Full
* @param lowerOrUpperFlag By Default False which return the Day, Month in lowerCase else Make True to return in UpperCase
* @returns The Full TimeStamp in `String` --> ( 10 OCT TUE 10:10AM - 10 Oct Tue 10:10am ) | ( 10 OCTOBER TUESDAY 10:10AM - 10 October Tuesday 10:10am )
*/
export const getCustomFullDateAndTimeWithAmPm = (
shortOrFullFlag?,
lowerOrUpperFlag?
) => {
const timeStamp = `${getCustomDate()} ${
shortOrFullFlag
? getCustomMonthNameShort(lowerOrUpperFlag ? lowerOrUpperFlag : false)
: getCustomMonthNameFull(lowerOrUpperFlag ? lowerOrUpperFlag : false)
} ${
shortOrFullFlag
? getCustomDayNameShort(lowerOrUpperFlag ? lowerOrUpperFlag : false)
: getCustomDayNameFull(lowerOrUpperFlag ? lowerOrUpperFlag : false)
} ${getCustomHour()}:${getCustomMinute()}${getCustomAmPm(
lowerOrUpperFlag ? lowerOrUpperFlag : false
)}`;
return timeStamp ? timeStamp : null;
};
/**
*
* @param shortOrFullFlag By Default False which return the Day, Month in Short else Make True to return in Full
* @param lowerOrUpperFlag By Default False which return the Day, Month in lowerCase else Make True to return in UpperCase
* @returns The Full TimeStamp in `String` --> ( 10 OCT TUE 10:10:00AM - 10 Oct Tue 10:10:00am ) | ( 10 OCTOBER TUESDAY 10:10:00AM - 10 October Tuesday 10:10:00am )
*/
export const getCustomFullDateAndTimeWithAmPmIncludingSeconds = (
shortOrFullFlag?,
lowerOrUpperFlag?
) => {
const timeStamp = `${getCustomDate()} ${
shortOrFullFlag
? getCustomMonthNameShort(lowerOrUpperFlag ? lowerOrUpperFlag : false)
: getCustomMonthNameFull(lowerOrUpperFlag ? lowerOrUpperFlag : false)
} ${
shortOrFullFlag
? getCustomDayNameShort(lowerOrUpperFlag ? lowerOrUpperFlag : false)
: getCustomDayNameFull(lowerOrUpperFlag ? lowerOrUpperFlag : false)
} ${getCustomHour()}:${getCustomMinute()}:${getCustomSecond()}${getCustomAmPm(
lowerOrUpperFlag ? lowerOrUpperFlag : false
)}`;
return timeStamp ? timeStamp : null;
};
|
27ecf3a59fc4dc53dca1af5135981c83f27b128f | 1,657 | ts | TypeScript | src/utils/date.ts | ka-fuachie/chronos | a0cb89738d803ce3f0a10ec41c3565970e5d28d4 | [
"MIT"
] | 1 | 2022-02-09T21:32:46.000Z | 2022-02-09T21:32:46.000Z | src/utils/date.ts | ka-fuachie/chronos | a0cb89738d803ce3f0a10ec41c3565970e5d28d4 | [
"MIT"
] | null | null | null | src/utils/date.ts | ka-fuachie/chronos | a0cb89738d803ce3f0a10ec41c3565970e5d28d4 | [
"MIT"
] | null | null | null | const DaysOfTheWeek = [
'Monday',
'Tuesday',
'Wednesday',
'Thursday',
'Friday',
'Saturday',
'Sunday',
]
const Months = [
'January',
'Febuary',
'March',
'April',
'May',
'June',
'July',
'August',
'September',
'October',
'November',
'December'
]
export function getDate(date: Date): number[] {
return [date.getDay(), date.getDate(), date.getMonth(), date.getFullYear()]
}
export function getTime(date: Date): number[] {
return [date.getHours(), date.getMinutes(), date.getSeconds()]
}
export function getFormattedDate(dateArr: number[]): string {
const [dayOfWeek, day, month, year] = dateArr
const dayOfWeekStr = DaysOfTheWeek[dayOfWeek - 1]
const dayStr = (function () {
let suffix: string
switch (day % 10) {
case 1:
suffix = 'st'
break;
case 2:
suffix = 'nd'
break;
case 3:
suffix = 'rd'
break;
default:
suffix = 'th'
break;
}
//Exception for 11, 12 and 13
if(day === 11 || day === 12 || day === 13 ){
suffix = 'th'
}
return `${day}${suffix}`
})()
const monthStr = Months[month]
return `${dayOfWeekStr}, ${dayStr} ${monthStr}, ${year}`
}
export function getFormattedTime(timeArr: number[]): string {
const [hours, minutes, seconds] = timeArr
let minuteStr: string
if (minutes < 10) {
minuteStr = `0${minutes}`
} else {
minuteStr = `${minutes}`
}
if (hours >= 12) {
return `${(hours - 12) || 12} ${minuteStr} ${'pm'}`
}
else if (hours > 0) {
return `${hours} ${minuteStr} ${'am'}`
}
else {
return `12 ${minuteStr} ${'am'}`
}
} | 18.829545 | 77 | 0.556427 | 74 | 5 | 0 | 4 | 9 | 0 | 1 | 0 | 8 | 0 | 0 | 12.4 | 531 | 0.016949 | 0.016949 | 0 | 0 | 0 | 0 | 0.444444 | 0.264783 | const DaysOfTheWeek = [
'Monday',
'Tuesday',
'Wednesday',
'Thursday',
'Friday',
'Saturday',
'Sunday',
]
const Months = [
'January',
'Febuary',
'March',
'April',
'May',
'June',
'July',
'August',
'September',
'October',
'November',
'December'
]
export /* Example usages of 'getDate' are shown below:
date.getDate();
*/
function getDate(date) {
return [date.getDay(), date.getDate(), date.getMonth(), date.getFullYear()]
}
export function getTime(date) {
return [date.getHours(), date.getMinutes(), date.getSeconds()]
}
export function getFormattedDate(dateArr) {
const [dayOfWeek, day, month, year] = dateArr
const dayOfWeekStr = DaysOfTheWeek[dayOfWeek - 1]
const dayStr = (function () {
let suffix
switch (day % 10) {
case 1:
suffix = 'st'
break;
case 2:
suffix = 'nd'
break;
case 3:
suffix = 'rd'
break;
default:
suffix = 'th'
break;
}
//Exception for 11, 12 and 13
if(day === 11 || day === 12 || day === 13 ){
suffix = 'th'
}
return `${day}${suffix}`
})()
const monthStr = Months[month]
return `${dayOfWeekStr}, ${dayStr} ${monthStr}, ${year}`
}
export function getFormattedTime(timeArr) {
const [hours, minutes, seconds] = timeArr
let minuteStr
if (minutes < 10) {
minuteStr = `0${minutes}`
} else {
minuteStr = `${minutes}`
}
if (hours >= 12) {
return `${(hours - 12) || 12} ${minuteStr} ${'pm'}`
}
else if (hours > 0) {
return `${hours} ${minuteStr} ${'am'}`
}
else {
return `12 ${minuteStr} ${'am'}`
}
} |
082d8395352b530dd0e85d72f0a5b74c68858c39 | 1,186 | ts | TypeScript | lingo3d/src/display/core/StaticObjectManager/applyMaterialProperties/copyMaterial.ts | lingo3d/lingo3d | 2c875d2f51e9df8388f37192a9ec0a63c18b9892 | [
"MIT"
] | 256 | 2022-02-28T10:23:22.000Z | 2022-03-31T17:05:50.000Z | lingo3d/src/display/core/StaticObjectManager/applyMaterialProperties/copyMaterial.ts | lingo3d/lingo3d | 2c875d2f51e9df8388f37192a9ec0a63c18b9892 | [
"MIT"
] | 7 | 2022-03-14T06:02:11.000Z | 2022-03-31T08:27:40.000Z | lingo3d/src/display/core/StaticObjectManager/applyMaterialProperties/copyMaterial.ts | lingo3d/lingo3d | 2c875d2f51e9df8388f37192a9ec0a63c18b9892 | [
"MIT"
] | 34 | 2022-02-28T10:41:12.000Z | 2022-03-31T10:38:47.000Z | const properties = [
"name",
"blending",
"side",
"vertexColors",
"opacity",
"transparent",
"blendSrc",
"blendDst",
"blendEquation",
"blendSrcAlpha",
"blendDstAlpha",
"blendEquationAlpha",
"depthFunc",
"depthTest",
"depthWrite",
"stencilWriteMask",
"stencilFunc",
"stencilRef",
"stencilFuncMask",
"stencilFail",
"stencilZFail",
"stencilZPass",
"stencilWrite",
"clipIntersection",
"clipShadows",
"shadowSide",
"colorWrite",
"precision",
"polygonOffset",
"polygonOffsetFactor",
"polygonOffsetUnits",
"dithering",
"alphaTest",
"alphaToCoverage",
"premultipliedAlpha",
"visible",
"toneMapped"
]
export default (from: any, to: any) => {
for (const prop of properties) {
const value = from[prop]
value != null && (to[prop] = value)
}
const srcPlanes = from.clippingPlanes
let dstPlanes = null
if (srcPlanes) {
const n = srcPlanes.length
dstPlanes = new Array(n)
for (let i = 0; i !== n; ++i)
dstPlanes[i] = srcPlanes[i].clone()
}
to.clippingPlanes = dstPlanes
} | 20.448276 | 47 | 0.574199 | 54 | 1 | 0 | 2 | 6 | 0 | 0 | 2 | 0 | 0 | 0 | 13 | 327 | 0.009174 | 0.018349 | 0 | 0 | 0 | 0.222222 | 0 | 0.247939 | const properties = [
"name",
"blending",
"side",
"vertexColors",
"opacity",
"transparent",
"blendSrc",
"blendDst",
"blendEquation",
"blendSrcAlpha",
"blendDstAlpha",
"blendEquationAlpha",
"depthFunc",
"depthTest",
"depthWrite",
"stencilWriteMask",
"stencilFunc",
"stencilRef",
"stencilFuncMask",
"stencilFail",
"stencilZFail",
"stencilZPass",
"stencilWrite",
"clipIntersection",
"clipShadows",
"shadowSide",
"colorWrite",
"precision",
"polygonOffset",
"polygonOffsetFactor",
"polygonOffsetUnits",
"dithering",
"alphaTest",
"alphaToCoverage",
"premultipliedAlpha",
"visible",
"toneMapped"
]
export default (from, to) => {
for (const prop of properties) {
const value = from[prop]
value != null && (to[prop] = value)
}
const srcPlanes = from.clippingPlanes
let dstPlanes = null
if (srcPlanes) {
const n = srcPlanes.length
dstPlanes = new Array(n)
for (let i = 0; i !== n; ++i)
dstPlanes[i] = srcPlanes[i].clone()
}
to.clippingPlanes = dstPlanes
} |
0853d1365a33244ce2232bcc7e51520121919175 | 3,488 | ts | TypeScript | sandpack-react/src/utils/stringUtils.ts | sophiebits/sandpack | 3c1cabea4abf68b9eac52f695e60c401ea5da201 | [
"Apache-2.0"
] | 1 | 2022-02-18T05:47:20.000Z | 2022-02-18T05:47:20.000Z | sandpack-react/src/utils/stringUtils.ts | sophiebits/sandpack | 3c1cabea4abf68b9eac52f695e60c401ea5da201 | [
"Apache-2.0"
] | 1 | 2022-02-18T02:21:22.000Z | 2022-02-18T02:21:22.000Z | sandpack-react/src/utils/stringUtils.ts | sophiebits/sandpack | 3c1cabea4abf68b9eac52f695e60c401ea5da201 | [
"Apache-2.0"
] | 1 | 2022-03-18T03:58:55.000Z | 2022-03-18T03:58:55.000Z | export const getFileName = (filePath: string): string => {
const lastIndexOfSlash = filePath.lastIndexOf("/");
return filePath.slice(lastIndexOfSlash + 1);
};
export const calculateNearestUniquePath = (
currentPath: string,
otherPaths: string[]
): string => {
const currentPathParts = (
currentPath[0] === "/" ? currentPath.slice(1) : currentPath
).split("/");
const resultPathParts: string[] = [];
// If path is on root, there are no parts to loop through
if (currentPathParts.length === 1) {
resultPathParts.unshift(currentPathParts[0]);
} else {
// Loop over all other paths to find a unique path
for (let fileIndex = 0; fileIndex < otherPaths.length; fileIndex++) {
// We go over each part of the path from end to start to find the closest unique directory
const otherPathParts = otherPaths[fileIndex].split("/");
for (
let partsFromEnd = 1;
partsFromEnd <= currentPathParts.length;
partsFromEnd++
) {
const currentPathPart =
currentPathParts[currentPathParts.length - partsFromEnd];
const otherPathPart =
otherPathParts[otherPathParts.length - partsFromEnd];
// If this part hasn't been added to the result path, we add it here
if (resultPathParts.length < partsFromEnd) {
resultPathParts.unshift(currentPathPart);
}
// If this part is different between the current path and other path we break
// as from this moment the current path is unique compared to this other path
if (currentPathPart !== otherPathPart) {
break;
}
}
}
}
// Add `..` if this is a relative path
if (resultPathParts.length < currentPathParts.length) {
resultPathParts.unshift("..");
}
// Join the result path parts into a path string
return resultPathParts.join("/");
};
export const hexToRGB = (
hex: string
): { red: number; green: number; blue: number } => {
let r = "0";
let g = "0";
let b = "0";
if (hex.length === 4) {
r = "0x" + hex[1] + hex[1];
g = "0x" + hex[2] + hex[2];
b = "0x" + hex[3] + hex[3];
} else if (hex.length === 7) {
r = "0x" + hex[1] + hex[2];
g = "0x" + hex[3] + hex[4];
b = "0x" + hex[5] + hex[6];
}
return {
red: +r,
green: +g,
blue: +b,
};
};
export const hexToCSSRGBa = (hex: string, alpha: number): string => {
if (hex.startsWith("#") && (hex.length === 4 || hex.length === 7)) {
const { red, green, blue } = hexToRGB(hex);
return `rgba(${red}, ${green}, ${blue}, ${alpha})`;
}
return hex;
};
// Checks both rgb and hex colors for contrast and returns true if the color is in the dark spectrum
export const isDarkColor = (color: string): boolean => {
let r = 0;
let g = 0;
let b = 0;
if (color.startsWith("#")) {
if (color.length < 7) {
return true;
}
r = parseInt(color.substr(1, 2), 16);
g = parseInt(color.substr(3, 2), 16);
b = parseInt(color.substr(5, 2), 16);
} else {
const rgbValues = color
.replace("rgb(", "")
.replace("rgba(", "")
.replace(")", "")
.split(",");
if (rgbValues.length < 3) {
return true;
}
r = parseInt(rgbValues[0], 10);
g = parseInt(rgbValues[1], 10);
b = parseInt(rgbValues[2], 10);
}
const yiq = (r * 299 + g * 587 + b * 114) / 1000;
return yiq < 128;
};
export const generateRandomId = (): string =>
Math.floor(Math.random() * 10000).toString();
| 28.357724 | 100 | 0.59031 | 97 | 6 | 0 | 7 | 23 | 0 | 1 | 0 | 16 | 0 | 0 | 13.5 | 1,053 | 0.012346 | 0.021842 | 0 | 0 | 0 | 0 | 0.444444 | 0.270003 | export const getFileName = (filePath) => {
const lastIndexOfSlash = filePath.lastIndexOf("/");
return filePath.slice(lastIndexOfSlash + 1);
};
export const calculateNearestUniquePath = (
currentPath,
otherPaths
) => {
const currentPathParts = (
currentPath[0] === "/" ? currentPath.slice(1) : currentPath
).split("/");
const resultPathParts = [];
// If path is on root, there are no parts to loop through
if (currentPathParts.length === 1) {
resultPathParts.unshift(currentPathParts[0]);
} else {
// Loop over all other paths to find a unique path
for (let fileIndex = 0; fileIndex < otherPaths.length; fileIndex++) {
// We go over each part of the path from end to start to find the closest unique directory
const otherPathParts = otherPaths[fileIndex].split("/");
for (
let partsFromEnd = 1;
partsFromEnd <= currentPathParts.length;
partsFromEnd++
) {
const currentPathPart =
currentPathParts[currentPathParts.length - partsFromEnd];
const otherPathPart =
otherPathParts[otherPathParts.length - partsFromEnd];
// If this part hasn't been added to the result path, we add it here
if (resultPathParts.length < partsFromEnd) {
resultPathParts.unshift(currentPathPart);
}
// If this part is different between the current path and other path we break
// as from this moment the current path is unique compared to this other path
if (currentPathPart !== otherPathPart) {
break;
}
}
}
}
// Add `..` if this is a relative path
if (resultPathParts.length < currentPathParts.length) {
resultPathParts.unshift("..");
}
// Join the result path parts into a path string
return resultPathParts.join("/");
};
export /* Example usages of 'hexToRGB' are shown below:
hexToRGB(hex);
*/
const hexToRGB = (
hex
) => {
let r = "0";
let g = "0";
let b = "0";
if (hex.length === 4) {
r = "0x" + hex[1] + hex[1];
g = "0x" + hex[2] + hex[2];
b = "0x" + hex[3] + hex[3];
} else if (hex.length === 7) {
r = "0x" + hex[1] + hex[2];
g = "0x" + hex[3] + hex[4];
b = "0x" + hex[5] + hex[6];
}
return {
red: +r,
green: +g,
blue: +b,
};
};
export const hexToCSSRGBa = (hex, alpha) => {
if (hex.startsWith("#") && (hex.length === 4 || hex.length === 7)) {
const { red, green, blue } = hexToRGB(hex);
return `rgba(${red}, ${green}, ${blue}, ${alpha})`;
}
return hex;
};
// Checks both rgb and hex colors for contrast and returns true if the color is in the dark spectrum
export const isDarkColor = (color) => {
let r = 0;
let g = 0;
let b = 0;
if (color.startsWith("#")) {
if (color.length < 7) {
return true;
}
r = parseInt(color.substr(1, 2), 16);
g = parseInt(color.substr(3, 2), 16);
b = parseInt(color.substr(5, 2), 16);
} else {
const rgbValues = color
.replace("rgb(", "")
.replace("rgba(", "")
.replace(")", "")
.split(",");
if (rgbValues.length < 3) {
return true;
}
r = parseInt(rgbValues[0], 10);
g = parseInt(rgbValues[1], 10);
b = parseInt(rgbValues[2], 10);
}
const yiq = (r * 299 + g * 587 + b * 114) / 1000;
return yiq < 128;
};
export const generateRandomId = () =>
Math.floor(Math.random() * 10000).toString();
|
088dbb6092dd01d7464a3400a133aa3854e24649 | 1,716 | ts | TypeScript | lib/utils/anime.ts | cvrlnolan/myanime | 503293a21c9a238169f4b78f8ee3e096b9594eef | [
"MIT"
] | null | null | null | lib/utils/anime.ts | cvrlnolan/myanime | 503293a21c9a238169f4b78f8ee3e096b9594eef | [
"MIT"
] | 21 | 2022-01-02T10:17:38.000Z | 2022-03-21T08:19:14.000Z | lib/utils/anime.ts | cvrlnolan/myanime | 503293a21c9a238169f4b78f8ee3e096b9594eef | [
"MIT"
] | null | null | null | export function animeStatus(status: number): string {
if (status === 0) {
return "Finished";
}
if (status === 1) {
return "Ongoing";
}
if (status === 2) {
return "Not Yet Released";
}
if (status === 3) {
return "Cancelled";
}
return "Unknown";
}
export function animeScore(score: number): string {
if (0 < score && score < 49) {
return "text-red-600";
}
if (49 < score && score < 59) {
return "text-amber-600";
}
if (59 < score && score < 79) {
return "text-lime-600";
}
if (79 < score && score <= 100) {
return "text-emerald-600";
}
return "text-gray-600";
}
export function animeFormat(format: number): string {
if (format === 0) {
return "TV Show";
}
if (format === 1) {
return "TV_SHORT";
}
if (format === 2) {
return "Movie";
}
if (format === 3) {
return "Special";
}
if (format === 4) {
return "OVA";
}
if (format === 5) {
return "ONA";
}
if (format === 6) {
return "Music";
}
return "Unknown";
}
export function animeEpisodes(episodes: number): string {
if (episodes === 1) {
return "";
}
return episodes + " episodes";
}
export function animeGenres(genres: any[]): any[] {
if (genres.length > 3) {
let featuredGenres = genres.sort().splice(0, 3);
return featuredGenres;
}
return genres.sort();
}
export function animeSeason(season: number): string {
if (season === 0) {
return "Winter";
}
if (season === 1) {
return "Spring";
}
if (season === 2) {
return "Summer";
}
if (season === 3) {
return "Fall";
}
return "Unknown";
}
export function animeEpDuration(duration: number): string {
return duration + " minutes";
}
| 18.652174 | 59 | 0.560606 | 85 | 7 | 0 | 7 | 1 | 0 | 0 | 2 | 12 | 0 | 0 | 10.142857 | 570 | 0.024561 | 0.001754 | 0 | 0 | 0 | 0.133333 | 0.8 | 0.230103 | export function animeStatus(status) {
if (status === 0) {
return "Finished";
}
if (status === 1) {
return "Ongoing";
}
if (status === 2) {
return "Not Yet Released";
}
if (status === 3) {
return "Cancelled";
}
return "Unknown";
}
export function animeScore(score) {
if (0 < score && score < 49) {
return "text-red-600";
}
if (49 < score && score < 59) {
return "text-amber-600";
}
if (59 < score && score < 79) {
return "text-lime-600";
}
if (79 < score && score <= 100) {
return "text-emerald-600";
}
return "text-gray-600";
}
export function animeFormat(format) {
if (format === 0) {
return "TV Show";
}
if (format === 1) {
return "TV_SHORT";
}
if (format === 2) {
return "Movie";
}
if (format === 3) {
return "Special";
}
if (format === 4) {
return "OVA";
}
if (format === 5) {
return "ONA";
}
if (format === 6) {
return "Music";
}
return "Unknown";
}
export function animeEpisodes(episodes) {
if (episodes === 1) {
return "";
}
return episodes + " episodes";
}
export function animeGenres(genres) {
if (genres.length > 3) {
let featuredGenres = genres.sort().splice(0, 3);
return featuredGenres;
}
return genres.sort();
}
export function animeSeason(season) {
if (season === 0) {
return "Winter";
}
if (season === 1) {
return "Spring";
}
if (season === 2) {
return "Summer";
}
if (season === 3) {
return "Fall";
}
return "Unknown";
}
export function animeEpDuration(duration) {
return duration + " minutes";
}
|
08be4619c4b3f45e21e4b981b8596e78d2674e11 | 3,095 | ts | TypeScript | src/util/strings.ts | hoamockim/authentication | 4be8caf72f08aa3797a1b418fcea65e053e533e7 | [
"Apache-2.0"
] | 1 | 2022-03-18T10:22:46.000Z | 2022-03-18T10:22:46.000Z | src/util/strings.ts | hoamockim/authentication | 4be8caf72f08aa3797a1b418fcea65e053e533e7 | [
"Apache-2.0"
] | null | null | null | src/util/strings.ts | hoamockim/authentication | 4be8caf72f08aa3797a1b418fcea65e053e533e7 | [
"Apache-2.0"
] | null | null | null | export default class StringUtil {
static stripAcents(input:string): string {
const source: string[] = [
"À", "Á", "Â", "Ã", "È", "É",
"Ê", "Ì", "Í", "Ò", "Ó", "Ô", "Õ", "Ù", "Ú", "Ý", "à", "á", "â",
"ã", "è", "é", "ê", "ì", "í", "ò", "ó", "ô", "õ", "ù", "ú", "ý",
"Ă", "ă", "Đ", "đ", "Ĩ", "ĩ", "Ũ", "ũ", "Ơ", "ơ", "Ư", "ư", "Ạ",
"ạ", "Ả", "ả", "Ấ", "ấ", "Ầ", "ầ", "Ẩ", "ẩ", "Ẫ", "ẫ", "Ậ", "ậ",
"Ắ", "ắ", "Ằ", "ằ", "Ẳ", "ẳ", "Ẵ", "ẵ", "Ặ", "ặ", "Ẹ", "ẹ", "Ẻ",
"ẻ", "Ẽ", "ẽ", "Ế", "ế", "Ề", "ề", "Ể", "ể", "Ễ", "ễ", "Ệ", "ệ",
"Ỉ", "ỉ", "Ị", "ị", "Ọ", "ọ", "Ỏ", "ỏ", "Ố", "ố", "Ồ", "ồ", "Ổ",
"ổ", "Ỗ", "ỗ", "Ộ", "ộ", "Ớ", "ớ", "Ờ", "ờ", "Ở", "ở", "Ỡ", "ỡ",
"Ợ", "ợ", "Ụ", "ụ", "Ủ", "ủ", "Ứ", "ứ", "Ừ", "ừ", "Ử", "ử", "Ữ",
"ữ", "Ự", "ự", "ý", "ỳ", "ỷ", "ỹ", "ỵ", "Ý", "Ỳ", "Ỷ", "Ỹ", "Ỵ"
];
const dist: string[] = [
"A", "A", "A", "A", "E",
"E", "E", "I", "I", "O", "O", "O", "O", "U", "U", "Y", "a", "a",
"a", "a", "e", "e", "e", "i", "i", "o", "o", "o", "o", "u", "u",
"y", "A", "a", "D", "d", "I", "i", "U", "u", "O", "o", "U", "u",
"A", "a", "A", "a", "A", "a", "A", "a", "A", "a", "A", "a", "A",
"a", "A", "a", "A", "a", "A", "a", "A", "a", "A", "a", "E", "e",
"E", "e", "E", "e", "E", "e", "E", "e", "E", "e", "E", "e", "E",
"e", "I", "i", "I", "i", "O", "o", "O", "o", "O", "o", "O", "o",
"O", "o", "O", "o", "O", "o", "O", "o", "O", "o", "O", "o", "O",
"o", "O", "o", "U", "u", "U", "u", "U", "u", "U", "u", "U", "u",
"U", "u", "U", "u", "y", "y", "y", "y", "y", "Y", "Y", "Y", "Y", "Y"
];
let result = input;
for(let i = 0; i< source.length; i++){
result = result.replace(source[i], dist[i]);
}
return result
};
static generateRandom(n: number): string {
const letters = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz" ;
let result = "" ;
for( let i = 0; i < n; i++ ){
let rd = Math.floor(Math.random() * letters.length);
if (rd < letters.length)
result += letters[rd];
}
return result;
};
static mask(input: string, start: number): string {
if (input.length <= start + 5) {
return input.substring(0,1) + "******" + input.substring(input.length-1,input.length)
}
return input.substring(0,start) +
"********" +
input.substring(input.length-3,input.length)
}
static isValidPassWord(pwd: string): boolean {
return new RegExp(/^(?=.*[a-z])(?=.*[A-Z])(?=.*[0-9])(?=.*[!@#\$%\^&\*]).{8,}$/).test(pwd)
}
static isValidEmail(email: string): boolean {
return new RegExp(/^(([^<>()\[\]\\.,;:\s@"]+(\.[^<>()\[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/).test(email)
}
}
| 45.514706 | 191 | 0.318901 | 59 | 5 | 0 | 6 | 8 | 0 | 0 | 0 | 13 | 1 | 0 | 9.4 | 1,403 | 0.00784 | 0.005702 | 0 | 0.000713 | 0 | 0 | 0.684211 | 0.207277 | export default class StringUtil {
static stripAcents(input) {
const source = [
"À", "Á", "Â", "Ã", "È", "É",
"Ê", "Ì", "Í", "Ò", "Ó", "Ô", "Õ", "Ù", "Ú", "Ý", "à", "á", "â",
"ã", "è", "é", "ê", "ì", "í", "ò", "ó", "ô", "õ", "ù", "ú", "ý",
"Ă", "ă", "Đ", "đ", "Ĩ", "ĩ", "Ũ", "ũ", "Ơ", "ơ", "Ư", "ư", "Ạ",
"ạ", "Ả", "ả", "Ấ", "ấ", "Ầ", "ầ", "Ẩ", "ẩ", "Ẫ", "ẫ", "Ậ", "ậ",
"Ắ", "ắ", "Ằ", "ằ", "Ẳ", "ẳ", "Ẵ", "ẵ", "Ặ", "ặ", "Ẹ", "ẹ", "Ẻ",
"ẻ", "Ẽ", "ẽ", "Ế", "ế", "Ề", "ề", "Ể", "ể", "Ễ", "ễ", "Ệ", "ệ",
"Ỉ", "ỉ", "Ị", "ị", "Ọ", "ọ", "Ỏ", "ỏ", "Ố", "ố", "Ồ", "ồ", "Ổ",
"ổ", "Ỗ", "ỗ", "Ộ", "ộ", "Ớ", "ớ", "Ờ", "ờ", "Ở", "ở", "Ỡ", "ỡ",
"Ợ", "ợ", "Ụ", "ụ", "Ủ", "ủ", "Ứ", "ứ", "Ừ", "ừ", "Ử", "ử", "Ữ",
"ữ", "Ự", "ự", "ý", "ỳ", "ỷ", "ỹ", "ỵ", "Ý", "Ỳ", "Ỷ", "Ỹ", "Ỵ"
];
const dist = [
"A", "A", "A", "A", "E",
"E", "E", "I", "I", "O", "O", "O", "O", "U", "U", "Y", "a", "a",
"a", "a", "e", "e", "e", "i", "i", "o", "o", "o", "o", "u", "u",
"y", "A", "a", "D", "d", "I", "i", "U", "u", "O", "o", "U", "u",
"A", "a", "A", "a", "A", "a", "A", "a", "A", "a", "A", "a", "A",
"a", "A", "a", "A", "a", "A", "a", "A", "a", "A", "a", "E", "e",
"E", "e", "E", "e", "E", "e", "E", "e", "E", "e", "E", "e", "E",
"e", "I", "i", "I", "i", "O", "o", "O", "o", "O", "o", "O", "o",
"O", "o", "O", "o", "O", "o", "O", "o", "O", "o", "O", "o", "O",
"o", "O", "o", "U", "u", "U", "u", "U", "u", "U", "u", "U", "u",
"U", "u", "U", "u", "y", "y", "y", "y", "y", "Y", "Y", "Y", "Y", "Y"
];
let result = input;
for(let i = 0; i< source.length; i++){
result = result.replace(source[i], dist[i]);
}
return result
};
static generateRandom(n) {
const letters = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz" ;
let result = "" ;
for( let i = 0; i < n; i++ ){
let rd = Math.floor(Math.random() * letters.length);
if (rd < letters.length)
result += letters[rd];
}
return result;
};
static mask(input, start) {
if (input.length <= start + 5) {
return input.substring(0,1) + "******" + input.substring(input.length-1,input.length)
}
return input.substring(0,start) +
"********" +
input.substring(input.length-3,input.length)
}
static isValidPassWord(pwd) {
return new RegExp(/^(?=.*[a-z])(?=.*[A-Z])(?=.*[0-9])(?=.*[!@#\$%\^&\*]).{8,}$/).test(pwd)
}
static isValidEmail(email) {
return new RegExp(/^(([^<>()\[\]\\.,;:\s@"]+(\.[^<>()\[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/).test(email)
}
}
|
611371b48316e912ee26c8611bb81bbc509c32ca | 2,340 | ts | TypeScript | src/formatters.ts | yuvipanda/jupyterlab-limit-output | 23de43278f8623b33eebbc50252663d8d5e37e70 | [
"BSD-3-Clause"
] | 2 | 2022-03-07T10:47:28.000Z | 2022-03-08T08:04:46.000Z | src/formatters.ts | yuvipanda/jupyterlab-limit-output | 23de43278f8623b33eebbc50252663d8d5e37e70 | [
"BSD-3-Clause"
] | null | null | null | src/formatters.ts | yuvipanda/jupyterlab-limit-output | 23de43278f8623b33eebbc50252663d8d5e37e70 | [
"BSD-3-Clause"
] | 1 | 2022-02-23T07:48:48.000Z | 2022-02-23T07:48:48.000Z | const NEW_LINE = '\n';
const SPACER = '\n\n\n';
/**
* Return a string with at most head starting characters and tail ending (plus a warning)
*/
export const limitByCharacters = (
text: string,
head: number,
tail: number
): string => {
const maxChars = head + tail;
if (text.length > maxChars) {
const headstr = text.substring(0, head);
const tailstr = text.substring(text.length - tail);
let msg = '';
if (head) {
msg = ` first ${head}`;
}
if (tail) {
msg += `${head ? ' and' : ''} last ${tail}`;
}
return `${headstr}${
head ? SPACER : ''
}WARNING: Output limited. Showing${msg} characters.${
tail ? SPACER : ''
}${tailstr}`;
}
return text;
};
/**
* Find the nth index of the newline character
*/
function _nthNewLineIndex(text: string, n: number): number | null {
let idx = 0;
while (n-- > 0 && idx++ < text.length) {
idx = text.indexOf(NEW_LINE, idx);
// Not found before we ran out of n
if (idx < 0) {
return null;
}
}
return idx;
}
/**
* Find the nth newline from the end of the string (excluding a possible final new line)
*/
function _nthNewLineFromLastIndex(text: string, n: number): number | null {
let idx = text.length - 1; // Ignore a possible final trailing \n
while (n-- > 0 && idx-- >= 0) {
idx = text.lastIndexOf(NEW_LINE, idx);
// Not found before we ran out of n
if (idx < 0) {
return null;
}
}
return idx;
}
/**
* Return a string with at most head starting lines and tail ending (plus a warning)
*/
export const limitByLines = (
text: string,
head: number,
tail: number
): string => {
const headEndPos = head > 0 ? _nthNewLineIndex(text, head) : -1;
if (headEndPos === null) {
return text;
}
const tailStartPos =
tail > 0 ? _nthNewLineFromLastIndex(text, tail) : text.length;
if (tailStartPos === null) {
return text;
}
if (tailStartPos <= headEndPos) {
return text;
}
const headstr = text.substring(0, headEndPos);
const tailstr = text.substring(tailStartPos);
let msg = '';
if (head) {
msg = ` first ${head}`;
}
if (tail) {
msg += `${head ? ' and' : ''} last ${tail}`;
}
return `${headstr}${
head ? SPACER : ''
}WARNING: Output limited. Showing${msg} lines.${
tail ? SPACER : ''
}${tailstr}`;
};
| 24.123711 | 89 | 0.589316 | 78 | 4 | 0 | 10 | 15 | 0 | 2 | 0 | 14 | 0 | 0 | 15 | 720 | 0.019444 | 0.020833 | 0 | 0 | 0 | 0 | 0.482759 | 0.283537 | const NEW_LINE = '\n';
const SPACER = '\n\n\n';
/**
* Return a string with at most head starting characters and tail ending (plus a warning)
*/
export const limitByCharacters = (
text,
head,
tail
) => {
const maxChars = head + tail;
if (text.length > maxChars) {
const headstr = text.substring(0, head);
const tailstr = text.substring(text.length - tail);
let msg = '';
if (head) {
msg = ` first ${head}`;
}
if (tail) {
msg += `${head ? ' and' : ''} last ${tail}`;
}
return `${headstr}${
head ? SPACER : ''
}WARNING: Output limited. Showing${msg} characters.${
tail ? SPACER : ''
}${tailstr}`;
}
return text;
};
/**
* Find the nth index of the newline character
*/
/* Example usages of '_nthNewLineIndex' are shown below:
head > 0 ? _nthNewLineIndex(text, head) : -1;
*/
function _nthNewLineIndex(text, n) {
let idx = 0;
while (n-- > 0 && idx++ < text.length) {
idx = text.indexOf(NEW_LINE, idx);
// Not found before we ran out of n
if (idx < 0) {
return null;
}
}
return idx;
}
/**
* Find the nth newline from the end of the string (excluding a possible final new line)
*/
/* Example usages of '_nthNewLineFromLastIndex' are shown below:
tail > 0 ? _nthNewLineFromLastIndex(text, tail) : text.length;
*/
function _nthNewLineFromLastIndex(text, n) {
let idx = text.length - 1; // Ignore a possible final trailing \n
while (n-- > 0 && idx-- >= 0) {
idx = text.lastIndexOf(NEW_LINE, idx);
// Not found before we ran out of n
if (idx < 0) {
return null;
}
}
return idx;
}
/**
* Return a string with at most head starting lines and tail ending (plus a warning)
*/
export const limitByLines = (
text,
head,
tail
) => {
const headEndPos = head > 0 ? _nthNewLineIndex(text, head) : -1;
if (headEndPos === null) {
return text;
}
const tailStartPos =
tail > 0 ? _nthNewLineFromLastIndex(text, tail) : text.length;
if (tailStartPos === null) {
return text;
}
if (tailStartPos <= headEndPos) {
return text;
}
const headstr = text.substring(0, headEndPos);
const tailstr = text.substring(tailStartPos);
let msg = '';
if (head) {
msg = ` first ${head}`;
}
if (tail) {
msg += `${head ? ' and' : ''} last ${tail}`;
}
return `${headstr}${
head ? SPACER : ''
}WARNING: Output limited. Showing${msg} lines.${
tail ? SPACER : ''
}${tailstr}`;
};
|
613c7e4f1af6683ffc402f1d62f87d50bc024185 | 11,246 | ts | TypeScript | libs/imagery/projection/BaiduMercatorProjection.ts | ts-gis/ts-cesium-lib | 6937e7d905037d3555bbcfe7561867b5a23f13fe | [
"Apache-2.0"
] | 1 | 2022-01-06T01:21:31.000Z | 2022-01-06T01:21:31.000Z | libs/imagery/projection/BaiduMercatorProjection.ts | ts-gis/ts-cesium-lib | 6937e7d905037d3555bbcfe7561867b5a23f13fe | [
"Apache-2.0"
] | null | null | null | libs/imagery/projection/BaiduMercatorProjection.ts | ts-gis/ts-cesium-lib | 6937e7d905037d3555bbcfe7561867b5a23f13fe | [
"Apache-2.0"
] | null | null | null | const EARTH_RADIUS = 6370996.81
const MC_BAND = [12890594.86, 8362377.87, 5591021, 3481989.83, 1678043.12, 0]
const LL_BAND = [75, 60, 45, 30, 15, 0]
const MC2LL = [
[
1.410526172116255e-8,
8.98305509648872e-6,
-1.9939833816331,
2.009824383106796e2,
-1.872403703815547e2,
91.6087516669843,
-23.38765649603339,
2.57121317296198,
-0.03801003308653,
1.73379812e7
],
[
-7.435856389565537e-9,
8.983055097726239e-6,
-0.78625201886289,
96.32687599759846,
-1.85204757529826,
-59.36935905485877,
47.40033549296737,
-16.50741931063887,
2.28786674699375,
1.026014486e7
],
[
-3.030883460898826e-8,
8.98305509983578e-6,
0.30071316287616,
59.74293618442277,
7.357984074871,
-25.38371002664745,
13.45380521110908,
-3.29883767235584,
0.32710905363475,
6.85681737e6
],
[
-1.981981304930552e-8,
8.983055099779535e-6,
0.03278182852591,
40.31678527705744,
0.65659298677277,
-4.44255534477492,
0.85341911805263,
0.12923347998204,
-0.04625736007561,
4.48277706e6
],
[
3.09191371068437e-9,
8.983055096812155e-6,
0.00006995724062,
23.10934304144901,
-0.00023663490511,
-0.6321817810242,
-0.00663494467273,
0.03430082397953,
-0.00466043876332,
2.5551644e6
],
[
2.890871144776878e-9,
8.983055095805407e-6,
-0.00000003068298,
7.47137025468032,
-0.00000353937994,
-0.02145144861037,
-0.00001234426596,
0.00010322952773,
-0.00000323890364,
8.260885e5
]
]
const LL2MC = [
[
-0.0015702102444,
1.113207020616939e5,
1.704480524535203e15,
-1.033898737604234e16,
2.611266785660388e16,
-3.51496691766537e16,
2.659570071840392e16,
-1.072501245418824e16,
1.800819912950474e15,
82.5
],
[
8.277824516172526e-4,
1.113207020463578e5,
6.477955746671608e8,
-4.082003173641316e9,
1.077490566351142e10,
-1.517187553151559e10,
1.205306533862167e10,
-5.124939663577472e9,
9.133119359512032e8,
67.5
],
[
0.00337398766765,
1.113207020202162e5,
4.481351045890365e6,
-2.339375119931662e7,
7.968221547186455e7,
-1.159649932797253e8,
9.723671115602145e7,
-4.366194633752821e7,
8.477230501135234e6,
52.5
],
[
0.00220636496208,
1.113207020209128e5,
5.175186112841131e4,
3.796837749470245e6,
9.920137397791013e5,
-1.22195221711287e6,
1.340652697009075e6,
-6.209436990984312e5,
1.444169293806241e5,
37.5
],
[
-3.441963504368392e-4,
1.113207020576856e5,
2.782353980772752e2,
2.485758690035394e6,
6.070750963243378e3,
5.482118345352118e4,
9.540606633304236e3,
-2.71055326746645e3,
1.405483844121726e3,
22.5
],
[
-3.218135878613132e-4,
1.113207020701615e5,
0.00369383431289,
8.237256402795718e5,
0.46104986909093,
2.351343141331292e3,
1.58060784298199,
8.77738589078284,
0.37238884252424,
7.45
]
]
type LngLatPoint = {
lng: number;
lat: number;
}
class BaiduMercatorProjection {
isWgs84: boolean;
constructor() {
this.isWgs84 = false
}
/**
*
* @param point1
* @param point2
* @returns {number}
*/
getDistanceByMC(point1: LngLatPoint, point2: LngLatPoint) {
if (!point1 || !point2) {
return 0
}
point1 = this.convertMC2LL(point1)
if (!point1) {
return 0
}
let x1 = this.toRadians(point1['lng'])
let y1 = this.toRadians(point1['lat'])
point2 = this.convertMC2LL(point2)
if (!point2) {
return 0
}
let x2 = this.toRadians(point2['lng'])
let y2 = this.toRadians(point2['lat'])
return this.getDistance(x1, x2, y1, y2)
}
/**
* Calculate the distance between two points according to the latitude and longitude coordinates
* @param point1
* @param point2
* @returns {number|*}
*/
getDistanceByLL(point1: LngLatPoint, point2: LngLatPoint) {
if (!point1 || !point2) {
return 0
}
point1['lng'] = this.getLoop(point1['lng'], -180, 180)
point1['lat'] = this.getRange(point1['lat'], -74, 74)
point2['lng'] = this.getLoop(point2['lng'], -180, 180)
point2['lat'] = this.getRange(point2['lat'], -74, 74)
let x1 = this.toRadians(point1['lng'])
let y1 = this.toRadians(point1['lat'])
let x2 = this.toRadians(point2['lng'])
let y2 = this.toRadians(point2['lat'])
return this.getDistance(x1, x2, y1, y2)
}
/**
* The plane cartesian coordinates are converted to latitude and longitude coordinates
* @param point
* @returns {Point|{lng: number, lat: number}}
*/
convertMC2LL(point: LngLatPoint) {
if (!point) {
return { lng: 0, lat: 0 }
}
let lnglat = { lng: 0, lat: 0 };
if (this.isWgs84) {
lnglat.lng = (point.lng / 20037508.34) * 180
let mmy = (point.lat / 20037508.34) * 180
lnglat.lat =
(180 / Math.PI) *
(2 * Math.atan(Math.exp((mmy * Math.PI) / 180)) - Math.PI / 2)
return {
lng: lnglat['lng'],
lat: lnglat['lat']
}
}
let temp = {
lng: Math.abs(point['lng']),
lat: Math.abs(point['lat'])
}
let factor: number[] = [];
for (let i = 0; i < MC_BAND.length; i++) {
if (temp['lat'] >= MC_BAND[i]) {
factor = MC2LL[i]
break
}
}
lnglat = this.convertor(point, factor)
return {
lng: lnglat['lng'],
lat: lnglat['lat']
}
}
/**
* The latitude and longitude coordinates are converted to plane cartesian coordinates
* @param point
* @returns {{lng: number, lat: number}|*}
*/
convertLL2MC(point: LngLatPoint) {
if (!point) {
return { lng: 0, lat: 0 }
}
if (
point['lng'] > 180 ||
point['lng'] < -180 ||
point['lat'] > 90 ||
point['lat'] < -90
) {
return point
}
if (this.isWgs84) {
let mercator = { lng: 0, lat: 0 };
let earthRad = 6378137.0
mercator.lng = ((point.lng * Math.PI) / 180) * earthRad
let a = (point.lat * Math.PI) / 180
mercator.lat =
(earthRad / 2) * Math.log((1.0 + Math.sin(a)) / (1.0 - Math.sin(a)))
return {
lng: parseFloat(mercator['lng'].toFixed(2)),
lat: parseFloat(mercator['lat'].toFixed(2))
}
}
point['lng'] = this.getLoop(point['lng'], -180, 180)
point['lat'] = this.getRange(point['lat'], -74, 74)
let temp = { lng: point['lng'], lat: point['lat'] }
let factor: number[] = [];
for (let i = 0; i < LL_BAND.length; i++) {
if (temp['lat'] >= LL_BAND[i]) {
factor = LL2MC[i]
break
}
}
if (!factor) {
for (let i = 0; i < LL_BAND.length; i++) {
if (temp['lat'] <= -LL_BAND[i]) {
factor = LL2MC[i]
break
}
}
}
let mc = this.convertor(point, factor)
return {
lng: parseFloat(mc['lng'].toFixed(2)),
lat: parseFloat(mc['lat'].toFixed(2))
}
}
/**
*
* @param fromPoint
* @param factor
* @returns {{lng: *, lat: *}}
*/
convertor(fromPoint: LngLatPoint, factor: number[]) {
if (!fromPoint || !factor) {
return { lng: 0, lat: 0 }
}
let x = factor[0] + factor[1] * Math.abs(fromPoint['lng'])
let temp = Math.abs(fromPoint['lat']) / factor[9]
let y =
factor[2] +
factor[3] * temp +
factor[4] * temp * temp +
factor[5] * temp * temp * temp +
factor[6] * temp * temp * temp * temp +
factor[7] * temp * temp * temp * temp * temp +
factor[8] * temp * temp * temp * temp * temp * temp
x *= fromPoint['lng'] < 0 ? -1 : 1
y *= fromPoint['lat'] < 0 ? -1 : 1
return {
lng: x,
lat: y
}
}
/**
*
* @param x1
* @param x2
* @param y1
* @param y2
* @returns {number}
*/
getDistance(x1: number, x2: number, y1: number, y2: number): number {
return (
EARTH_RADIUS *
Math.acos(
Math.sin(y1) * Math.sin(y2) +
Math.cos(y1) * Math.cos(y2) * Math.cos(x2 - x1)
)
)
}
/**
*
* @param deg
* @returns {number}
*/
toRadians(deg: number): number {
return (Math.PI * deg) / 180
}
/**
*
* @param rad
* @returns {number}
*/
toDegrees(rad: number): number {
return (180 * rad) / Math.PI
}
/**
*
* @param v
* @param a
* @param b
* @returns {number}
*/
getRange(v: number, a: number, b: number): number {
if (a != null) {
v = Math.max(v, a)
}
if (b != null) {
v = Math.min(v, b)
}
return v
}
/**
*
* @param v
* @param a
* @param b
* @returns {*}
*/
getLoop(v: number, a: number, b: number): number {
while (v > b) {
v -= b - a
}
while (v < a) {
v += b - a
}
return v
}
/**
*
* @param point
* @returns {{lng: number, lat: number}|*}
*/
lngLatToMercator(point: LngLatPoint) {
return this.convertLL2MC(point)
}
/**
*
* @param point
* @returns {{x: (number|*), y: (number|*)}}
*/
lngLatToPoint(point: LngLatPoint) {
let mercator = this.convertLL2MC(point)
return {
x: mercator['lng'],
y: mercator['lat']
}
}
/**
* WebMercator transforms to latitude and longitude
* @param point
* @returns {Point|{lng: number, lat: number}}
*/
mercatorToLngLat(point: LngLatPoint) {
return this.convertMC2LL(point)
}
/**
*
* @param point
* @returns {Point|{lng: number, lat: number}}
*/
pointToLngLat(point: LngLatPoint) {
let mercator = { lng: point.lng, lat: point.lat }
return this.convertMC2LL(mercator)
}
/**
* Latitude and longitude coordinates transforms to pixel coordinates
* @param point
* @param zoom
* @param mapCenter
* @param mapSize
* @returns {{x: number, y: number}}
*/
pointToPixel(point: LngLatPoint, zoom: number, mapCenter: LngLatPoint, mapSize: { width: number, height: number }) {
if (!point) {
return { x: 0, y: 0 }
}
point = this.lngLatToMercator(point)
let zoomUnits = this.getZoomUnits(zoom)
let x = Math.round(
(point['lng'] - mapCenter['lng']) / zoomUnits + mapSize.width / 2
)
let y = Math.round(
(mapCenter['lat'] - point['lat']) / zoomUnits + mapSize.height / 2
)
return { x, y }
}
/**
* Pixel coordinates transforms to latitude and longitude coordinates
* @param pixel
* @param zoom
* @param mapCenter
* @param mapSize
* @returns {Point|{lng: number, lat: number}}
*/
pixelToPoint(pixel: { x: number, y: number }, zoom: number, mapCenter: LngLatPoint, mapSize: { width: number, height: number }) {
if (!pixel) {
return { lng: 0, lat: 0 }
}
let zoomUnits = this.getZoomUnits(zoom)
let lng = mapCenter['lng'] + zoomUnits * (pixel.x - mapSize.width / 2)
let lat = mapCenter['lat'] - zoomUnits * (pixel.y - mapSize.height / 2)
let point = { lng, lat }
return this.mercatorToLngLat(point)
}
/**
*
* @param zoom
* @returns {number}
*/
getZoomUnits(zoom: number) {
return Math.pow(2, 18 - zoom)
}
}
export default BaiduMercatorProjection | 22.447106 | 131 | 0.571937 | 373 | 18 | 0 | 33 | 38 | 3 | 10 | 0 | 32 | 2 | 0 | 9.888889 | 5,227 | 0.009757 | 0.00727 | 0.000574 | 0.000383 | 0 | 0 | 0.347826 | 0.219346 | const EARTH_RADIUS = 6370996.81
const MC_BAND = [12890594.86, 8362377.87, 5591021, 3481989.83, 1678043.12, 0]
const LL_BAND = [75, 60, 45, 30, 15, 0]
const MC2LL = [
[
1.410526172116255e-8,
8.98305509648872e-6,
-1.9939833816331,
2.009824383106796e2,
-1.872403703815547e2,
91.6087516669843,
-23.38765649603339,
2.57121317296198,
-0.03801003308653,
1.73379812e7
],
[
-7.435856389565537e-9,
8.983055097726239e-6,
-0.78625201886289,
96.32687599759846,
-1.85204757529826,
-59.36935905485877,
47.40033549296737,
-16.50741931063887,
2.28786674699375,
1.026014486e7
],
[
-3.030883460898826e-8,
8.98305509983578e-6,
0.30071316287616,
59.74293618442277,
7.357984074871,
-25.38371002664745,
13.45380521110908,
-3.29883767235584,
0.32710905363475,
6.85681737e6
],
[
-1.981981304930552e-8,
8.983055099779535e-6,
0.03278182852591,
40.31678527705744,
0.65659298677277,
-4.44255534477492,
0.85341911805263,
0.12923347998204,
-0.04625736007561,
4.48277706e6
],
[
3.09191371068437e-9,
8.983055096812155e-6,
0.00006995724062,
23.10934304144901,
-0.00023663490511,
-0.6321817810242,
-0.00663494467273,
0.03430082397953,
-0.00466043876332,
2.5551644e6
],
[
2.890871144776878e-9,
8.983055095805407e-6,
-0.00000003068298,
7.47137025468032,
-0.00000353937994,
-0.02145144861037,
-0.00001234426596,
0.00010322952773,
-0.00000323890364,
8.260885e5
]
]
const LL2MC = [
[
-0.0015702102444,
1.113207020616939e5,
1.704480524535203e15,
-1.033898737604234e16,
2.611266785660388e16,
-3.51496691766537e16,
2.659570071840392e16,
-1.072501245418824e16,
1.800819912950474e15,
82.5
],
[
8.277824516172526e-4,
1.113207020463578e5,
6.477955746671608e8,
-4.082003173641316e9,
1.077490566351142e10,
-1.517187553151559e10,
1.205306533862167e10,
-5.124939663577472e9,
9.133119359512032e8,
67.5
],
[
0.00337398766765,
1.113207020202162e5,
4.481351045890365e6,
-2.339375119931662e7,
7.968221547186455e7,
-1.159649932797253e8,
9.723671115602145e7,
-4.366194633752821e7,
8.477230501135234e6,
52.5
],
[
0.00220636496208,
1.113207020209128e5,
5.175186112841131e4,
3.796837749470245e6,
9.920137397791013e5,
-1.22195221711287e6,
1.340652697009075e6,
-6.209436990984312e5,
1.444169293806241e5,
37.5
],
[
-3.441963504368392e-4,
1.113207020576856e5,
2.782353980772752e2,
2.485758690035394e6,
6.070750963243378e3,
5.482118345352118e4,
9.540606633304236e3,
-2.71055326746645e3,
1.405483844121726e3,
22.5
],
[
-3.218135878613132e-4,
1.113207020701615e5,
0.00369383431289,
8.237256402795718e5,
0.46104986909093,
2.351343141331292e3,
1.58060784298199,
8.77738589078284,
0.37238884252424,
7.45
]
]
type LngLatPoint = {
lng;
lat;
}
class BaiduMercatorProjection {
isWgs84;
constructor() {
this.isWgs84 = false
}
/**
*
* @param point1
* @param point2
* @returns {number}
*/
getDistanceByMC(point1, point2) {
if (!point1 || !point2) {
return 0
}
point1 = this.convertMC2LL(point1)
if (!point1) {
return 0
}
let x1 = this.toRadians(point1['lng'])
let y1 = this.toRadians(point1['lat'])
point2 = this.convertMC2LL(point2)
if (!point2) {
return 0
}
let x2 = this.toRadians(point2['lng'])
let y2 = this.toRadians(point2['lat'])
return this.getDistance(x1, x2, y1, y2)
}
/**
* Calculate the distance between two points according to the latitude and longitude coordinates
* @param point1
* @param point2
* @returns {number|*}
*/
getDistanceByLL(point1, point2) {
if (!point1 || !point2) {
return 0
}
point1['lng'] = this.getLoop(point1['lng'], -180, 180)
point1['lat'] = this.getRange(point1['lat'], -74, 74)
point2['lng'] = this.getLoop(point2['lng'], -180, 180)
point2['lat'] = this.getRange(point2['lat'], -74, 74)
let x1 = this.toRadians(point1['lng'])
let y1 = this.toRadians(point1['lat'])
let x2 = this.toRadians(point2['lng'])
let y2 = this.toRadians(point2['lat'])
return this.getDistance(x1, x2, y1, y2)
}
/**
* The plane cartesian coordinates are converted to latitude and longitude coordinates
* @param point
* @returns {Point|{lng: number, lat: number}}
*/
convertMC2LL(point) {
if (!point) {
return { lng: 0, lat: 0 }
}
let lnglat = { lng: 0, lat: 0 };
if (this.isWgs84) {
lnglat.lng = (point.lng / 20037508.34) * 180
let mmy = (point.lat / 20037508.34) * 180
lnglat.lat =
(180 / Math.PI) *
(2 * Math.atan(Math.exp((mmy * Math.PI) / 180)) - Math.PI / 2)
return {
lng: lnglat['lng'],
lat: lnglat['lat']
}
}
let temp = {
lng: Math.abs(point['lng']),
lat: Math.abs(point['lat'])
}
let factor = [];
for (let i = 0; i < MC_BAND.length; i++) {
if (temp['lat'] >= MC_BAND[i]) {
factor = MC2LL[i]
break
}
}
lnglat = this.convertor(point, factor)
return {
lng: lnglat['lng'],
lat: lnglat['lat']
}
}
/**
* The latitude and longitude coordinates are converted to plane cartesian coordinates
* @param point
* @returns {{lng: number, lat: number}|*}
*/
convertLL2MC(point) {
if (!point) {
return { lng: 0, lat: 0 }
}
if (
point['lng'] > 180 ||
point['lng'] < -180 ||
point['lat'] > 90 ||
point['lat'] < -90
) {
return point
}
if (this.isWgs84) {
let mercator = { lng: 0, lat: 0 };
let earthRad = 6378137.0
mercator.lng = ((point.lng * Math.PI) / 180) * earthRad
let a = (point.lat * Math.PI) / 180
mercator.lat =
(earthRad / 2) * Math.log((1.0 + Math.sin(a)) / (1.0 - Math.sin(a)))
return {
lng: parseFloat(mercator['lng'].toFixed(2)),
lat: parseFloat(mercator['lat'].toFixed(2))
}
}
point['lng'] = this.getLoop(point['lng'], -180, 180)
point['lat'] = this.getRange(point['lat'], -74, 74)
let temp = { lng: point['lng'], lat: point['lat'] }
let factor = [];
for (let i = 0; i < LL_BAND.length; i++) {
if (temp['lat'] >= LL_BAND[i]) {
factor = LL2MC[i]
break
}
}
if (!factor) {
for (let i = 0; i < LL_BAND.length; i++) {
if (temp['lat'] <= -LL_BAND[i]) {
factor = LL2MC[i]
break
}
}
}
let mc = this.convertor(point, factor)
return {
lng: parseFloat(mc['lng'].toFixed(2)),
lat: parseFloat(mc['lat'].toFixed(2))
}
}
/**
*
* @param fromPoint
* @param factor
* @returns {{lng: *, lat: *}}
*/
convertor(fromPoint, factor) {
if (!fromPoint || !factor) {
return { lng: 0, lat: 0 }
}
let x = factor[0] + factor[1] * Math.abs(fromPoint['lng'])
let temp = Math.abs(fromPoint['lat']) / factor[9]
let y =
factor[2] +
factor[3] * temp +
factor[4] * temp * temp +
factor[5] * temp * temp * temp +
factor[6] * temp * temp * temp * temp +
factor[7] * temp * temp * temp * temp * temp +
factor[8] * temp * temp * temp * temp * temp * temp
x *= fromPoint['lng'] < 0 ? -1 : 1
y *= fromPoint['lat'] < 0 ? -1 : 1
return {
lng: x,
lat: y
}
}
/**
*
* @param x1
* @param x2
* @param y1
* @param y2
* @returns {number}
*/
getDistance(x1, x2, y1, y2) {
return (
EARTH_RADIUS *
Math.acos(
Math.sin(y1) * Math.sin(y2) +
Math.cos(y1) * Math.cos(y2) * Math.cos(x2 - x1)
)
)
}
/**
*
* @param deg
* @returns {number}
*/
toRadians(deg) {
return (Math.PI * deg) / 180
}
/**
*
* @param rad
* @returns {number}
*/
toDegrees(rad) {
return (180 * rad) / Math.PI
}
/**
*
* @param v
* @param a
* @param b
* @returns {number}
*/
getRange(v, a, b) {
if (a != null) {
v = Math.max(v, a)
}
if (b != null) {
v = Math.min(v, b)
}
return v
}
/**
*
* @param v
* @param a
* @param b
* @returns {*}
*/
getLoop(v, a, b) {
while (v > b) {
v -= b - a
}
while (v < a) {
v += b - a
}
return v
}
/**
*
* @param point
* @returns {{lng: number, lat: number}|*}
*/
lngLatToMercator(point) {
return this.convertLL2MC(point)
}
/**
*
* @param point
* @returns {{x: (number|*), y: (number|*)}}
*/
lngLatToPoint(point) {
let mercator = this.convertLL2MC(point)
return {
x: mercator['lng'],
y: mercator['lat']
}
}
/**
* WebMercator transforms to latitude and longitude
* @param point
* @returns {Point|{lng: number, lat: number}}
*/
mercatorToLngLat(point) {
return this.convertMC2LL(point)
}
/**
*
* @param point
* @returns {Point|{lng: number, lat: number}}
*/
pointToLngLat(point) {
let mercator = { lng: point.lng, lat: point.lat }
return this.convertMC2LL(mercator)
}
/**
* Latitude and longitude coordinates transforms to pixel coordinates
* @param point
* @param zoom
* @param mapCenter
* @param mapSize
* @returns {{x: number, y: number}}
*/
pointToPixel(point, zoom, mapCenter, mapSize) {
if (!point) {
return { x: 0, y: 0 }
}
point = this.lngLatToMercator(point)
let zoomUnits = this.getZoomUnits(zoom)
let x = Math.round(
(point['lng'] - mapCenter['lng']) / zoomUnits + mapSize.width / 2
)
let y = Math.round(
(mapCenter['lat'] - point['lat']) / zoomUnits + mapSize.height / 2
)
return { x, y }
}
/**
* Pixel coordinates transforms to latitude and longitude coordinates
* @param pixel
* @param zoom
* @param mapCenter
* @param mapSize
* @returns {Point|{lng: number, lat: number}}
*/
pixelToPoint(pixel, zoom, mapCenter, mapSize) {
if (!pixel) {
return { lng: 0, lat: 0 }
}
let zoomUnits = this.getZoomUnits(zoom)
let lng = mapCenter['lng'] + zoomUnits * (pixel.x - mapSize.width / 2)
let lat = mapCenter['lat'] - zoomUnits * (pixel.y - mapSize.height / 2)
let point = { lng, lat }
return this.mercatorToLngLat(point)
}
/**
*
* @param zoom
* @returns {number}
*/
getZoomUnits(zoom) {
return Math.pow(2, 18 - zoom)
}
}
export default BaiduMercatorProjection |
61811f6d5ec9421f9b4aaef6478b2aa7abe326c0 | 1,961 | ts | TypeScript | src/clue.ts | 6zs/xordle | d17e414279c13137f987edd20a2f36aaed572712 | [
"MIT"
] | 1 | 2022-03-21T03:49:52.000Z | 2022-03-21T03:49:52.000Z | src/clue.ts | 6zs/xordle | d17e414279c13137f987edd20a2f36aaed572712 | [
"MIT"
] | null | null | null | src/clue.ts | 6zs/xordle | d17e414279c13137f987edd20a2f36aaed572712 | [
"MIT"
] | 1 | 2022-03-09T21:19:56.000Z | 2022-03-09T21:19:56.000Z | export enum Clue {
Absent,
Elsewhere,
Correct,
}
export interface CluedLetter {
clue?: Clue;
letter: string;
}
export function clue(word: string, target: string): CluedLetter[] {
let elusive: string[] = [];
target.split("").forEach((letter, i) => {
if (word[i] !== letter) {
elusive.push(letter);
}
});
return word.split("").map((letter, i) => {
let j: number;
if (target[i] === letter) {
return { clue: Clue.Correct, letter };
} else if ((j = elusive.indexOf(letter)) > -1) {
// "use it up" so we don't clue at it twice
elusive[j] = "";
return { clue: Clue.Elsewhere, letter };
} else {
return { clue: Clue.Absent, letter };
}
});
}
export function xorclue(clue1: CluedLetter[], clue2: CluedLetter[]): CluedLetter[] {
return clue1.map((cluedLetter,i) => {
if (cluedLetter !== clue2[i]) {
if ( cluedLetter.clue === Clue.Correct || clue2[i].clue === Clue.Correct ) {
return { clue: Clue.Correct, letter: cluedLetter.letter };
}
if ( cluedLetter.clue === Clue.Elsewhere || clue2[i].clue === Clue.Elsewhere ) {
return { clue: Clue.Elsewhere, letter: cluedLetter.letter };
}
}
return { clue: Clue.Absent, letter: cluedLetter.letter };
});
}
export function clueClass(clue: Clue, correctGuess: boolean): string {
const suffix = (correctGuess ? "-fin" : "");
if (clue === Clue.Absent) {
return "letter-absent";
} else if (clue === Clue.Elsewhere) {
return "letter-elsewhere" + suffix;
} else {
return "letter-correct" + suffix;
}
}
export function clueWord(clue: Clue): string {
if (clue === Clue.Absent) {
return "no";
} else if (clue === Clue.Elsewhere) {
return "elsewhere";
} else {
return "correct";
}
}
export function describeClue(clue: CluedLetter[]): string {
return clue
.map(({ letter, clue }) => letter.toUpperCase() + " " + clueWord(clue!))
.join(", ");
}
| 26.863014 | 86 | 0.592045 | 65 | 9 | 0 | 15 | 3 | 2 | 1 | 0 | 9 | 1 | 0 | 7.555556 | 643 | 0.037325 | 0.004666 | 0.00311 | 0.001555 | 0 | 0 | 0.310345 | 0.274998 | export enum Clue {
Absent,
Elsewhere,
Correct,
}
export interface CluedLetter {
clue?;
letter;
}
export /* Example usages of 'clue' are shown below:
;
cluedLetter.clue === Clue.Correct || clue2[i].clue === Clue.Correct;
cluedLetter.clue === Clue.Elsewhere || clue2[i].clue === Clue.Elsewhere;
clue === Clue.Absent;
clue === Clue.Elsewhere;
clue
.map(({ letter, clue }) => letter.toUpperCase() + " " + clueWord(clue!))
.join(", ");
letter.toUpperCase() + " " + clueWord(clue!);
*/
function clue(word, target) {
let elusive = [];
target.split("").forEach((letter, i) => {
if (word[i] !== letter) {
elusive.push(letter);
}
});
return word.split("").map((letter, i) => {
let j;
if (target[i] === letter) {
return { clue: Clue.Correct, letter };
} else if ((j = elusive.indexOf(letter)) > -1) {
// "use it up" so we don't clue at it twice
elusive[j] = "";
return { clue: Clue.Elsewhere, letter };
} else {
return { clue: Clue.Absent, letter };
}
});
}
export function xorclue(clue1, clue2) {
return clue1.map((cluedLetter,i) => {
if (cluedLetter !== clue2[i]) {
if ( cluedLetter.clue === Clue.Correct || clue2[i].clue === Clue.Correct ) {
return { clue: Clue.Correct, letter: cluedLetter.letter };
}
if ( cluedLetter.clue === Clue.Elsewhere || clue2[i].clue === Clue.Elsewhere ) {
return { clue: Clue.Elsewhere, letter: cluedLetter.letter };
}
}
return { clue: Clue.Absent, letter: cluedLetter.letter };
});
}
export function clueClass(clue, correctGuess) {
const suffix = (correctGuess ? "-fin" : "");
if (clue === Clue.Absent) {
return "letter-absent";
} else if (clue === Clue.Elsewhere) {
return "letter-elsewhere" + suffix;
} else {
return "letter-correct" + suffix;
}
}
export /* Example usages of 'clueWord' are shown below:
letter.toUpperCase() + " " + clueWord(clue!);
*/
function clueWord(clue) {
if (clue === Clue.Absent) {
return "no";
} else if (clue === Clue.Elsewhere) {
return "elsewhere";
} else {
return "correct";
}
}
export function describeClue(clue) {
return clue
.map(({ letter, clue }) => letter.toUpperCase() + " " + clueWord(clue!))
.join(", ");
}
|
692b6650dfaec64762a5a63c3ed9a70a95671b5f | 4,696 | ts | TypeScript | src/libs/bus.ts | chaosst/view-scroller | bfb45a6b4345f7167f4ac5db17160d50fcfd3e47 | [
"MIT"
] | 1 | 2022-02-10T08:59:25.000Z | 2022-02-10T08:59:25.000Z | src/libs/bus.ts | chaosst/view-scroller | bfb45a6b4345f7167f4ac5db17160d50fcfd3e47 | [
"MIT"
] | null | null | null | src/libs/bus.ts | chaosst/view-scroller | bfb45a6b4345f7167f4ac5db17160d50fcfd3e47 | [
"MIT"
] | null | null | null | interface busEv{
name:string,
isOnce:boolean,
callback:Function;
}
/**
* 自定义的事件总线
* 方法:
* on: 绑定一个事件
* once: 绑定一个一次性事件
* off: 移除一个事件
* emit: 触发一个事件
* use: 添加一个中间件
*/
export class EventBus{
//事件列表
public eventArr:Array<any> = [];
//添加的中间件列表
public useFunArr:any[] = [];
constructor(){
}
public eventTpl:busEv = {
name: "", //事件名
isOnce: false, //是否只执行一次
//回调
callback: function ():void {
}
}
/**
* 创建一个事件
* @param {String} name
* @param {Function} callback
* @return {eventTpl}
*/
private createEvent = (name:string, callback:Function):busEv=>{
let e:busEv = {
name: name, //事件名
isOnce: false, //是否只执行一次
callback: callback //回调
}
return e;
}
/**
* 获取事件
* @param {String} name
* @param {Function} fn
* @return {eventTpl}
*/
private getEvent = (name:string, fn?:Function):Array<busEv>=>{
let matchFn:any = fn && typeof fn == 'function';
return this.eventArr.filter((e) => {
let b = e.name === name;
if (matchFn) {
b = b && e.fn === fn;
}
return b;
})
}
/**
* 移除一个事件
* @param {String} name
* @param {Function} fn fn为空则全部移除
* @return {void}
*/
private removeEvent = (name:string, fn?:Function):void=>{
let matchFn:any = fn && typeof fn == 'function';
this.eventArr = this.eventArr.filter((e) => {
let b = e.name === name;
if (matchFn) {
b = b && e.fn === fn;
}
return !b;
})
}
/**
* 移除一个事件, 同removeEvent
* @param {String} name
* @param {Function} fn fn为空则全部移除
* @return {void}
*/
public off = (name:string, fn?:Function):void=>{
this.removeEvent(name, fn);
}
/**
* 添加中间件
* @param {function(string, object, ()=>{})} fn 中间件函数 fn(name, packet, next)
* @return {void}
*/
private use = (fn:Function):void=>{
this.useFunArr.push(fn)
}
/**
* 中间件过滤, 只有添加的中间件执行next(),
* 才会触发下一个中间件,
* 否则终止触发事件
* @param {String} name 触发事件名
* @param {Object} packet 触发事件传入的数据
* @return {boolean} b
*/
private useFilter = (name:string, packet:object):boolean=>{
let useFunArr:Array<any> = this.useFunArr;
let len:number = useFunArr.length;
let index:number = 0;
if (len) {
//从第一个中间件开始执行
useFunArr[0](name, packet, next);
//执行过的中间件与中间件总数相比较
if (index === len - 1) {
return true;
} else {
return false;
}
}
return true;
function next() {
//每执行一个中间件,指数+1
index++;
if (index < len) {
useFunArr[index](name, packet, next);
}
}
}
/**
* 添加事件
* @param {String} name 事件名
* @param {Function} fn 执行的事件函数
* @param {boolean} cover 是否覆盖之前的事件
* @return {eventTpl}
*/
public on = (name:string, fn:Function, cover:boolean = false):busEv=>{
let ev:busEv = this.createEvent(name, fn);
if (cover) {
let eventArr = this.getEvent(name);
if (eventArr.length > 0) {
this.removeEvent(name);
}
}
this.eventArr.push(ev);
return ev;
}
/**
* 添加事件, 执行完立即立即销毁
* @param {String} name 事件名
* @param {Function} fn 执行的事件函数
* @param {boolean} cover 是否覆盖之前的事件
* @return {void}
*/
public once = (name:string, fn:Function, cover:boolean = false):void=>{
let ev:busEv = this.on(name, fn, cover);
ev.isOnce = true;
}
/**
* 触发一个事件
* @param {String} name 事件名
* @param {Object} data 传入事件监听方法的数据
* @return {void}
*/
public emit = (name:string, data:object):void=> {
let eventArr:Array<any> = this.getEvent(name);
let b:boolean = this.useFilter(name, data);
if (!b) {
return;
}
let len:number = eventArr.length,
ev:busEv;
for (let i = 0; i < len; i++) {
ev = eventArr[i];
//执行监听的事件
if (typeof ev.callback === 'function') {
let b = ev.callback(data);
if (ev.isOnce) {
this.removeEvent(ev.name);
}
if (typeof b != 'undefined' && b === false) {
return;
}
}
}
}
} | 24.331606 | 80 | 0.468484 | 107 | 14 | 0 | 21 | 17 | 15 | 0 | 14 | 25 | 2 | 4 | 6.142857 | 1,368 | 0.025585 | 0.012427 | 0.010965 | 0.001462 | 0.002924 | 0.208955 | 0.373134 | 0.268622 | interface busEv{
name,
isOnce,
callback;
}
/**
* 自定义的事件总线
* 方法:
* on: 绑定一个事件
* once: 绑定一个一次性事件
* off: 移除一个事件
* emit: 触发一个事件
* use: 添加一个中间件
*/
export class EventBus{
//事件列表
public eventArr = [];
//添加的中间件列表
public useFunArr = [];
constructor(){
}
public eventTpl = {
name: "", //事件名
isOnce: false, //是否只执行一次
//回调
callback: function () {
}
}
/**
* 创建一个事件
* @param {String} name
* @param {Function} callback
* @return {eventTpl}
*/
private createEvent = (name, callback)=>{
let e = {
name: name, //事件名
isOnce: false, //是否只执行一次
callback: callback //回调
}
return e;
}
/**
* 获取事件
* @param {String} name
* @param {Function} fn
* @return {eventTpl}
*/
private getEvent = (name, fn?)=>{
let matchFn = fn && typeof fn == 'function';
return this.eventArr.filter((e) => {
let b = e.name === name;
if (matchFn) {
b = b && e.fn === fn;
}
return b;
})
}
/**
* 移除一个事件
* @param {String} name
* @param {Function} fn fn为空则全部移除
* @return {void}
*/
private removeEvent = (name, fn?)=>{
let matchFn = fn && typeof fn == 'function';
this.eventArr = this.eventArr.filter((e) => {
let b = e.name === name;
if (matchFn) {
b = b && e.fn === fn;
}
return !b;
})
}
/**
* 移除一个事件, 同removeEvent
* @param {String} name
* @param {Function} fn fn为空则全部移除
* @return {void}
*/
public off = (name, fn?)=>{
this.removeEvent(name, fn);
}
/**
* 添加中间件
* @param {function(string, object, ()=>{})} fn 中间件函数 fn(name, packet, next)
* @return {void}
*/
private use = (fn)=>{
this.useFunArr.push(fn)
}
/**
* 中间件过滤, 只有添加的中间件执行next(),
* 才会触发下一个中间件,
* 否则终止触发事件
* @param {String} name 触发事件名
* @param {Object} packet 触发事件传入的数据
* @return {boolean} b
*/
private useFilter = (name, packet)=>{
let useFunArr = this.useFunArr;
let len = useFunArr.length;
let index = 0;
if (len) {
//从第一个中间件开始执行
useFunArr[0](name, packet, next);
//执行过的中间件与中间件总数相比较
if (index === len - 1) {
return true;
} else {
return false;
}
}
return true;
/* Example usages of 'next' are shown below:
//从第一个中间件开始执行
useFunArr[0](name, packet, next);
useFunArr[index](name, packet, next);
*/
function next() {
//每执行一个中间件,指数+1
index++;
if (index < len) {
useFunArr[index](name, packet, next);
}
}
}
/**
* 添加事件
* @param {String} name 事件名
* @param {Function} fn 执行的事件函数
* @param {boolean} cover 是否覆盖之前的事件
* @return {eventTpl}
*/
public on = (name, fn, cover = false)=>{
let ev = this.createEvent(name, fn);
if (cover) {
let eventArr = this.getEvent(name);
if (eventArr.length > 0) {
this.removeEvent(name);
}
}
this.eventArr.push(ev);
return ev;
}
/**
* 添加事件, 执行完立即立即销毁
* @param {String} name 事件名
* @param {Function} fn 执行的事件函数
* @param {boolean} cover 是否覆盖之前的事件
* @return {void}
*/
public once = (name, fn, cover = false)=>{
let ev = this.on(name, fn, cover);
ev.isOnce = true;
}
/**
* 触发一个事件
* @param {String} name 事件名
* @param {Object} data 传入事件监听方法的数据
* @return {void}
*/
public emit = (name, data)=> {
let eventArr = this.getEvent(name);
let b = this.useFilter(name, data);
if (!b) {
return;
}
let len = eventArr.length,
ev;
for (let i = 0; i < len; i++) {
ev = eventArr[i];
//执行监听的事件
if (typeof ev.callback === 'function') {
let b = ev.callback(data);
if (ev.isOnce) {
this.removeEvent(ev.name);
}
if (typeof b != 'undefined' && b === false) {
return;
}
}
}
}
} |
6950b0c6d8ed7c8e7929ed15895c89d2b1d81e39 | 1,365 | ts | TypeScript | typescript/src/libs/linked_list.ts | eteplus/leetcode | 13cb7aac323dd68c670b1548a8d72667eb68bd7c | [
"MIT"
] | 1 | 2022-01-25T09:03:59.000Z | 2022-01-25T09:03:59.000Z | typescript/src/libs/linked_list.ts | eteplus/leetcode | 13cb7aac323dd68c670b1548a8d72667eb68bd7c | [
"MIT"
] | null | null | null | typescript/src/libs/linked_list.ts | eteplus/leetcode | 13cb7aac323dd68c670b1548a8d72667eb68bd7c | [
"MIT"
] | null | null | null | export class ListNode {
public val: number;
public next: ListNode | null;
constructor(val?: number, next?: ListNode | null) {
this.val = val === undefined ? 0 : val;
this.next = next === undefined ? null : next;
}
}
export function createLinkedList(nums: number[]): ListNode | null {
let head: ListNode | null = null;
let curr: ListNode | null = null;
for (let num of nums) {
if (head === null) {
head = new ListNode(num);
curr = head;
} else if (curr !== null) {
curr.next = new ListNode(num);
curr = curr.next;
}
}
return head;
}
export function createCycleLinkedList(nums: number[], pos: number): ListNode | null {
let head: ListNode | null = null;
let curr: ListNode | null = null;
let cycle: ListNode | null = null;
for (let i = 0; i < nums.length; i++) {
const num = nums[i];
if (!head) {
head = new ListNode(num);
curr = head;
} else if (curr !== null) {
curr.next = new ListNode(num);
curr = curr.next;
}
if (i === pos) {
cycle = curr;
}
}
if (curr) {
curr.next = cycle;
}
return head;
}
export function parseLinkedList(head: ListNode | null): number[] {
let result: number[] = [];
let curr: ListNode | null = head;
while (curr !== null) {
result.push(curr.val);
curr = curr.next;
}
return result;
}
| 23.947368 | 85 | 0.576557 | 53 | 4 | 0 | 6 | 9 | 2 | 0 | 0 | 7 | 1 | 0 | 10.25 | 395 | 0.025316 | 0.022785 | 0.005063 | 0.002532 | 0 | 0 | 0.333333 | 0.307405 | export class ListNode {
public val;
public next;
constructor(val?, next?) {
this.val = val === undefined ? 0 : val;
this.next = next === undefined ? null : next;
}
}
export function createLinkedList(nums) {
let head = null;
let curr = null;
for (let num of nums) {
if (head === null) {
head = new ListNode(num);
curr = head;
} else if (curr !== null) {
curr.next = new ListNode(num);
curr = curr.next;
}
}
return head;
}
export function createCycleLinkedList(nums, pos) {
let head = null;
let curr = null;
let cycle = null;
for (let i = 0; i < nums.length; i++) {
const num = nums[i];
if (!head) {
head = new ListNode(num);
curr = head;
} else if (curr !== null) {
curr.next = new ListNode(num);
curr = curr.next;
}
if (i === pos) {
cycle = curr;
}
}
if (curr) {
curr.next = cycle;
}
return head;
}
export function parseLinkedList(head) {
let result = [];
let curr = head;
while (curr !== null) {
result.push(curr.val);
curr = curr.next;
}
return result;
}
|
696f12f562f1205851371083a8b2e8343613e123 | 3,160 | ts | TypeScript | theatre/shared/src/utils/color.ts | Mu-L/theatre | 9dda07d3f18760cb62ee38edef401a823cee9695 | [
"Apache-2.0"
] | 361 | 2022-01-20T12:18:44.000Z | 2022-03-31T07:55:16.000Z | theatre/shared/src/utils/color.ts | Mu-L/theatre | 9dda07d3f18760cb62ee38edef401a823cee9695 | [
"Apache-2.0"
] | 43 | 2022-01-24T21:43:33.000Z | 2022-03-31T14:23:50.000Z | theatre/shared/src/utils/color.ts | Mu-L/theatre | 9dda07d3f18760cb62ee38edef401a823cee9695 | [
"Apache-2.0"
] | 23 | 2022-01-22T11:22:13.000Z | 2022-03-28T00:26:50.000Z | export function parseRgbaFromHex(rgba: string) {
rgba = rgba.trim().toLowerCase()
const hex = rgba.match(/^#?([0-9a-f]{8})$/i)
if (!hex) {
return {
r: 0,
g: 0,
b: 0,
a: 1,
}
}
const match = hex[1]
return {
r: parseInt(match.substr(0, 2), 16) / 255,
g: parseInt(match.substr(2, 2), 16) / 255,
b: parseInt(match.substr(4, 2), 16) / 255,
a: parseInt(match.substr(6, 2), 16) / 255,
}
}
export function rgba2hex(rgba: Rgba) {
const hex =
((rgba.r * 255) | (1 << 8)).toString(16).slice(1) +
((rgba.g * 255) | (1 << 8)).toString(16).slice(1) +
((rgba.b * 255) | (1 << 8)).toString(16).slice(1) +
((rgba.a * 255) | (1 << 8)).toString(16).slice(1)
return `#${hex}`
}
// TODO: We should add a decorate property to the propConfig too.
// Right now, each place that has anything to do with a color is individually
// responsible for defining a toString() function on the object it returns.
export function decorateRgba(rgba: Rgba) {
return {
...rgba,
toString() {
return rgba2hex(this)
},
}
}
export function linearSrgbToSrgb(rgba: Rgba) {
function compress(x: number) {
// This looks funky because sRGB uses a linear scale below 0.0031308 in
// order to avoid an infinite slope, while trying to approximate gamma 2.2
// as closely as possible, hence the branching and the 2.4 exponent.
if (x >= 0.0031308) return 1.055 * x ** (1.0 / 2.4) - 0.055
else return 12.92 * x
}
return {
r: compress(rgba.r),
g: compress(rgba.g),
b: compress(rgba.b),
a: rgba.a,
}
}
export function srgbToLinearSrgb(rgba: Rgba) {
function expand(x: number) {
if (x >= 0.04045) return ((x + 0.055) / (1 + 0.055)) ** 2.4
else return x / 12.92
}
return {
r: expand(rgba.r),
g: expand(rgba.g),
b: expand(rgba.b),
a: rgba.a,
}
}
export function linearSrgbToOklab(rgba: Rgba) {
let l = 0.4122214708 * rgba.r + 0.5363325363 * rgba.g + 0.0514459929 * rgba.b
let m = 0.2119034982 * rgba.r + 0.6806995451 * rgba.g + 0.1073969566 * rgba.b
let s = 0.0883024619 * rgba.r + 0.2817188376 * rgba.g + 0.6299787005 * rgba.b
let l_ = Math.cbrt(l)
let m_ = Math.cbrt(m)
let s_ = Math.cbrt(s)
return {
L: 0.2104542553 * l_ + 0.793617785 * m_ - 0.0040720468 * s_,
a: 1.9779984951 * l_ - 2.428592205 * m_ + 0.4505937099 * s_,
b: 0.0259040371 * l_ + 0.7827717662 * m_ - 0.808675766 * s_,
alpha: rgba.a,
}
}
export function oklabToLinearSrgb(laba: Laba) {
let l_ = laba.L + 0.3963377774 * laba.a + 0.2158037573 * laba.b
let m_ = laba.L - 0.1055613458 * laba.a - 0.0638541728 * laba.b
let s_ = laba.L - 0.0894841775 * laba.a - 1.291485548 * laba.b
let l = l_ * l_ * l_
let m = m_ * m_ * m_
let s = s_ * s_ * s_
return {
r: +4.0767416621 * l - 3.3077115913 * m + 0.2309699292 * s,
g: -1.2684380046 * l + 2.6097574011 * m - 0.3413193965 * s,
b: -0.0041960863 * l - 0.7034186147 * m + 1.707614701 * s,
a: laba.alpha,
}
}
export type Rgba = {
r: number
g: number
b: number
a: number
}
export type Laba = {
L: number
a: number
b: number
alpha: number
}
| 26.115702 | 79 | 0.593671 | 99 | 10 | 0 | 9 | 15 | 8 | 4 | 0 | 11 | 2 | 0 | 7.8 | 1,543 | 0.012314 | 0.009721 | 0.005185 | 0.001296 | 0 | 0 | 0.261905 | 0.233382 | export function parseRgbaFromHex(rgba) {
rgba = rgba.trim().toLowerCase()
const hex = rgba.match(/^#?([0-9a-f]{8})$/i)
if (!hex) {
return {
r: 0,
g: 0,
b: 0,
a: 1,
}
}
const match = hex[1]
return {
r: parseInt(match.substr(0, 2), 16) / 255,
g: parseInt(match.substr(2, 2), 16) / 255,
b: parseInt(match.substr(4, 2), 16) / 255,
a: parseInt(match.substr(6, 2), 16) / 255,
}
}
export /* Example usages of 'rgba2hex' are shown below:
rgba2hex(this);
*/
function rgba2hex(rgba) {
const hex =
((rgba.r * 255) | (1 << 8)).toString(16).slice(1) +
((rgba.g * 255) | (1 << 8)).toString(16).slice(1) +
((rgba.b * 255) | (1 << 8)).toString(16).slice(1) +
((rgba.a * 255) | (1 << 8)).toString(16).slice(1)
return `#${hex}`
}
// TODO: We should add a decorate property to the propConfig too.
// Right now, each place that has anything to do with a color is individually
// responsible for defining a toString() function on the object it returns.
export function decorateRgba(rgba) {
return {
...rgba,
toString() {
return rgba2hex(this)
},
}
}
export function linearSrgbToSrgb(rgba) {
/* Example usages of 'compress' are shown below:
compress(rgba.r);
compress(rgba.g);
compress(rgba.b);
*/
function compress(x) {
// This looks funky because sRGB uses a linear scale below 0.0031308 in
// order to avoid an infinite slope, while trying to approximate gamma 2.2
// as closely as possible, hence the branching and the 2.4 exponent.
if (x >= 0.0031308) return 1.055 * x ** (1.0 / 2.4) - 0.055
else return 12.92 * x
}
return {
r: compress(rgba.r),
g: compress(rgba.g),
b: compress(rgba.b),
a: rgba.a,
}
}
export function srgbToLinearSrgb(rgba) {
/* Example usages of 'expand' are shown below:
expand(rgba.r);
expand(rgba.g);
expand(rgba.b);
*/
function expand(x) {
if (x >= 0.04045) return ((x + 0.055) / (1 + 0.055)) ** 2.4
else return x / 12.92
}
return {
r: expand(rgba.r),
g: expand(rgba.g),
b: expand(rgba.b),
a: rgba.a,
}
}
export function linearSrgbToOklab(rgba) {
let l = 0.4122214708 * rgba.r + 0.5363325363 * rgba.g + 0.0514459929 * rgba.b
let m = 0.2119034982 * rgba.r + 0.6806995451 * rgba.g + 0.1073969566 * rgba.b
let s = 0.0883024619 * rgba.r + 0.2817188376 * rgba.g + 0.6299787005 * rgba.b
let l_ = Math.cbrt(l)
let m_ = Math.cbrt(m)
let s_ = Math.cbrt(s)
return {
L: 0.2104542553 * l_ + 0.793617785 * m_ - 0.0040720468 * s_,
a: 1.9779984951 * l_ - 2.428592205 * m_ + 0.4505937099 * s_,
b: 0.0259040371 * l_ + 0.7827717662 * m_ - 0.808675766 * s_,
alpha: rgba.a,
}
}
export function oklabToLinearSrgb(laba) {
let l_ = laba.L + 0.3963377774 * laba.a + 0.2158037573 * laba.b
let m_ = laba.L - 0.1055613458 * laba.a - 0.0638541728 * laba.b
let s_ = laba.L - 0.0894841775 * laba.a - 1.291485548 * laba.b
let l = l_ * l_ * l_
let m = m_ * m_ * m_
let s = s_ * s_ * s_
return {
r: +4.0767416621 * l - 3.3077115913 * m + 0.2309699292 * s,
g: -1.2684380046 * l + 2.6097574011 * m - 0.3413193965 * s,
b: -0.0041960863 * l - 0.7034186147 * m + 1.707614701 * s,
a: laba.alpha,
}
}
export type Rgba = {
r
g
b
a
}
export type Laba = {
L
a
b
alpha
}
|
6994dbf5e9c18f1d7b530b33ac5f9c66a9216dca | 2,363 | ts | TypeScript | packages/angular/cli/src/utilities/memoize.ts | 10088/angular-cli | 7ce88c74edefdb90cc3527a10cfe6564ad3ddcbc | [
"MIT"
] | null | null | null | packages/angular/cli/src/utilities/memoize.ts | 10088/angular-cli | 7ce88c74edefdb90cc3527a10cfe6564ad3ddcbc | [
"MIT"
] | 3 | 2022-01-21T23:12:11.000Z | 2022-03-08T20:09:59.000Z | packages/angular/cli/src/utilities/memoize.ts | 10088/angular-cli | 7ce88c74edefdb90cc3527a10cfe6564ad3ddcbc | [
"MIT"
] | null | null | null | /**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
/**
* A decorator that memoizes methods and getters.
*
* **Note**: Be cautious where and how to use this decorator as the size of the cache will grow unbounded.
*
* @see https://en.wikipedia.org/wiki/Memoization
*/
export function memoize<T>(
target: Object,
propertyKey: string | symbol,
descriptor: TypedPropertyDescriptor<T>,
): TypedPropertyDescriptor<T> {
const descriptorPropertyName = descriptor.get ? 'get' : 'value';
const originalMethod: unknown = descriptor[descriptorPropertyName];
if (typeof originalMethod !== 'function') {
throw new Error('Memoize decorator can only be used on methods or get accessors.');
}
const cache = new Map<string, unknown>();
return {
...descriptor,
[descriptorPropertyName]: function (this: unknown, ...args: unknown[]) {
for (const arg of args) {
if (!isJSONSerializable(arg)) {
throw new Error(
`Argument ${isNonPrimitive(arg) ? arg.toString() : arg} is JSON serializable.`,
);
}
}
const key = JSON.stringify(args);
if (cache.has(key)) {
return cache.get(key);
}
const result = originalMethod.apply(this, args);
cache.set(key, result);
return result;
},
};
}
/** Method to check if value is a non primitive. */
function isNonPrimitive(value: unknown): value is object | Function | symbol {
return (
(value !== null && typeof value === 'object') ||
typeof value === 'function' ||
typeof value === 'symbol'
);
}
/** Method to check if the values are JSON serializable */
function isJSONSerializable(value: unknown): boolean {
if (!isNonPrimitive(value)) {
// Can be seralized since it's a primitive.
return true;
}
let nestedValues: unknown[] | undefined;
if (Array.isArray(value)) {
// It's an array, check each item.
nestedValues = value;
} else if (Object.prototype.toString.call(value) === '[object Object]') {
// It's a plain object, check each value.
nestedValues = Object.values(value);
}
if (!nestedValues || nestedValues.some((v) => !isJSONSerializable(v))) {
return false;
}
return true;
}
| 27.8 | 106 | 0.646212 | 53 | 5 | 0 | 8 | 6 | 0 | 2 | 1 | 13 | 0 | 4 | 11.6 | 598 | 0.021739 | 0.010033 | 0 | 0 | 0.006689 | 0.052632 | 0.684211 | 0.251494 | /**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
/**
* A decorator that memoizes methods and getters.
*
* **Note**: Be cautious where and how to use this decorator as the size of the cache will grow unbounded.
*
* @see https://en.wikipedia.org/wiki/Memoization
*/
export function memoize<T>(
target,
propertyKey,
descriptor,
) {
const descriptorPropertyName = descriptor.get ? 'get' : 'value';
const originalMethod = descriptor[descriptorPropertyName];
if (typeof originalMethod !== 'function') {
throw new Error('Memoize decorator can only be used on methods or get accessors.');
}
const cache = new Map<string, unknown>();
return {
...descriptor,
[descriptorPropertyName]: function (this, ...args) {
for (const arg of args) {
if (!isJSONSerializable(arg)) {
throw new Error(
`Argument ${isNonPrimitive(arg) ? arg.toString() : arg} is JSON serializable.`,
);
}
}
const key = JSON.stringify(args);
if (cache.has(key)) {
return cache.get(key);
}
const result = originalMethod.apply(this, args);
cache.set(key, result);
return result;
},
};
}
/** Method to check if value is a non primitive. */
/* Example usages of 'isNonPrimitive' are shown below:
isNonPrimitive(arg) ? arg.toString() : arg;
!isNonPrimitive(value);
*/
function isNonPrimitive(value): value is object | Function | symbol {
return (
(value !== null && typeof value === 'object') ||
typeof value === 'function' ||
typeof value === 'symbol'
);
}
/** Method to check if the values are JSON serializable */
/* Example usages of 'isJSONSerializable' are shown below:
!isJSONSerializable(arg);
!isJSONSerializable(v);
*/
function isJSONSerializable(value) {
if (!isNonPrimitive(value)) {
// Can be seralized since it's a primitive.
return true;
}
let nestedValues;
if (Array.isArray(value)) {
// It's an array, check each item.
nestedValues = value;
} else if (Object.prototype.toString.call(value) === '[object Object]') {
// It's a plain object, check each value.
nestedValues = Object.values(value);
}
if (!nestedValues || nestedValues.some((v) => !isJSONSerializable(v))) {
return false;
}
return true;
}
|
64364c41d7fd6ce7e26433e81d5bc12edc01a49e | 1,256 | ts | TypeScript | src/components/limit.ts | allen-garvey/embla-carousel | 8a9615965e1256c08816e104dd60d01dde171237 | [
"MIT"
] | 1 | 2022-02-17T08:23:35.000Z | 2022-02-17T08:23:35.000Z | src/components/limit.ts | chernrus/embla-carousel | c6c535e75fac833979b147ec2f5aa1bcc18bb189 | [
"MIT"
] | null | null | null | src/components/limit.ts | chernrus/embla-carousel | c6c535e75fac833979b147ec2f5aa1bcc18bb189 | [
"MIT"
] | null | null | null | type Limits = 'min' | 'max' | ''
type Params = {
min: number
max: number
}
export type Limit = {
min: number
max: number
loop: (n: number) => number
constrain: (n: number) => number
reachedAny: (n: number) => boolean
reachedMax: (n: number) => boolean
reachedMin: (n: number) => boolean
}
export function Limit(params: Params): Limit {
const { min, max } = params
const loopLimits = { max: min, min: max }
const constrainLimits = { min, max }
function reachedMin(n: number): boolean {
return n < min
}
function reachedMax(n: number): boolean {
return n > max
}
function reachedAny(n: number): boolean {
return reachedMin(n) || reachedMax(n)
}
function reachedWhich(n: number): Limits {
const isMin = reachedMin(n) && 'min'
const isMax = reachedMax(n) && 'max'
return isMin || isMax || ''
}
function loop(n: number): number {
const which = reachedWhich(n)
return which ? loopLimits[which] : n
}
function constrain(n: number): number {
const which = reachedWhich(n)
return which ? constrainLimits[which] : n
}
const self: Limit = {
constrain,
loop,
max,
min,
reachedAny,
reachedMax,
reachedMin,
}
return Object.freeze(self)
}
| 20.258065 | 46 | 0.621019 | 51 | 7 | 0 | 7 | 8 | 9 | 3 | 0 | 25 | 3 | 0 | 6.428571 | 365 | 0.038356 | 0.021918 | 0.024658 | 0.008219 | 0 | 0 | 0.806452 | 0.34442 | type Limits = 'min' | 'max' | ''
type Params = {
min
max
}
export type Limit = {
min
max
loop
constrain
reachedAny
reachedMax
reachedMin
}
export /* Example usages of 'Limit' are shown below:
;
*/
function Limit(params) {
const { min, max } = params
const loopLimits = { max: min, min: max }
const constrainLimits = { min, max }
/* Example usages of 'reachedMin' are shown below:
;
reachedMin(n) || reachedMax(n);
reachedMin(n) && 'min';
*/
function reachedMin(n) {
return n < min
}
/* Example usages of 'reachedMax' are shown below:
;
reachedMin(n) || reachedMax(n);
reachedMax(n) && 'max';
*/
function reachedMax(n) {
return n > max
}
/* Example usages of 'reachedAny' are shown below:
;
*/
function reachedAny(n) {
return reachedMin(n) || reachedMax(n)
}
/* Example usages of 'reachedWhich' are shown below:
reachedWhich(n);
*/
function reachedWhich(n) {
const isMin = reachedMin(n) && 'min'
const isMax = reachedMax(n) && 'max'
return isMin || isMax || ''
}
/* Example usages of 'loop' are shown below:
;
*/
function loop(n) {
const which = reachedWhich(n)
return which ? loopLimits[which] : n
}
/* Example usages of 'constrain' are shown below:
;
*/
function constrain(n) {
const which = reachedWhich(n)
return which ? constrainLimits[which] : n
}
const self = {
constrain,
loop,
max,
min,
reachedAny,
reachedMax,
reachedMin,
}
return Object.freeze(self)
}
|
64595b8249135ee031171343f8ec4f50b2c9a087 | 2,872 | ts | TypeScript | src/object.ts | YFang-FE/yfang-utils | 6154f8ac335d1d355bd24794713bcd6bb739065e | [
"MIT"
] | 1 | 2022-02-09T11:48:51.000Z | 2022-02-09T11:48:51.000Z | src/object.ts | YFang-FE/yfang-utils | 6154f8ac335d1d355bd24794713bcd6bb739065e | [
"MIT"
] | null | null | null | src/object.ts | YFang-FE/yfang-utils | 6154f8ac335d1d355bd24794713bcd6bb739065e | [
"MIT"
] | null | null | null | /**
* ```ts
* import {deepClone} from 'yfang-utils'
* const data = deepClone<{value:string}>({value: 'name'})
* ```
* @export 深拷贝任意类型数据
*
* @param data 任意类型数据
* @returns
*/
export function deepClone<T>(data: any): T {
if (!data || !(data instanceof Object) || typeof data === 'function') {
return data
}
let constructor = data.constructor
let result = new constructor()
for (let key in data) {
if (data.hasOwnProperty(key)) {
result[key] = deepClone(data[key])
}
}
return result
}
/**
* @export 判断两个变量值是否完全相同
* @param a 任何类型变量
* @param b 任何类型变量
*/
export function isEquals(a: any, b: any): boolean {
if (a === b) return true
if (a instanceof Date && b instanceof Date) return a.getTime() === b.getTime()
if (!a || !b || (typeof a !== 'object' && typeof b !== 'object')) return a === b
if (a.prototype !== b.prototype) return false
if (Array.isArray(a) && Array.isArray(b)) a.sort(), b.sort()
let keys = Object.keys(a)
if (keys.length !== Object.keys(b).length) return false
return keys.every(k => isEquals(a[k], b[k]))
}
/**
* @export 对象序列化
* @param obj 任意对象
* @return
*/
export function stringfyQueryString(obj: any): string {
if (!obj) return ''
const pairs = []
for (let key in obj) {
let value = obj[key]
if (value instanceof Array) {
for (let i = 0; i < value.length; ++i) {
pairs.push(encodeURIComponent(key + '[' + i + ']') + '=' + encodeURIComponent(value[i]))
}
continue
}
pairs.push(encodeURIComponent(key) + '=' + encodeURIComponent(obj[key]))
}
return pairs.join('&')
}
/**
* @export 生成指定范围随机数
* @param {Number} min 最小值
* @param {Number} max 最大值
* @return {Number}
*/
export function randomNum(min: number, max: number): number {
if (typeof min === 'number' && typeof max === 'number')
return Math.floor(min + Math.random() * (max - min))
return 0
}
/**
* @export 时间格式化
* @param {*} date Date对象,string 或 number 的毫秒事件数
* @param {string} fmt 格式类型为:"yyyy-MM-dd hh:mm:ss"
* @returns {string}
*/
export function formatDate(date: any, fmt: string = 'yyyy-MM-dd hh:mm:ss'): string {
if (!date) {
return '--'
}
if (typeof date === 'string' && !/-/.test(date)) date = Number(date)
date = new Date(date)
let o: any = {
'M+': date.getMonth() + 1, // 月份
'd+': date.getDate(), // 日
'h+': date.getHours(), // 小时
'm+': date.getMinutes(), // 分
's+': date.getSeconds(), // 秒
'q+': Math.floor((date.getMonth() + 3) / 3), // 季度
S: date.getMilliseconds() // 毫秒
}
if (/(y+)/.test(fmt))
fmt = fmt.replace(RegExp.$1, (date.getFullYear() + '').substr(4 - RegExp.$1.length))
for (let k in o) {
if (new RegExp('(' + k + ')').test(fmt))
fmt = fmt.replace(
RegExp.$1,
RegExp.$1.length === 1 ? o[k] : ('00' + o[k]).substr(('' + o[k]).length)
)
}
return fmt
}
| 26.841121 | 96 | 0.573468 | 69 | 6 | 0 | 9 | 7 | 0 | 2 | 6 | 7 | 0 | 10 | 10 | 961 | 0.015609 | 0.007284 | 0 | 0 | 0.010406 | 0.272727 | 0.318182 | 0.224559 | /**
* ```ts
* import {deepClone} from 'yfang-utils'
* const data = deepClone<{value:string}>({value: 'name'})
* ```
* @export 深拷贝任意类型数据
*
* @param data 任意类型数据
* @returns
*/
export /* Example usages of 'deepClone' are shown below:
result[key] = deepClone(data[key]);
*/
function deepClone<T>(data) {
if (!data || !(data instanceof Object) || typeof data === 'function') {
return data
}
let constructor = data.constructor
let result = new constructor()
for (let key in data) {
if (data.hasOwnProperty(key)) {
result[key] = deepClone(data[key])
}
}
return result
}
/**
* @export 判断两个变量值是否完全相同
* @param a 任何类型变量
* @param b 任何类型变量
*/
export /* Example usages of 'isEquals' are shown below:
isEquals(a[k], b[k]);
*/
function isEquals(a, b) {
if (a === b) return true
if (a instanceof Date && b instanceof Date) return a.getTime() === b.getTime()
if (!a || !b || (typeof a !== 'object' && typeof b !== 'object')) return a === b
if (a.prototype !== b.prototype) return false
if (Array.isArray(a) && Array.isArray(b)) a.sort(), b.sort()
let keys = Object.keys(a)
if (keys.length !== Object.keys(b).length) return false
return keys.every(k => isEquals(a[k], b[k]))
}
/**
* @export 对象序列化
* @param obj 任意对象
* @return
*/
export function stringfyQueryString(obj) {
if (!obj) return ''
const pairs = []
for (let key in obj) {
let value = obj[key]
if (value instanceof Array) {
for (let i = 0; i < value.length; ++i) {
pairs.push(encodeURIComponent(key + '[' + i + ']') + '=' + encodeURIComponent(value[i]))
}
continue
}
pairs.push(encodeURIComponent(key) + '=' + encodeURIComponent(obj[key]))
}
return pairs.join('&')
}
/**
* @export 生成指定范围随机数
* @param {Number} min 最小值
* @param {Number} max 最大值
* @return {Number}
*/
export function randomNum(min, max) {
if (typeof min === 'number' && typeof max === 'number')
return Math.floor(min + Math.random() * (max - min))
return 0
}
/**
* @export 时间格式化
* @param {*} date Date对象,string 或 number 的毫秒事件数
* @param {string} fmt 格式类型为:"yyyy-MM-dd hh:mm:ss"
* @returns {string}
*/
export function formatDate(date, fmt = 'yyyy-MM-dd hh:mm:ss') {
if (!date) {
return '--'
}
if (typeof date === 'string' && !/-/.test(date)) date = Number(date)
date = new Date(date)
let o = {
'M+': date.getMonth() + 1, // 月份
'd+': date.getDate(), // 日
'h+': date.getHours(), // 小时
'm+': date.getMinutes(), // 分
's+': date.getSeconds(), // 秒
'q+': Math.floor((date.getMonth() + 3) / 3), // 季度
S: date.getMilliseconds() // 毫秒
}
if (/(y+)/.test(fmt))
fmt = fmt.replace(RegExp.$1, (date.getFullYear() + '').substr(4 - RegExp.$1.length))
for (let k in o) {
if (new RegExp('(' + k + ')').test(fmt))
fmt = fmt.replace(
RegExp.$1,
RegExp.$1.length === 1 ? o[k] : ('00' + o[k]).substr(('' + o[k]).length)
)
}
return fmt
}
|
6478bea094a31a7ec544167c5477da0c204ff43f | 1,935 | ts | TypeScript | src/lib/bezier.ts | Lantern-chat/frontend | 9bf63a15e45329a46415e954efdb263860a22a67 | [
"FSFAP"
] | 4 | 2022-01-26T20:07:24.000Z | 2022-03-23T06:10:08.000Z | src/lib/bezier.ts | Lantern-chat/frontend | 9bf63a15e45329a46415e954efdb263860a22a67 | [
"FSFAP"
] | 2 | 2022-01-26T19:27:06.000Z | 2022-02-23T15:53:11.000Z | src/lib/bezier.ts | Lantern-chat/frontend | 9bf63a15e45329a46415e954efdb263860a22a67 | [
"FSFAP"
] | null | null | null | const EPSILON = 1e-2; // Precision
// https://github.com/thednp/CubicBezier
export class CubicBezier {
cx: number;
bx: number;
ax: number;
cy: number;
by: number;
ay: number;
constructor(p1x: number, p1y: number, p2x: number, p2y: number) {
this.cx = 3.0 * p1x;
this.bx = 3.0 * (p2x - p1x) - this.cx;
this.ax = 1.0 - this.cx - this.bx;
this.cy = 3.0 * p1y;
this.by = 3.0 * (p2y - p1y) - this.cy;
this.ay = 1.0 - this.cy - this.by;
}
/// Return the X value at T
tx(t: number): number {
return ((this.ax * t + this.bx) * t + this.cx) * t;
}
/// Return the Y value at T
ty(t: number): number {
return ((this.ay * t + this.by) * t + this.cy) * t;
}
/// Return the derivative with respect to X at T
tdx(t: number): number {
return (3.0 * this.ax * t + 2.0 * this.bx) * t + this.cx;
}
/// Compute the Y value at X
y(x: number): number {
if(x <= 0) return 0;
if(x >= 1) return 1;
return this.ty(this.solve_x(x));
}
/// Solve for T at X
solve_x(x: number): number {
let t0, t1, t2, x2, d2, i;
// First try a few iterations of Newton's method -- normally very fast.
for(t2 = x, i = 0; i < 32; i += 1) {
x2 = this.tx(t2) - x;
if(Math.abs(x2) < EPSILON) return t2;
d2 = this.tdx(t2);
if(Math.abs(d2) < EPSILON) break;
t2 -= x2 / d2;
}
// No solution found - use bi-section
t0 = 0.0;
t1 = 1.0;
t2 = x;
if(t2 < t0) return t0;
if(t2 > t1) return t1;
while(t0 < t1) {
x2 = this.tx(t2);
if(Math.abs(x2 - x) < EPSILON) return t2;
if(x > x2) t0 = t2;
else t1 = t2;
t2 = (t1 - t0) * 0.5 + t0;
}
// Give up
return t2;
}
} | 25.12987 | 79 | 0.463566 | 54 | 6 | 0 | 9 | 7 | 6 | 4 | 0 | 20 | 1 | 0 | 5.5 | 708 | 0.021186 | 0.009887 | 0.008475 | 0.001412 | 0 | 0 | 0.714286 | 0.254292 | const EPSILON = 1e-2; // Precision
// https://github.com/thednp/CubicBezier
export class CubicBezier {
cx;
bx;
ax;
cy;
by;
ay;
constructor(p1x, p1y, p2x, p2y) {
this.cx = 3.0 * p1x;
this.bx = 3.0 * (p2x - p1x) - this.cx;
this.ax = 1.0 - this.cx - this.bx;
this.cy = 3.0 * p1y;
this.by = 3.0 * (p2y - p1y) - this.cy;
this.ay = 1.0 - this.cy - this.by;
}
/// Return the X value at T
tx(t) {
return ((this.ax * t + this.bx) * t + this.cx) * t;
}
/// Return the Y value at T
ty(t) {
return ((this.ay * t + this.by) * t + this.cy) * t;
}
/// Return the derivative with respect to X at T
tdx(t) {
return (3.0 * this.ax * t + 2.0 * this.bx) * t + this.cx;
}
/// Compute the Y value at X
y(x) {
if(x <= 0) return 0;
if(x >= 1) return 1;
return this.ty(this.solve_x(x));
}
/// Solve for T at X
solve_x(x) {
let t0, t1, t2, x2, d2, i;
// First try a few iterations of Newton's method -- normally very fast.
for(t2 = x, i = 0; i < 32; i += 1) {
x2 = this.tx(t2) - x;
if(Math.abs(x2) < EPSILON) return t2;
d2 = this.tdx(t2);
if(Math.abs(d2) < EPSILON) break;
t2 -= x2 / d2;
}
// No solution found - use bi-section
t0 = 0.0;
t1 = 1.0;
t2 = x;
if(t2 < t0) return t0;
if(t2 > t1) return t1;
while(t0 < t1) {
x2 = this.tx(t2);
if(Math.abs(x2 - x) < EPSILON) return t2;
if(x > x2) t0 = t2;
else t1 = t2;
t2 = (t1 - t0) * 0.5 + t0;
}
// Give up
return t2;
}
} |
db376862601a94fa1ae1b06de6200da26d207e77 | 2,010 | ts | TypeScript | src/main.ts | aryelgois/br-timezone | 7f8f30f6dabe3ce26c20f158807e5213b49fb4dd | [
"MIT"
] | 2 | 2022-01-21T15:10:57.000Z | 2022-01-21T15:21:47.000Z | src/main.ts | aryelgois/br-timezone | 7f8f30f6dabe3ce26c20f158807e5213b49fb4dd | [
"MIT"
] | null | null | null | src/main.ts | aryelgois/br-timezone | 7f8f30f6dabe3ce26c20f158807e5213b49fb4dd | [
"MIT"
] | null | null | null | export const brStates = [
'AC', 'AL', 'AM', 'AP', 'BA', 'CE', 'DF', 'ES', 'GO',
'MA', 'MG', 'MS', 'MT', 'PA', 'PB', 'PE', 'PI', 'PR',
'RJ', 'RN', 'RO', 'RR', 'RS', 'SC', 'SE', 'SP', 'TO'
] as const
export type BrState = typeof brStates[number]
function isBrState (stateCode: any): stateCode is BrState {
return brStates.includes(stateCode)
}
const timezoneByCity: Array<[string, string[]]> = [
['America/Araguaina', ['1702109']],
['America/Eirunepe', ['1301407']],
['America/Noronha', ['2605459']],
[
'America/Rio_Branco',
[
'1300201', '1300607', '1300706', '1301506', '1301654', '1301803',
'1301951', '1302306', '1302405', '1303502', '1303908', '1304062'
]
],
['America/Santarem', ['1506807']]
]
const timezoneByState: Array<[string, BrState[]]> = [
['America/Bahia', ['BA']],
['America/Belem', ['AP', 'PA', 'TO']],
['America/Boa_Vista', ['RR']],
['America/Campo_Grande', ['MS']],
['America/Cuiaba', ['MT']],
['America/Fortaleza', ['CE', 'MA', 'PI', 'RN']],
['America/Maceio', ['AL', 'SE']],
['America/Manaus', ['AM']],
['America/Porto_Velho', ['RO']],
['America/Recife', ['PB', 'PE']],
['America/Rio_Branco', ['AC']],
['America/Sao_Paulo', ['DF', 'ES', 'GO', 'MG', 'PR', 'RJ', 'RS', 'SC', 'SP']]
]
function findTimezone <T> (map: Array<[string, T[]]>, value: T): string | null {
for (const [timezone, list] of map) {
if (list.includes(value)) {
return timezone
}
}
return null
}
export function getBrTimezone (stateCode: string, ibgeCode?: string): string {
if (!isBrState(stateCode)) {
throw new Error(`Invalid State Code: '${stateCode}'`)
}
let timezone: string | null
if (ibgeCode !== undefined) {
timezone = findTimezone(timezoneByCity, ibgeCode)
if (timezone !== null) {
return timezone
}
}
timezone = findTimezone(timezoneByState, stateCode)
if (timezone !== null) {
return timezone
}
throw new Error(`State Code '${stateCode}' is not mapped to a timezone`)
}
| 27.916667 | 80 | 0.579602 | 61 | 3 | 0 | 5 | 4 | 0 | 2 | 1 | 10 | 1 | 1 | 7.333333 | 767 | 0.01043 | 0.005215 | 0 | 0.001304 | 0.001304 | 0.083333 | 0.833333 | 0.211491 | export const brStates = [
'AC', 'AL', 'AM', 'AP', 'BA', 'CE', 'DF', 'ES', 'GO',
'MA', 'MG', 'MS', 'MT', 'PA', 'PB', 'PE', 'PI', 'PR',
'RJ', 'RN', 'RO', 'RR', 'RS', 'SC', 'SE', 'SP', 'TO'
] as const
export type BrState = typeof brStates[number]
/* Example usages of 'isBrState' are shown below:
!isBrState(stateCode);
*/
function isBrState (stateCode): stateCode is BrState {
return brStates.includes(stateCode)
}
const timezoneByCity = [
['America/Araguaina', ['1702109']],
['America/Eirunepe', ['1301407']],
['America/Noronha', ['2605459']],
[
'America/Rio_Branco',
[
'1300201', '1300607', '1300706', '1301506', '1301654', '1301803',
'1301951', '1302306', '1302405', '1303502', '1303908', '1304062'
]
],
['America/Santarem', ['1506807']]
]
const timezoneByState = [
['America/Bahia', ['BA']],
['America/Belem', ['AP', 'PA', 'TO']],
['America/Boa_Vista', ['RR']],
['America/Campo_Grande', ['MS']],
['America/Cuiaba', ['MT']],
['America/Fortaleza', ['CE', 'MA', 'PI', 'RN']],
['America/Maceio', ['AL', 'SE']],
['America/Manaus', ['AM']],
['America/Porto_Velho', ['RO']],
['America/Recife', ['PB', 'PE']],
['America/Rio_Branco', ['AC']],
['America/Sao_Paulo', ['DF', 'ES', 'GO', 'MG', 'PR', 'RJ', 'RS', 'SC', 'SP']]
]
/* Example usages of 'findTimezone' are shown below:
timezone = findTimezone(timezoneByCity, ibgeCode);
timezone = findTimezone(timezoneByState, stateCode);
*/
function findTimezone <T> (map, value) {
for (const [timezone, list] of map) {
if (list.includes(value)) {
return timezone
}
}
return null
}
export function getBrTimezone (stateCode, ibgeCode?) {
if (!isBrState(stateCode)) {
throw new Error(`Invalid State Code: '${stateCode}'`)
}
let timezone
if (ibgeCode !== undefined) {
timezone = findTimezone(timezoneByCity, ibgeCode)
if (timezone !== null) {
return timezone
}
}
timezone = findTimezone(timezoneByState, stateCode)
if (timezone !== null) {
return timezone
}
throw new Error(`State Code '${stateCode}' is not mapped to a timezone`)
}
|
db66edaa360f29a56c384ee5767dfb683b38958f | 5,915 | ts | TypeScript | packages/convertor/src/index.ts | linyisonger/Ru.Toolkit | 9c5ca09e6565ef36a3428fd5e24709d309468519 | [
"MIT"
] | 1 | 2022-03-01T03:06:28.000Z | 2022-03-01T03:06:28.000Z | packages/convertor/src/index.ts | linyisonger/Ru.Toolkit | 9c5ca09e6565ef36a3428fd5e24709d309468519 | [
"MIT"
] | null | null | null | packages/convertor/src/index.ts | linyisonger/Ru.Toolkit | 9c5ca09e6565ef36a3428fd5e24709d309468519 | [
"MIT"
] | null | null | null | // 加解密
class Base64 {
// private property
static keyStr = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";
// public method for encoding
/**
* 加密
*/
static encode(input: string) {
let output = "";
let chr1, chr2, chr3, enc1, enc2, enc3, enc4;
let i = 0;
input = this._utf8_encode(input);
while (i < input.length) {
chr1 = input.charCodeAt(i++);
chr2 = input.charCodeAt(i++);
chr3 = input.charCodeAt(i++);
enc1 = chr1 >> 2;
enc2 = ((chr1 & 3) << 4) | (chr2 >> 4);
enc3 = ((chr2 & 15) << 2) | (chr3 >> 6);
enc4 = chr3 & 63;
if (isNaN(chr2)) {
enc3 = enc4 = 64;
} else if (isNaN(chr3)) {
enc4 = 64;
}
output = output +
this.keyStr.charAt(enc1) + this.keyStr.charAt(enc2) +
this.keyStr.charAt(enc3) + this.keyStr.charAt(enc4);
}
return output;
}
// public method for decoding
/**
* 解密
*/
static decode(input: string) {
let output = "";
let chr1, chr2, chr3;
let enc1, enc2, enc3, enc4;
let i = 0;
input = input.replace(/[^A-Za-z0-9\+\/\=]/g, "");
while (i < input.length) {
enc1 = this.keyStr.indexOf(input.charAt(i++));
enc2 = this.keyStr.indexOf(input.charAt(i++));
enc3 = this.keyStr.indexOf(input.charAt(i++));
enc4 = this.keyStr.indexOf(input.charAt(i++));
chr1 = (enc1 << 2) | (enc2 >> 4);
chr2 = ((enc2 & 15) << 4) | (enc3 >> 2);
chr3 = ((enc3 & 3) << 6) | enc4;
output = output + String.fromCharCode(chr1);
if (enc3 != 64) {
output = output + String.fromCharCode(chr2);
}
if (enc4 != 64) {
output = output + String.fromCharCode(chr3);
}
}
output = this._utf8_decode(output);
return output;
}
// private method for UTF-8 encoding
static _utf8_encode(string: string) {
string = string.replace(/\r\n/g, "\n");
let utftext = "";
for (let n = 0; n < string.length; n++) {
let c = string.charCodeAt(n);
if (c < 128) {
utftext += String.fromCharCode(c);
} else if ((c > 127) && (c < 2048)) {
utftext += String.fromCharCode((c >> 6) | 192);
utftext += String.fromCharCode((c & 63) | 128);
} else {
utftext += String.fromCharCode((c >> 12) | 224);
utftext += String.fromCharCode(((c >> 6) & 63) | 128);
utftext += String.fromCharCode((c & 63) | 128);
}
}
return utftext;
}
// private method for UTF-8 decoding
static _utf8_decode(utftext: string) {
let str = "";
let i = 0;
let c = 0;
let c1 = 0;
let c2 = 0;
while (i < utftext.length) {
c = utftext.charCodeAt(i);
if (c < 128) {
str += String.fromCharCode(c);
i++;
} else if ((c > 191) && (c < 224)) {
c2 = utftext.charCodeAt(i + 1);
str += String.fromCharCode(((c & 31) << 6) | (c2 & 63));
i += 2;
} else {
c2 = utftext.charCodeAt(i + 1);
c1 = utftext.charCodeAt(i + 2);
str += String.fromCharCode(((c & 15) << 12) | ((c2 & 63) << 6) | (c1 & 63));
i += 3;
}
}
return str;
}
}
/**
* 转换拓展类
*/
export class Convertor {
/**
* 社会统一信用代码转换组织机构代码
* @param usci 社会统一信用代码
* @returns 组织机构代码
*/
static usciToOibc(usci: string): string {
if (usci.length != 18) return "" // 长度不正确
return usci.substring(8, 16) + '-' + usci.substring(16, 17);
}
/**
* 时间格式化
* @param date 日期
* @param fmt 格式化方案
* @returns
*/
static timeFormat(date: Date, fmt: string = "yyyy-MM-dd hh:mm:ss"): string {
let o: any = {
"M+": date.getMonth() + 1, //月份
"d+": date.getDate(), //日
"h+": date.getHours(), //小时
"m+": date.getMinutes(), //分
"s+": date.getSeconds(), //秒
"q+": Math.floor((date.getMonth() + 3) / 3), //季度
"S": date.getMilliseconds() //毫秒
};
let r = /(y+)/.exec(fmt);
if (r) fmt = fmt.replace(r[0], (date.getFullYear() + "").substring(4 - r[0].length));
for (let k in o) {
r = new RegExp("(" + k + ")").exec(fmt)
if (r) fmt = fmt.replace(r[0], (r[0].length == 1) ? (o[k]) : (("00" + o[k]).substring(("" + o[k]).length)));
}
return fmt;
}
/**
* 千分位处理
* @param num 数值
* @returns
*/
static thousands(num: number | string): string {
let str = num + '';
return str.replace(/\d{1,3}(?=(\d{3})+$)/g, (s) => s + ',')
}
/**
* 文本转base64
* @param text 文本
* @returns
*/
static textToBase64(text: string): string {
return Base64.encode(text)
}
/**
* base64转文本
* @param base64
* @returns
*/
static base64ToText(base64: string): string {
return Base64.decode(base64)
}
/**
* json对象转换base64
* @param json
* @returns
*/
static jsonToBase64<T>(json: T): string {
return this.textToBase64(JSON.stringify(json))
}
/**
* base64转换json对象
* @param base64
* @returns
*/
static base64ToJson<T>(base64: string): T {
return JSON.parse(this.base64ToText(base64))
}
}
| 31.296296 | 120 | 0.444463 | 134 | 12 | 0 | 13 | 29 | 1 | 6 | 1 | 17 | 2 | 0 | 9 | 1,819 | 0.013744 | 0.015943 | 0.00055 | 0.0011 | 0 | 0.018182 | 0.309091 | 0.256913 | // 加解密
class Base64 {
// private property
static keyStr = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";
// public method for encoding
/**
* 加密
*/
static encode(input) {
let output = "";
let chr1, chr2, chr3, enc1, enc2, enc3, enc4;
let i = 0;
input = this._utf8_encode(input);
while (i < input.length) {
chr1 = input.charCodeAt(i++);
chr2 = input.charCodeAt(i++);
chr3 = input.charCodeAt(i++);
enc1 = chr1 >> 2;
enc2 = ((chr1 & 3) << 4) | (chr2 >> 4);
enc3 = ((chr2 & 15) << 2) | (chr3 >> 6);
enc4 = chr3 & 63;
if (isNaN(chr2)) {
enc3 = enc4 = 64;
} else if (isNaN(chr3)) {
enc4 = 64;
}
output = output +
this.keyStr.charAt(enc1) + this.keyStr.charAt(enc2) +
this.keyStr.charAt(enc3) + this.keyStr.charAt(enc4);
}
return output;
}
// public method for decoding
/**
* 解密
*/
static decode(input) {
let output = "";
let chr1, chr2, chr3;
let enc1, enc2, enc3, enc4;
let i = 0;
input = input.replace(/[^A-Za-z0-9\+\/\=]/g, "");
while (i < input.length) {
enc1 = this.keyStr.indexOf(input.charAt(i++));
enc2 = this.keyStr.indexOf(input.charAt(i++));
enc3 = this.keyStr.indexOf(input.charAt(i++));
enc4 = this.keyStr.indexOf(input.charAt(i++));
chr1 = (enc1 << 2) | (enc2 >> 4);
chr2 = ((enc2 & 15) << 4) | (enc3 >> 2);
chr3 = ((enc3 & 3) << 6) | enc4;
output = output + String.fromCharCode(chr1);
if (enc3 != 64) {
output = output + String.fromCharCode(chr2);
}
if (enc4 != 64) {
output = output + String.fromCharCode(chr3);
}
}
output = this._utf8_decode(output);
return output;
}
// private method for UTF-8 encoding
static _utf8_encode(string) {
string = string.replace(/\r\n/g, "\n");
let utftext = "";
for (let n = 0; n < string.length; n++) {
let c = string.charCodeAt(n);
if (c < 128) {
utftext += String.fromCharCode(c);
} else if ((c > 127) && (c < 2048)) {
utftext += String.fromCharCode((c >> 6) | 192);
utftext += String.fromCharCode((c & 63) | 128);
} else {
utftext += String.fromCharCode((c >> 12) | 224);
utftext += String.fromCharCode(((c >> 6) & 63) | 128);
utftext += String.fromCharCode((c & 63) | 128);
}
}
return utftext;
}
// private method for UTF-8 decoding
static _utf8_decode(utftext) {
let str = "";
let i = 0;
let c = 0;
let c1 = 0;
let c2 = 0;
while (i < utftext.length) {
c = utftext.charCodeAt(i);
if (c < 128) {
str += String.fromCharCode(c);
i++;
} else if ((c > 191) && (c < 224)) {
c2 = utftext.charCodeAt(i + 1);
str += String.fromCharCode(((c & 31) << 6) | (c2 & 63));
i += 2;
} else {
c2 = utftext.charCodeAt(i + 1);
c1 = utftext.charCodeAt(i + 2);
str += String.fromCharCode(((c & 15) << 12) | ((c2 & 63) << 6) | (c1 & 63));
i += 3;
}
}
return str;
}
}
/**
* 转换拓展类
*/
export class Convertor {
/**
* 社会统一信用代码转换组织机构代码
* @param usci 社会统一信用代码
* @returns 组织机构代码
*/
static usciToOibc(usci) {
if (usci.length != 18) return "" // 长度不正确
return usci.substring(8, 16) + '-' + usci.substring(16, 17);
}
/**
* 时间格式化
* @param date 日期
* @param fmt 格式化方案
* @returns
*/
static timeFormat(date, fmt = "yyyy-MM-dd hh:mm:ss") {
let o = {
"M+": date.getMonth() + 1, //月份
"d+": date.getDate(), //日
"h+": date.getHours(), //小时
"m+": date.getMinutes(), //分
"s+": date.getSeconds(), //秒
"q+": Math.floor((date.getMonth() + 3) / 3), //季度
"S": date.getMilliseconds() //毫秒
};
let r = /(y+)/.exec(fmt);
if (r) fmt = fmt.replace(r[0], (date.getFullYear() + "").substring(4 - r[0].length));
for (let k in o) {
r = new RegExp("(" + k + ")").exec(fmt)
if (r) fmt = fmt.replace(r[0], (r[0].length == 1) ? (o[k]) : (("00" + o[k]).substring(("" + o[k]).length)));
}
return fmt;
}
/**
* 千分位处理
* @param num 数值
* @returns
*/
static thousands(num) {
let str = num + '';
return str.replace(/\d{1,3}(?=(\d{3})+$)/g, (s) => s + ',')
}
/**
* 文本转base64
* @param text 文本
* @returns
*/
static textToBase64(text) {
return Base64.encode(text)
}
/**
* base64转文本
* @param base64
* @returns
*/
static base64ToText(base64) {
return Base64.decode(base64)
}
/**
* json对象转换base64
* @param json
* @returns
*/
static jsonToBase64<T>(json) {
return this.textToBase64(JSON.stringify(json))
}
/**
* base64转换json对象
* @param base64
* @returns
*/
static base64ToJson<T>(base64) {
return JSON.parse(this.base64ToText(base64))
}
}
|
639f0a493017ff95c94330e7560433867dc8b550 | 1,246 | ts | TypeScript | frontend/src/container/GeneralSettings/utils.ts | prashant-shahi/signoz | 9c8c31d912c7d0d78eeb84f1a21f7dc37553c134 | [
"MIT"
] | null | null | null | frontend/src/container/GeneralSettings/utils.ts | prashant-shahi/signoz | 9c8c31d912c7d0d78eeb84f1a21f7dc37553c134 | [
"MIT"
] | 1 | 2022-02-08T17:35:02.000Z | 2022-02-08T17:35:02.000Z | frontend/src/container/GeneralSettings/utils.ts | prashant-shahi/signoz | 9c8c31d912c7d0d78eeb84f1a21f7dc37553c134 | [
"MIT"
] | null | null | null | export type SettingPeriod = 'hr' | 'day' | 'month';
export interface ITimeUnit {
value: SettingPeriod;
key: string;
multiplier: number;
}
export const TimeUnits: ITimeUnit[] = [
{
value: 'hr',
key: 'Hours',
multiplier: 1,
},
{
value: 'day',
key: 'Days',
multiplier: 1 / 24,
},
{
value: 'month',
key: 'Months',
multiplier: 1 / (24 * 30),
},
];
interface ITimeUnitConversion {
value: number;
timeUnitValue: SettingPeriod;
}
export const convertHoursValueToRelevantUnit = (
value: number,
): ITimeUnitConversion => {
if (value)
for (let idx = TimeUnits.length - 1; idx >= 0; idx -= 1) {
const timeUnit = TimeUnits[idx];
const convertedValue = timeUnit.multiplier * value;
if (
convertedValue >= 1 &&
convertedValue === parseInt(`${convertedValue}`, 10)
) {
return { value: convertedValue, timeUnitValue: timeUnit.value };
}
}
return { value, timeUnitValue: TimeUnits[0].value };
};
export const convertHoursValueToRelevantUnitString = (
value: number,
): string => {
if (!value) return '';
const convertedTimeUnit = convertHoursValueToRelevantUnit(value);
return `${convertedTimeUnit.value} ${convertedTimeUnit.timeUnitValue}${
convertedTimeUnit.value >= 2 ? 's' : ''
}`;
};
| 21.859649 | 72 | 0.661316 | 52 | 2 | 0 | 2 | 7 | 5 | 1 | 0 | 6 | 3 | 0 | 8.5 | 405 | 0.009877 | 0.017284 | 0.012346 | 0.007407 | 0 | 0 | 0.375 | 0.261347 | export type SettingPeriod = 'hr' | 'day' | 'month';
export interface ITimeUnit {
value;
key;
multiplier;
}
export const TimeUnits = [
{
value: 'hr',
key: 'Hours',
multiplier: 1,
},
{
value: 'day',
key: 'Days',
multiplier: 1 / 24,
},
{
value: 'month',
key: 'Months',
multiplier: 1 / (24 * 30),
},
];
interface ITimeUnitConversion {
value;
timeUnitValue;
}
export /* Example usages of 'convertHoursValueToRelevantUnit' are shown below:
convertHoursValueToRelevantUnit(value);
*/
const convertHoursValueToRelevantUnit = (
value,
) => {
if (value)
for (let idx = TimeUnits.length - 1; idx >= 0; idx -= 1) {
const timeUnit = TimeUnits[idx];
const convertedValue = timeUnit.multiplier * value;
if (
convertedValue >= 1 &&
convertedValue === parseInt(`${convertedValue}`, 10)
) {
return { value: convertedValue, timeUnitValue: timeUnit.value };
}
}
return { value, timeUnitValue: TimeUnits[0].value };
};
export const convertHoursValueToRelevantUnitString = (
value,
) => {
if (!value) return '';
const convertedTimeUnit = convertHoursValueToRelevantUnit(value);
return `${convertedTimeUnit.value} ${convertedTimeUnit.timeUnitValue}${
convertedTimeUnit.value >= 2 ? 's' : ''
}`;
};
|
63e1ec43873557aad6ce5230bd635656a9eccd96 | 1,625 | ts | TypeScript | src/Utilities/CsvUtils.ts | brendanjmeade/celeri_ui | d0a804d5d48ff9413c6cf257330ce5e7e82b364a | [
"MIT"
] | 1 | 2022-03-02T14:49:56.000Z | 2022-03-02T14:49:56.000Z | src/Utilities/CsvUtils.ts | brendanjmeade/celeri_ui | d0a804d5d48ff9413c6cf257330ce5e7e82b364a | [
"MIT"
] | 27 | 2022-02-02T16:02:18.000Z | 2022-03-30T21:07:11.000Z | src/Utilities/CsvUtils.ts | brendanjmeade/celeri_ui | d0a804d5d48ff9413c6cf257330ce5e7e82b364a | [
"MIT"
] | null | null | null | /* eslint-disable @typescript-eslint/no-magic-numbers */
export function parse(contents: string): Record<string, number | string>[] {
const rows = contents.split(/\n/g)
const headers = rows[0].split(',').map(h => h.trim())
const remaining = rows.slice(1)
const items: Record<string, number | string>[] = []
for (const row of remaining) {
if (row.trim() !== '') {
const rowSplit = row.split(/\s*,\s*/)
const item: Record<string, number | string> = {}
// eslint-disable-next-line unicorn/no-for-loop
for (let index = 0; index < headers.length; index += 1) {
let value: number | string = rowSplit[index]
const header = headers[index]
const number = Number.parseFloat(value)
value = Number.isNaN(number) ? value : number
if (typeof value === 'string') {
value =
value.startsWith(`"`) && value.endsWith(`"`)
? value.slice(1, -1).trim()
: value.trim()
}
item[header] = value
}
items.push(item)
}
}
return items
}
export function stringify<T>(array: T[], headers: string[]): string {
const rows = [headers.join(',')]
for (const item of array) {
const record = item as unknown as Record<string, number | string>
rows.push(
headers
.map(key => {
if (key in record) {
const value = record[key]
return typeof value === 'string' && /\s/.test(`${value}`)
? `"${value.trim()}"`
: `${
typeof value === 'number' &&
(key.includes('lon') || key.includes('lat'))
? value.toFixed(6)
: value
}`
}
return ''
})
.join(',')
)
}
return rows.join('\n')
}
| 29.017857 | 76 | 0.572923 | 52 | 4 | 0 | 5 | 13 | 0 | 0 | 0 | 18 | 0 | 5 | 15.25 | 514 | 0.01751 | 0.025292 | 0 | 0 | 0.009728 | 0 | 0.818182 | 0.291172 | /* eslint-disable @typescript-eslint/no-magic-numbers */
export function parse(contents) {
const rows = contents.split(/\n/g)
const headers = rows[0].split(',').map(h => h.trim())
const remaining = rows.slice(1)
const items = []
for (const row of remaining) {
if (row.trim() !== '') {
const rowSplit = row.split(/\s*,\s*/)
const item = {}
// eslint-disable-next-line unicorn/no-for-loop
for (let index = 0; index < headers.length; index += 1) {
let value = rowSplit[index]
const header = headers[index]
const number = Number.parseFloat(value)
value = Number.isNaN(number) ? value : number
if (typeof value === 'string') {
value =
value.startsWith(`"`) && value.endsWith(`"`)
? value.slice(1, -1).trim()
: value.trim()
}
item[header] = value
}
items.push(item)
}
}
return items
}
export function stringify<T>(array, headers) {
const rows = [headers.join(',')]
for (const item of array) {
const record = item as unknown as Record<string, number | string>
rows.push(
headers
.map(key => {
if (key in record) {
const value = record[key]
return typeof value === 'string' && /\s/.test(`${value}`)
? `"${value.trim()}"`
: `${
typeof value === 'number' &&
(key.includes('lon') || key.includes('lat'))
? value.toFixed(6)
: value
}`
}
return ''
})
.join(',')
)
}
return rows.join('\n')
}
|
83fe848d25f3b8a39f2fc8e8921c7cd1252f9130 | 1,781 | ts | TypeScript | measure/DataSourceSpec.ts | umdsquare/data-at-hand-core | 31352ae1447b66a175ca099eb0ffa53dc201cbc3 | [
"MIT"
] | 1 | 2022-02-08T18:15:27.000Z | 2022-02-08T18:15:27.000Z | measure/DataSourceSpec.ts | umdsquare/data-at-hand-core | 31352ae1447b66a175ca099eb0ffa53dc201cbc3 | [
"MIT"
] | null | null | null | measure/DataSourceSpec.ts | umdsquare/data-at-hand-core | 31352ae1447b66a175ca099eb0ffa53dc201cbc3 | [
"MIT"
] | 1 | 2022-02-08T18:15:31.000Z | 2022-02-08T18:15:31.000Z | export enum DataSourceCategory{
Step="step",
Sleep="sleep",
Weight="weight",
HeartRate="heartRate"
}
export enum DataSourceType{
StepCount="step_count",
HoursSlept="sleep_duration",
SleepRange="sleep_range",
HeartRate="heart_rate",
Weight="weight",
}
export interface DataSourceSpec{
category: DataSourceCategory,
type: DataSourceType,
name: string,
description: string,
}
export interface DataSourceCategorySpec{
category: DataSourceCategory,
name: string
}
export enum MeasureUnitType{
Metric = "metric",
US = "us"
}
export enum IntraDayDataSourceType {
StepCount = "step",
HeartRate = "heart_rate",
Sleep = "sleep"
}
export function getIntraDayDataSourceName(type: IntraDayDataSourceType): string {
switch (type) {
case IntraDayDataSourceType.StepCount:
return "Step Count"
case IntraDayDataSourceType.Sleep:
return "Sleep"
case IntraDayDataSourceType.HeartRate:
return "Heart Rate"
}
}
export function inferIntraDayDataSourceType(dataSource: DataSourceType): IntraDayDataSourceType | null {
switch (dataSource) {
case DataSourceType.StepCount:
return IntraDayDataSourceType.StepCount
case DataSourceType.HeartRate:
return IntraDayDataSourceType.HeartRate
case DataSourceType.HoursSlept:
case DataSourceType.SleepRange:
return IntraDayDataSourceType.Sleep
default: return null
}
}
export function inferDataSource(intraDayDataSource: IntraDayDataSourceType): DataSourceType {
switch (intraDayDataSource) {
case IntraDayDataSourceType.StepCount:
return DataSourceType.StepCount
case IntraDayDataSourceType.Sleep:
return DataSourceType.SleepRange
case IntraDayDataSourceType.HeartRate:
return DataSourceType.HeartRate
}
} | 24.067568 | 104 | 0.754071 | 64 | 3 | 0 | 3 | 0 | 6 | 0 | 0 | 4 | 2 | 0 | 8.666667 | 454 | 0.013216 | 0 | 0.013216 | 0.004405 | 0 | 0 | 0.333333 | 0.207632 | export enum DataSourceCategory{
Step="step",
Sleep="sleep",
Weight="weight",
HeartRate="heartRate"
}
export enum DataSourceType{
StepCount="step_count",
HoursSlept="sleep_duration",
SleepRange="sleep_range",
HeartRate="heart_rate",
Weight="weight",
}
export interface DataSourceSpec{
category,
type,
name,
description,
}
export interface DataSourceCategorySpec{
category,
name
}
export enum MeasureUnitType{
Metric = "metric",
US = "us"
}
export enum IntraDayDataSourceType {
StepCount = "step",
HeartRate = "heart_rate",
Sleep = "sleep"
}
export function getIntraDayDataSourceName(type) {
switch (type) {
case IntraDayDataSourceType.StepCount:
return "Step Count"
case IntraDayDataSourceType.Sleep:
return "Sleep"
case IntraDayDataSourceType.HeartRate:
return "Heart Rate"
}
}
export function inferIntraDayDataSourceType(dataSource) {
switch (dataSource) {
case DataSourceType.StepCount:
return IntraDayDataSourceType.StepCount
case DataSourceType.HeartRate:
return IntraDayDataSourceType.HeartRate
case DataSourceType.HoursSlept:
case DataSourceType.SleepRange:
return IntraDayDataSourceType.Sleep
default: return null
}
}
export function inferDataSource(intraDayDataSource) {
switch (intraDayDataSource) {
case IntraDayDataSourceType.StepCount:
return DataSourceType.StepCount
case IntraDayDataSourceType.Sleep:
return DataSourceType.SleepRange
case IntraDayDataSourceType.HeartRate:
return DataSourceType.HeartRate
}
} |
75a670e99130e8849df2a75321ceea69d119503e | 1,176 | ts | TypeScript | src/util/schoolTransform.ts | Software-Meister-High-School-Community/MOIZA-Front | db0a6070f11bafb203da6d260ac9c82227a520a3 | [
"MIT"
] | 7 | 2022-02-20T20:24:46.000Z | 2022-03-15T00:06:38.000Z | src/util/schoolTransform.ts | Software-Meister-High-School-Community/MOIZA-Front | db0a6070f11bafb203da6d260ac9c82227a520a3 | [
"MIT"
] | 14 | 2022-02-21T12:41:21.000Z | 2022-03-29T13:19:02.000Z | src/util/schoolTransform.ts | Software-Meister-High-School-Community/MOIZA-Front | db0a6070f11bafb203da6d260ac9c82227a520a3 | [
"MIT"
] | null | null | null | class schoolTransform {
public schoolToEmail(mail: string): string {
let schoolMail = "";
switch (mail) {
case "광주소프트웨어마이스터고등학교":
schoolMail = "@gsm.hs.kr";
break;
case "대구소프트웨어마이스터고등학교":
schoolMail = "@dgsw.hs.kr";
break;
case "대덕소프트웨어마이스터고등학교":
schoolMail = "@dsm.hs.kr";
break;
case "미림마이스터고등학교":
schoolMail = "@e-mirim.hs.kr";
break;
case "부산소프트웨어마이스터고등학교":
schoolMail = "@bssm.hs.kr";
break;
default:
schoolMail = "@gsm.hs.kr";
break;
}
return schoolMail;
}
public schoolToAbbreviationName(school: string): string {
let name = "";
switch (school) {
case "광주소프트웨어마이스터고등학교":
name = "GSM";
break;
case "대구소프트웨어마이스터고등학교":
name = "DGSW";
break;
case "대덕소프트웨어마이스터고등학교":
name = "DSM";
break;
case "미림마이스터고등학교":
name = "NCMM";
break;
case "부산소프트웨어마이스터고등학교":
name = "BSSM";
break;
default:
name = "GSM";
break;
}
return name;
}
}
export default new schoolTransform();
| 19.6 | 59 | 0.517007 | 51 | 2 | 0 | 2 | 2 | 0 | 0 | 0 | 4 | 1 | 0 | 22 | 481 | 0.008316 | 0.004158 | 0 | 0.002079 | 0 | 0 | 0.666667 | 0.205631 | class schoolTransform {
public schoolToEmail(mail) {
let schoolMail = "";
switch (mail) {
case "광주소프트웨어마이스터고등학교":
schoolMail = "@gsm.hs.kr";
break;
case "대구소프트웨어마이스터고등학교":
schoolMail = "@dgsw.hs.kr";
break;
case "대덕소프트웨어마이스터고등학교":
schoolMail = "@dsm.hs.kr";
break;
case "미림마이스터고등학교":
schoolMail = "@e-mirim.hs.kr";
break;
case "부산소프트웨어마이스터고등학교":
schoolMail = "@bssm.hs.kr";
break;
default:
schoolMail = "@gsm.hs.kr";
break;
}
return schoolMail;
}
public schoolToAbbreviationName(school) {
let name = "";
switch (school) {
case "광주소프트웨어마이스터고등학교":
name = "GSM";
break;
case "대구소프트웨어마이스터고등학교":
name = "DGSW";
break;
case "대덕소프트웨어마이스터고등학교":
name = "DSM";
break;
case "미림마이스터고등학교":
name = "NCMM";
break;
case "부산소프트웨어마이스터고등학교":
name = "BSSM";
break;
default:
name = "GSM";
break;
}
return name;
}
}
export default new schoolTransform();
|
75cc216858cda81da5f47cc98579e10eec11b4c8 | 2,503 | ts | TypeScript | src/renderer/pages/main/utils/beats-detector.ts | maotoumao/desktop-pet | 23fdfc9c11dea4254bc26b2a67863f9a56ba5d0d | [
"MIT"
] | 1 | 2022-01-22T18:41:47.000Z | 2022-01-22T18:41:47.000Z | src/renderer/pages/main/utils/beats-detector.ts | maotoumao/desktop-pet | 23fdfc9c11dea4254bc26b2a67863f9a56ba5d0d | [
"MIT"
] | null | null | null | src/renderer/pages/main/utils/beats-detector.ts | maotoumao/desktop-pet | 23fdfc9c11dea4254bc26b2a67863f9a56ba5d0d | [
"MIT"
] | null | null | null | // @ts-nocheck
let counter = 0;
const beats = [];
function emitBpmEvent(value) {
if (beats.length >= 5) {
beats.shift();
}
beats.push(value);
if (!counter) {
window.Events.emit(
'musicBpm',
beats.length
? beats.reduce((prev, curr) => prev + curr) / beats.length
: 0
);
}
counter = (counter + 1) % 2;
}
async function record() {
const audioSource: MediaStream = await navigator.mediaDevices.getUserMedia({
audio: {
mandatory: {
chromeMediaSource: 'desktop',
},
},
video: {
mandatory: {
chromeMediaSource: 'desktop',
},
},
});
(audioSource.getVideoTracks() ?? []).forEach((track) => {
audioSource.removeTrack(track);
});
const sampleRate = 5120;
const context = new AudioContext({
sampleRate,
});
const processor = context.createScriptProcessor(16384, 2, 2);
processor.onaudioprocess = (e) => {
const bufferData = e.inputBuffer.getChannelData(0);
const duration = e.inputBuffer.duration;
// 实测 这个采样率足够了。那么接下来就瞎搞吧
// 采样率4096, 这段时间刚好4s,真的会有30bpm的歌吗
// 寻找peaks,先拿一个轨道看吧
// 先来个放大
const max = Math.max(...bufferData);
if (max < 0.3) {
// 听不见
emitBpmEvent(0);
return;
}
bufferData.forEach((k, index) => {
bufferData[index] = k / max;
});
const peaks = [];
bufferData.forEach((buf, index) => {
if (buf > 0.7) {
peaks.push(index);
}
});
let rhythms = [];
peaks.forEach((k, i) => i && rhythms.push(k - peaks[i - 1]));
rhythms = rhythms.filter((k) => k > sampleRate / 8);
if (!rhythms.length) {
emitBpmEvent(0);
return;
}
if (rhythms.length > 4) {
const avg =
(rhythms.reduce((prev, curr) => prev + curr) -
Math.max(...rhythms) -
Math.min(...rhythms)) /
(rhythms.length - 2);
const beat = (60 / avg) * sampleRate;
emitBpmEvent(beat > 200 ? beat / 2 : beat, rhythms.length);
} else {
const avg = rhythms.reduce((prev, curr) => prev + curr) / rhythms.length;
const beat = (60 / avg) * sampleRate;
emitBpmEvent(beat > 200 ? beat / 2 : beat, rhythms.length);
}
};
// 搞个低通滤波器
const mediaNode = context.createMediaStreamSource(audioSource);
const filterNode = context.createBiquadFilter();
filterNode.type = 'lowpass';
mediaNode.connect(filterNode);
filterNode.connect(processor);
processor.connect(context.destination);
}
export default record;
| 24.782178 | 79 | 0.581702 | 84 | 11 | 0 | 16 | 17 | 0 | 1 | 0 | 0 | 0 | 0 | 11.181818 | 839 | 0.032181 | 0.020262 | 0 | 0 | 0 | 0 | 0 | 0.311832 | // @ts-nocheck
let counter = 0;
const beats = [];
/* Example usages of 'emitBpmEvent' are shown below:
// 听不见
emitBpmEvent(0);
emitBpmEvent(0);
emitBpmEvent(beat > 200 ? beat / 2 : beat, rhythms.length);
*/
function emitBpmEvent(value) {
if (beats.length >= 5) {
beats.shift();
}
beats.push(value);
if (!counter) {
window.Events.emit(
'musicBpm',
beats.length
? beats.reduce((prev, curr) => prev + curr) / beats.length
: 0
);
}
counter = (counter + 1) % 2;
}
/* Example usages of 'record' are shown below:
;
*/
async function record() {
const audioSource = await navigator.mediaDevices.getUserMedia({
audio: {
mandatory: {
chromeMediaSource: 'desktop',
},
},
video: {
mandatory: {
chromeMediaSource: 'desktop',
},
},
});
(audioSource.getVideoTracks() ?? []).forEach((track) => {
audioSource.removeTrack(track);
});
const sampleRate = 5120;
const context = new AudioContext({
sampleRate,
});
const processor = context.createScriptProcessor(16384, 2, 2);
processor.onaudioprocess = (e) => {
const bufferData = e.inputBuffer.getChannelData(0);
const duration = e.inputBuffer.duration;
// 实测 这个采样率足够了。那么接下来就瞎搞吧
// 采样率4096, 这段时间刚好4s,真的会有30bpm的歌吗
// 寻找peaks,先拿一个轨道看吧
// 先来个放大
const max = Math.max(...bufferData);
if (max < 0.3) {
// 听不见
emitBpmEvent(0);
return;
}
bufferData.forEach((k, index) => {
bufferData[index] = k / max;
});
const peaks = [];
bufferData.forEach((buf, index) => {
if (buf > 0.7) {
peaks.push(index);
}
});
let rhythms = [];
peaks.forEach((k, i) => i && rhythms.push(k - peaks[i - 1]));
rhythms = rhythms.filter((k) => k > sampleRate / 8);
if (!rhythms.length) {
emitBpmEvent(0);
return;
}
if (rhythms.length > 4) {
const avg =
(rhythms.reduce((prev, curr) => prev + curr) -
Math.max(...rhythms) -
Math.min(...rhythms)) /
(rhythms.length - 2);
const beat = (60 / avg) * sampleRate;
emitBpmEvent(beat > 200 ? beat / 2 : beat, rhythms.length);
} else {
const avg = rhythms.reduce((prev, curr) => prev + curr) / rhythms.length;
const beat = (60 / avg) * sampleRate;
emitBpmEvent(beat > 200 ? beat / 2 : beat, rhythms.length);
}
};
// 搞个低通滤波器
const mediaNode = context.createMediaStreamSource(audioSource);
const filterNode = context.createBiquadFilter();
filterNode.type = 'lowpass';
mediaNode.connect(filterNode);
filterNode.connect(processor);
processor.connect(context.destination);
}
export default record;
|
f539e65447d2e78a613b80b1a7fd0613103db606 | 5,296 | ts | TypeScript | src/app/core/utils/helpers.ts | XT-Cheng/web-template | e744549f8144e5de7af24309604febc83e005e53 | [
"MIT"
] | null | null | null | src/app/core/utils/helpers.ts | XT-Cheng/web-template | e744549f8144e5de7af24309604febc83e005e53 | [
"MIT"
] | 1 | 2022-03-02T02:52:14.000Z | 2022-03-02T02:52:14.000Z | src/app/core/utils/helpers.ts | XT-Cheng/web-template | e744549f8144e5de7af24309604febc83e005e53 | [
"MIT"
] | null | null | null | //#region Decode related
export function urlBase64Decode(str: string): string {
let output = str.replace(/-/g, '+').replace(/_/g, '/');
switch (output.length % 4) {
case 0: { break; }
case 2: { output += '=='; break; }
case 3: { output += '='; break; }
default: {
throw new Error('Illegal base64url string!');
}
}
return b64DecodeUnicode(output);
}
export function b64decode(str: string): string {
const chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=';
let output = '';
str = String(str).replace(/=+$/, '');
if (str.length % 4 === 1) {
throw new Error(`'atob' failed: The string to be decoded is not correctly encoded.`);
}
for (
// initialize result and counters
let bc = 0, bs: any, buffer: any, idx = 0;
// get next character
buffer = str.charAt(idx++);
// character found in table? initialize bit storage and add its ascii value;
// tslint:disable-next-line:no-bitwise
~buffer && (bs = bc % 4 ? bs * 64 + buffer : buffer,
// and if not first of each 4 characters,
// convert the first 8 bits to one ascii character
// tslint:disable-next-line:no-bitwise
bc++ % 4) ? output += String.fromCharCode(255 & bs >> (-2 * bc & 6)) : 0
) {
// try to find character in table (0-63, not found => -1)
buffer = chars.indexOf(buffer);
}
return output;
}
// https://developer.mozilla.org/en/docs/Web/API/WindowBase64/Base64_encoding_and_decoding#The_Unicode_Problem
export function b64DecodeUnicode(str: any) {
return decodeURIComponent(Array.prototype.map.call(b64decode(str), (c: any) => {
return '%' + ('00' + c.charCodeAt(0).toString(16)).slice(-2);
}).join(''));
}
//#endregion
//#region Object related
export function getDeepFromObject(object = {}, name: string, defaultValue?: any) {
const keys = name.split('.');
// clone the object
let level = deepExtend({}, object || {});
keys.forEach((k) => {
if (level && typeof level[k] !== 'undefined') {
level = level[k];
} else {
level = undefined;
}
});
return typeof level === 'undefined' ? defaultValue : level;
}
const deepExtend = function (...objects: any[]): any {
if (arguments.length < 1 || typeof arguments[0] !== 'object') {
return false;
}
if (arguments.length < 2) {
return arguments[0];
}
const target = arguments[0];
// convert arguments to array and cut off target object
const args = Array.prototype.slice.call(arguments, 1);
let val, src;
args.forEach(function (obj: any) {
// skip argument if it is array or isn't object
if (typeof obj !== 'object' || Array.isArray(obj)) {
return;
}
Object.keys(obj).forEach(function (key) {
src = target[key]; // source value
val = obj[key]; // new value
// recursion prevention
if (val === target) {
return;
/**
* if new value isn't object then just overwrite by new value
* instead of extending.
*/
} else if (typeof val !== 'object' || val === null) {
target[key] = val;
return;
// just clone arrays (and recursive clone objects inside)
} else if (Array.isArray(val)) {
target[key] = deepCloneArray(val);
return;
// custom cloning and overwrite for specific objects
} else if (isSpecificValue(val)) {
target[key] = cloneSpecificValue(val);
return;
// overwrite by new value if source isn't object or array
} else if (typeof src !== 'object' || src === null || Array.isArray(src)) {
target[key] = deepExtend({}, val);
return;
// source value and new value is objects both, extending...
} else {
target[key] = deepExtend(src, val);
return;
}
});
});
return target;
};
/**
* Recursive cloning array.
*/
function deepCloneArray(arr: any[]): any {
const clone: any[] = [];
arr.forEach(function (item: any, index: any) {
if (typeof item === 'object' && item !== null) {
if (Array.isArray(item)) {
clone[index] = deepCloneArray(item);
} else if (isSpecificValue(item)) {
clone[index] = cloneSpecificValue(item);
} else {
clone[index] = deepExtend({}, item);
}
} else {
clone[index] = item;
}
});
return clone;
}
function isSpecificValue(val: any) {
return (
val instanceof Date
|| val instanceof RegExp
) ? true : false;
}
function cloneSpecificValue(val: any): any {
if (val instanceof Date) {
return new Date(val.getTime());
} else if (val instanceof RegExp) {
return new RegExp(val);
} else {
throw new Error('cloneSpecificValue: Unexpected situation');
}
}
//#endregion
| 29.752809 | 110 | 0.537953 | 117 | 13 | 0 | 16 | 15 | 0 | 6 | 16 | 5 | 0 | 11 | 12.538462 | 1,310 | 0.022137 | 0.01145 | 0 | 0 | 0.008397 | 0.363636 | 0.113636 | 0.253613 | //#region Decode related
export function urlBase64Decode(str) {
let output = str.replace(/-/g, '+').replace(/_/g, '/');
switch (output.length % 4) {
case 0: { break; }
case 2: { output += '=='; break; }
case 3: { output += '='; break; }
default: {
throw new Error('Illegal base64url string!');
}
}
return b64DecodeUnicode(output);
}
export /* Example usages of 'b64decode' are shown below:
decodeURIComponent(Array.prototype.map.call(b64decode(str), (c) => {
return '%' + ('00' + c.charCodeAt(0).toString(16)).slice(-2);
}).join(''));
*/
function b64decode(str) {
const chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=';
let output = '';
str = String(str).replace(/=+$/, '');
if (str.length % 4 === 1) {
throw new Error(`'atob' failed: The string to be decoded is not correctly encoded.`);
}
for (
// initialize result and counters
let bc = 0, bs, buffer, idx = 0;
// get next character
buffer = str.charAt(idx++);
// character found in table? initialize bit storage and add its ascii value;
// tslint:disable-next-line:no-bitwise
~buffer && (bs = bc % 4 ? bs * 64 + buffer : buffer,
// and if not first of each 4 characters,
// convert the first 8 bits to one ascii character
// tslint:disable-next-line:no-bitwise
bc++ % 4) ? output += String.fromCharCode(255 & bs >> (-2 * bc & 6)) : 0
) {
// try to find character in table (0-63, not found => -1)
buffer = chars.indexOf(buffer);
}
return output;
}
// https://developer.mozilla.org/en/docs/Web/API/WindowBase64/Base64_encoding_and_decoding#The_Unicode_Problem
export /* Example usages of 'b64DecodeUnicode' are shown below:
b64DecodeUnicode(output);
*/
function b64DecodeUnicode(str) {
return decodeURIComponent(Array.prototype.map.call(b64decode(str), (c) => {
return '%' + ('00' + c.charCodeAt(0).toString(16)).slice(-2);
}).join(''));
}
//#endregion
//#region Object related
export function getDeepFromObject(object = {}, name, defaultValue?) {
const keys = name.split('.');
// clone the object
let level = deepExtend({}, object || {});
keys.forEach((k) => {
if (level && typeof level[k] !== 'undefined') {
level = level[k];
} else {
level = undefined;
}
});
return typeof level === 'undefined' ? defaultValue : level;
}
/* Example usages of 'deepExtend' are shown below:
deepExtend({}, object || {});
target[key] = deepExtend({}, val);
target[key] = deepExtend(src, val);
clone[index] = deepExtend({}, item);
*/
const deepExtend = function (...objects) {
if (arguments.length < 1 || typeof arguments[0] !== 'object') {
return false;
}
if (arguments.length < 2) {
return arguments[0];
}
const target = arguments[0];
// convert arguments to array and cut off target object
const args = Array.prototype.slice.call(arguments, 1);
let val, src;
args.forEach(function (obj) {
// skip argument if it is array or isn't object
if (typeof obj !== 'object' || Array.isArray(obj)) {
return;
}
Object.keys(obj).forEach(function (key) {
src = target[key]; // source value
val = obj[key]; // new value
// recursion prevention
if (val === target) {
return;
/**
* if new value isn't object then just overwrite by new value
* instead of extending.
*/
} else if (typeof val !== 'object' || val === null) {
target[key] = val;
return;
// just clone arrays (and recursive clone objects inside)
} else if (Array.isArray(val)) {
target[key] = deepCloneArray(val);
return;
// custom cloning and overwrite for specific objects
} else if (isSpecificValue(val)) {
target[key] = cloneSpecificValue(val);
return;
// overwrite by new value if source isn't object or array
} else if (typeof src !== 'object' || src === null || Array.isArray(src)) {
target[key] = deepExtend({}, val);
return;
// source value and new value is objects both, extending...
} else {
target[key] = deepExtend(src, val);
return;
}
});
});
return target;
};
/**
* Recursive cloning array.
*/
/* Example usages of 'deepCloneArray' are shown below:
target[key] = deepCloneArray(val);
clone[index] = deepCloneArray(item);
*/
function deepCloneArray(arr) {
const clone = [];
arr.forEach(function (item, index) {
if (typeof item === 'object' && item !== null) {
if (Array.isArray(item)) {
clone[index] = deepCloneArray(item);
} else if (isSpecificValue(item)) {
clone[index] = cloneSpecificValue(item);
} else {
clone[index] = deepExtend({}, item);
}
} else {
clone[index] = item;
}
});
return clone;
}
/* Example usages of 'isSpecificValue' are shown below:
isSpecificValue(val);
isSpecificValue(item);
*/
function isSpecificValue(val) {
return (
val instanceof Date
|| val instanceof RegExp
) ? true : false;
}
/* Example usages of 'cloneSpecificValue' are shown below:
target[key] = cloneSpecificValue(val);
clone[index] = cloneSpecificValue(item);
*/
function cloneSpecificValue(val) {
if (val instanceof Date) {
return new Date(val.getTime());
} else if (val instanceof RegExp) {
return new RegExp(val);
} else {
throw new Error('cloneSpecificValue: Unexpected situation');
}
}
//#endregion
|
f55a000c7e9ccce07c96857921f4e093a4e1c71c | 7,641 | ts | TypeScript | src/app/script/bb/color/color.ts | satopian/klecks | aa1026c59ab925a275c330b3bbe552063c8c810f | [
"MIT"
] | 11 | 2022-01-29T22:46:39.000Z | 2022-03-28T15:42:22.000Z | src/app/script/bb/color/color.ts | satopian/klecks | aa1026c59ab925a275c330b3bbe552063c8c810f | [
"MIT"
] | 14 | 2022-02-13T21:52:23.000Z | 2022-03-31T16:07:47.000Z | src/app/script/bb/color/color.ts | satopian/klecks | aa1026c59ab925a275c330b3bbe552063c8c810f | [
"MIT"
] | 7 | 2022-02-04T23:51:42.000Z | 2022-03-21T12:31:44.000Z |
// based on js color conversion http://www.webtoolkit.info/
export class HSV {
h: number;
s: number;
v: number;
constructor(h: number, s: number, v: number) {
this.h = Math.max(0, Math.min(360, h));
this.s = Math.max(0.001, Math.min(100, s)); //bug when 0
this.v = Math.max(0, Math.min(100, v));
}
}
export class RGB {
r : number;
g: number;
b: number;
constructor(r: number, g: number, b: number) {
this.r = Math.max(0, Math.min(255, r));
this.g = Math.max(0, Math.min(255, g));
this.b = Math.max(0, Math.min(255, b));
}
}
export class CMYK {
c: number;
m: number;
y: number;
k: number;
constructor(c: number, m: number, y: number, k: number) {
this.c = Math.max(0, Math.min(100, c));
this.m = Math.max(0, Math.min(100, m));
this.y = Math.max(0, Math.min(100, y));
this.k = Math.max(0, Math.min(100, k));
}
}
export const ColorConverter = {
_RGBtoHSV: function (RGB: RGB): HSV {
const result = new HSV(0, 0, 0);
const r = RGB.r / 255;
const g = RGB.g / 255;
const b = RGB.b / 255;
const minVal = Math.min(r, g, b);
const maxVal = Math.max(r, g, b);
const delta = maxVal - minVal;
result.v = maxVal;
if (delta == 0) {
result.h = 0;
result.s = 0;
} else {
result.s = delta / maxVal;
const del_R = (((maxVal - r) / 6) + (delta / 2)) / delta;
const del_G = (((maxVal - g) / 6) + (delta / 2)) / delta;
const del_B = (((maxVal - b) / 6) + (delta / 2)) / delta;
if (r == maxVal) {
result.h = del_B - del_G;
} else if (g == maxVal) {
result.h = (1 / 3) + del_R - del_B;
} else if (b == maxVal) {
result.h = (2 / 3) + del_G - del_R;
}
if (result.h < 0) {
result.h += 1;
}
if (result.h > 1) {
result.h -= 1;
}
}
result.h = Math.round(result.h * 360);
result.s = Math.round(result.s * 100);
result.v = Math.round(result.v * 100);
return result;
},
_HSVtoRGB: function (HSV: HSV): RGB {
const result = new RGB(0, 0, 0);
let var_h, var_i, var_1, var_2, var_3, var_r, var_g, var_b;
const h = (HSV.h / 360) % 1;
const s = HSV.s / 100;
const v = HSV.v / 100;
if (s == 0) {
result.r = v * 255;
result.g = v * 255;
result.b = v * 255;
} else {
var_h = h * 6;
var_i = Math.floor(var_h);
var_1 = v * (1 - s);
var_2 = v * (1 - s * (var_h - var_i));
var_3 = v * (1 - s * (1 - (var_h - var_i)));
if (var_i == 0) {
var_r = v;
var_g = var_3;
var_b = var_1
} else if (var_i == 1) {
var_r = var_2;
var_g = v;
var_b = var_1
} else if (var_i == 2) {
var_r = var_1;
var_g = v;
var_b = var_3
} else if (var_i == 3) {
var_r = var_1;
var_g = var_2;
var_b = v
} else if (var_i == 4) {
var_r = var_3;
var_g = var_1;
var_b = v
} else {
var_r = v;
var_g = var_1;
var_b = var_2
}
result.r = var_r * 255;
result.g = var_g * 255;
result.b = var_b * 255;
result.r = Math.round(result.r);
result.g = Math.round(result.g);
result.b = Math.round(result.b);
}
return result;
},
_CMYKtoRGB: function (CMYK: CMYK): RGB {
const result = new RGB(0, 0, 0);
const c = CMYK.c / 100;
const m = CMYK.m / 100;
const y = CMYK.y / 100;
const k = CMYK.k / 100;
result.r = 1 - Math.min(1, c * (1 - k) + k);
result.g = 1 - Math.min(1, m * (1 - k) + k);
result.b = 1 - Math.min(1, y * (1 - k) + k);
result.r = Math.round(result.r * 255);
result.g = Math.round(result.g * 255);
result.b = Math.round(result.b * 255);
return result;
},
_RGBtoCMYK: function (RGB: RGB): CMYK {
const result = new CMYK(0, 0, 0, 0);
const r = RGB.r / 255;
const g = RGB.g / 255;
const b = RGB.b / 255;
result.k = Math.min(1 - r, 1 - g, 1 - b);
result.c = (1 - r - result.k) / (1 - result.k);
result.m = (1 - g - result.k) / (1 - result.k);
result.y = (1 - b - result.k) / (1 - result.k);
result.c = Math.round(result.c * 100);
result.m = Math.round(result.m * 100);
result.y = Math.round(result.y * 100);
result.k = Math.round(result.k * 100);
return result;
},
toRGB: function (o: RGB | HSV | CMYK): RGB {
if (o instanceof RGB) {
return o;
}
if (o instanceof HSV) {
return this._HSVtoRGB(o);
}
if (o instanceof CMYK) {
return this._CMYKtoRGB(o);
}
},
toHSV: function (o: RGB | HSV | CMYK): HSV {
if (o instanceof HSV) {
return o;
}
if (o instanceof RGB) {
return this._RGBtoHSV(o);
}
if (o instanceof CMYK) {
return this._RGBtoHSV(this._CMYKtoRGB(o));
}
},
toCMYK: function (o: RGB | HSV | CMYK): CMYK {
if (o instanceof CMYK) {
return o;
}
if (o instanceof RGB) {
return this._RGBtoCMYK(o);
}
if (o instanceof HSV) {
return this._RGBtoCMYK(this._HSVtoRGB(o));
}
},
toHexString: function (o: RGB): string {
if (o instanceof RGB) {
let ha = (parseInt('' + o.r)).toString(16);
let hb = (parseInt('' + o.g)).toString(16);
let hc = (parseInt('' + o.b)).toString(16);
if (ha.length == 1)
ha = '0' + ha;
if (hb.length == 1)
hb = '0' + hb;
if (hc.length == 1)
hc = '0' + hc;
return ha + hb + hc;
}
},
toRgbStr: function(rgbObj: {r: number, g: number, b: number}): string {
return 'rgb(' + Math.round(rgbObj.r) + ', ' + Math.round(rgbObj.g) + ', ' + Math.round(rgbObj.b) + ')';
},
toRgbaStr: function(rgbaObj: {r: number, g: number, b: number, a: number}): string {
return 'rgba(' + Math.round(rgbaObj.r) + ', ' + Math.round(rgbaObj.g) + ', ' + Math.round(rgbaObj.b) + ', ' + rgbaObj.a + ')';
},
hexToRGB: function(hexStr: string): RGB | null {
hexStr = hexStr.trim();
// Expand shorthand form (e.g. "03F") to full form (e.g. "0033FF")
const shorthandRegex = /^#?([a-f\d])([a-f\d])([a-f\d])$/i;
hexStr = hexStr.replace(shorthandRegex, function(m, r, g, b) {
return r + r + g + g + b + b;
});
const result = /^#?([a-f\d]{2})([a-f\d]{2})([a-f\d]{2})$/i.exec(hexStr);
return result ? new RGB(
parseInt(result[1], 16),
parseInt(result[2], 16),
parseInt(result[3], 16)
) : null;
}
};
export function testIsWhiteBestContrast(rgbObj: {r: number, g: number, b: number}): boolean {
return (rgbObj.r * 0.299 + rgbObj.g * 0.587 + rgbObj.b * 0.114) < 125;
} | 29.275862 | 134 | 0.444444 | 218 | 16 | 0 | 26 | 37 | 10 | 0 | 0 | 35 | 3 | 10 | 10.6875 | 2,664 | 0.015766 | 0.013889 | 0.003754 | 0.001126 | 0.003754 | 0 | 0.393258 | 0.253065 |
// based on js color conversion http://www.webtoolkit.info/
export class HSV {
h;
s;
v;
constructor(h, s, v) {
this.h = Math.max(0, Math.min(360, h));
this.s = Math.max(0.001, Math.min(100, s)); //bug when 0
this.v = Math.max(0, Math.min(100, v));
}
}
export class RGB {
r ;
g;
b;
constructor(r, g, b) {
this.r = Math.max(0, Math.min(255, r));
this.g = Math.max(0, Math.min(255, g));
this.b = Math.max(0, Math.min(255, b));
}
}
export class CMYK {
c;
m;
y;
k;
constructor(c, m, y, k) {
this.c = Math.max(0, Math.min(100, c));
this.m = Math.max(0, Math.min(100, m));
this.y = Math.max(0, Math.min(100, y));
this.k = Math.max(0, Math.min(100, k));
}
}
export const ColorConverter = {
_RGBtoHSV: function (RGB) {
const result = new HSV(0, 0, 0);
const r = RGB.r / 255;
const g = RGB.g / 255;
const b = RGB.b / 255;
const minVal = Math.min(r, g, b);
const maxVal = Math.max(r, g, b);
const delta = maxVal - minVal;
result.v = maxVal;
if (delta == 0) {
result.h = 0;
result.s = 0;
} else {
result.s = delta / maxVal;
const del_R = (((maxVal - r) / 6) + (delta / 2)) / delta;
const del_G = (((maxVal - g) / 6) + (delta / 2)) / delta;
const del_B = (((maxVal - b) / 6) + (delta / 2)) / delta;
if (r == maxVal) {
result.h = del_B - del_G;
} else if (g == maxVal) {
result.h = (1 / 3) + del_R - del_B;
} else if (b == maxVal) {
result.h = (2 / 3) + del_G - del_R;
}
if (result.h < 0) {
result.h += 1;
}
if (result.h > 1) {
result.h -= 1;
}
}
result.h = Math.round(result.h * 360);
result.s = Math.round(result.s * 100);
result.v = Math.round(result.v * 100);
return result;
},
_HSVtoRGB: function (HSV) {
const result = new RGB(0, 0, 0);
let var_h, var_i, var_1, var_2, var_3, var_r, var_g, var_b;
const h = (HSV.h / 360) % 1;
const s = HSV.s / 100;
const v = HSV.v / 100;
if (s == 0) {
result.r = v * 255;
result.g = v * 255;
result.b = v * 255;
} else {
var_h = h * 6;
var_i = Math.floor(var_h);
var_1 = v * (1 - s);
var_2 = v * (1 - s * (var_h - var_i));
var_3 = v * (1 - s * (1 - (var_h - var_i)));
if (var_i == 0) {
var_r = v;
var_g = var_3;
var_b = var_1
} else if (var_i == 1) {
var_r = var_2;
var_g = v;
var_b = var_1
} else if (var_i == 2) {
var_r = var_1;
var_g = v;
var_b = var_3
} else if (var_i == 3) {
var_r = var_1;
var_g = var_2;
var_b = v
} else if (var_i == 4) {
var_r = var_3;
var_g = var_1;
var_b = v
} else {
var_r = v;
var_g = var_1;
var_b = var_2
}
result.r = var_r * 255;
result.g = var_g * 255;
result.b = var_b * 255;
result.r = Math.round(result.r);
result.g = Math.round(result.g);
result.b = Math.round(result.b);
}
return result;
},
_CMYKtoRGB: function (CMYK) {
const result = new RGB(0, 0, 0);
const c = CMYK.c / 100;
const m = CMYK.m / 100;
const y = CMYK.y / 100;
const k = CMYK.k / 100;
result.r = 1 - Math.min(1, c * (1 - k) + k);
result.g = 1 - Math.min(1, m * (1 - k) + k);
result.b = 1 - Math.min(1, y * (1 - k) + k);
result.r = Math.round(result.r * 255);
result.g = Math.round(result.g * 255);
result.b = Math.round(result.b * 255);
return result;
},
_RGBtoCMYK: function (RGB) {
const result = new CMYK(0, 0, 0, 0);
const r = RGB.r / 255;
const g = RGB.g / 255;
const b = RGB.b / 255;
result.k = Math.min(1 - r, 1 - g, 1 - b);
result.c = (1 - r - result.k) / (1 - result.k);
result.m = (1 - g - result.k) / (1 - result.k);
result.y = (1 - b - result.k) / (1 - result.k);
result.c = Math.round(result.c * 100);
result.m = Math.round(result.m * 100);
result.y = Math.round(result.y * 100);
result.k = Math.round(result.k * 100);
return result;
},
toRGB: function (o) {
if (o instanceof RGB) {
return o;
}
if (o instanceof HSV) {
return this._HSVtoRGB(o);
}
if (o instanceof CMYK) {
return this._CMYKtoRGB(o);
}
},
toHSV: function (o) {
if (o instanceof HSV) {
return o;
}
if (o instanceof RGB) {
return this._RGBtoHSV(o);
}
if (o instanceof CMYK) {
return this._RGBtoHSV(this._CMYKtoRGB(o));
}
},
toCMYK: function (o) {
if (o instanceof CMYK) {
return o;
}
if (o instanceof RGB) {
return this._RGBtoCMYK(o);
}
if (o instanceof HSV) {
return this._RGBtoCMYK(this._HSVtoRGB(o));
}
},
toHexString: function (o) {
if (o instanceof RGB) {
let ha = (parseInt('' + o.r)).toString(16);
let hb = (parseInt('' + o.g)).toString(16);
let hc = (parseInt('' + o.b)).toString(16);
if (ha.length == 1)
ha = '0' + ha;
if (hb.length == 1)
hb = '0' + hb;
if (hc.length == 1)
hc = '0' + hc;
return ha + hb + hc;
}
},
toRgbStr: function(rgbObj) {
return 'rgb(' + Math.round(rgbObj.r) + ', ' + Math.round(rgbObj.g) + ', ' + Math.round(rgbObj.b) + ')';
},
toRgbaStr: function(rgbaObj) {
return 'rgba(' + Math.round(rgbaObj.r) + ', ' + Math.round(rgbaObj.g) + ', ' + Math.round(rgbaObj.b) + ', ' + rgbaObj.a + ')';
},
hexToRGB: function(hexStr) {
hexStr = hexStr.trim();
// Expand shorthand form (e.g. "03F") to full form (e.g. "0033FF")
const shorthandRegex = /^#?([a-f\d])([a-f\d])([a-f\d])$/i;
hexStr = hexStr.replace(shorthandRegex, function(m, r, g, b) {
return r + r + g + g + b + b;
});
const result = /^#?([a-f\d]{2})([a-f\d]{2})([a-f\d]{2})$/i.exec(hexStr);
return result ? new RGB(
parseInt(result[1], 16),
parseInt(result[2], 16),
parseInt(result[3], 16)
) : null;
}
};
export function testIsWhiteBestContrast(rgbObj) {
return (rgbObj.r * 0.299 + rgbObj.g * 0.587 + rgbObj.b * 0.114) < 125;
} |
f591c6b5762110500a3e955840b23afba95536d3 | 2,687 | ts | TypeScript | DetaiListHoursOnly/src/time.extension.ts | soulsoftware/PowerPlatform-PCF | a719edf153fb248c239be71218a34ddbbb7c33df | [
"MIT"
] | null | null | null | DetaiListHoursOnly/src/time.extension.ts | soulsoftware/PowerPlatform-PCF | a719edf153fb248c239be71218a34ddbbb7c33df | [
"MIT"
] | 1 | 2022-01-15T14:03:56.000Z | 2022-01-15T14:03:56.000Z | OfficeUIHourOnlyField/src/time.extension.ts | soulsoftware/PowerPlatform-PCF | a719edf153fb248c239be71218a34ddbbb7c33df | [
"MIT"
] | null | null | null | type TimeObject = {
hh:number,
mm:number,
am?:boolean
}
declare interface Date {
getTimeObject( options?: Intl.DateTimeFormatOptions ):TimeObject
setTimeObject( t:TimeObject ):void
addMinutes( minutes:number ):Date
// toLocaleTimeObjectString(locales?: string | string[]):string
toTimeZoneIndependentString( options?: Intl.DateTimeFormatOptions ):string
toTimeZoneDependentString( options?: Intl.DateTimeFormatOptions ):string
}
Date.prototype.addMinutes = function( minutes:number) {
const mm = this.getMinutes() + minutes
const result = new Date( this.getTime() )
result.setMinutes( mm )
return result
}
Date.prototype.getTimeObject = function( options?: Intl.DateTimeFormatOptions ):TimeObject {
if( options?.hour12 ) {
const result:TimeObject = {
hh:this.getHours() - 12,
mm:this.getMinutes(),
am:false
}
if( result.hh === 0 ) {
result.hh = 12
}
else if( result.hh === -12 ) {
result.hh = 12
result.am = true
}
else if( result.hh < 0 ) {
result.hh = 12 + result.hh
result.am = true
}
return result
}
return { hh:this.getHours(), mm:this.getMinutes() }
}
Date.prototype.setTimeObject = function(t:TimeObject) {
this.setHours(t.hh)
this.setMinutes(t.mm)
}
Date.prototype.toTimeZoneIndependentString = function( options?: Intl.DateTimeFormatOptions ) {
const twodigit = ( v:number) => (v < 10) ? `0${v}` : `${v}`
const tmpDate = this.addMinutes( this.getTimezoneOffset() )
const t = tmpDate.getTimeObject( options )
if( options?.hour12 ) {
return `${twodigit(t.hh)}:${twodigit(t.mm)} ${(t.am) ? 'AM': 'PM'}`
}
return `${twodigit(t.hh)}:${twodigit(t.mm)}`
}
Date.prototype.toTimeZoneDependentString = function( options?: Intl.DateTimeFormatOptions ) {
const twodigit = ( v:number) => (v < 10) ? `0${v}` : `${v}`
const t = this.getTimeObject( options )
if( options?.hour12 ) {
return `${twodigit(t.hh)}:${twodigit(t.mm)} ${(t.am) ? 'AM': 'PM'}`
}
return `${twodigit(t.hh)}:${twodigit(t.mm)}`
}
// Date.prototype.toLocaleTimeObjectString = function(locales?: string | string[]) {
// let options: Intl.DateTimeFormatOptions = {
// //weekday: "short",
// //year: "numeric",
// //month: "short",
// //day: "numeric",
// hour: "2-digit",
// minute: "2-digit"
// };
// return this.toLocaleTimeString(locales, options);
// } | 25.349057 | 95 | 0.572758 | 61 | 7 | 5 | 12 | 8 | 3 | 3 | 0 | 10 | 2 | 0 | 5.857143 | 781 | 0.024328 | 0.010243 | 0.003841 | 0.002561 | 0 | 0 | 0.285714 | 0.264959 | type TimeObject = {
hh,
mm,
am?
}
declare interface Date {
getTimeObject( options? )
setTimeObject( t )
addMinutes( minutes )
// toLocaleTimeObjectString(locales?: string | string[]):string
toTimeZoneIndependentString( options? )
toTimeZoneDependentString( options? )
}
Date.prototype.addMinutes = function( minutes) {
const mm = this.getMinutes() + minutes
const result = new Date( this.getTime() )
result.setMinutes( mm )
return result
}
Date.prototype.getTimeObject = function( options? ) {
if( options?.hour12 ) {
const result = {
hh:this.getHours() - 12,
mm:this.getMinutes(),
am:false
}
if( result.hh === 0 ) {
result.hh = 12
}
else if( result.hh === -12 ) {
result.hh = 12
result.am = true
}
else if( result.hh < 0 ) {
result.hh = 12 + result.hh
result.am = true
}
return result
}
return { hh:this.getHours(), mm:this.getMinutes() }
}
Date.prototype.setTimeObject = function(t) {
this.setHours(t.hh)
this.setMinutes(t.mm)
}
Date.prototype.toTimeZoneIndependentString = function( options? ) {
/* Example usages of 'twodigit' are shown below:
twodigit(t.hh);
twodigit(t.mm);
*/
/* Example usages of 'twodigit' are shown below:
twodigit(t.hh);
twodigit(t.mm);
*/
const twodigit = ( v) => (v < 10) ? `0${v}` : `${v}`
const tmpDate = this.addMinutes( this.getTimezoneOffset() )
const t = tmpDate.getTimeObject( options )
if( options?.hour12 ) {
return `${twodigit(t.hh)}:${twodigit(t.mm)} ${(t.am) ? 'AM': 'PM'}`
}
return `${twodigit(t.hh)}:${twodigit(t.mm)}`
}
Date.prototype.toTimeZoneDependentString = function( options? ) {
/* Example usages of 'twodigit' are shown below:
twodigit(t.hh);
twodigit(t.mm);
*/
/* Example usages of 'twodigit' are shown below:
twodigit(t.hh);
twodigit(t.mm);
*/
const twodigit = ( v) => (v < 10) ? `0${v}` : `${v}`
const t = this.getTimeObject( options )
if( options?.hour12 ) {
return `${twodigit(t.hh)}:${twodigit(t.mm)} ${(t.am) ? 'AM': 'PM'}`
}
return `${twodigit(t.hh)}:${twodigit(t.mm)}`
}
// Date.prototype.toLocaleTimeObjectString = function(locales?: string | string[]) {
// let options: Intl.DateTimeFormatOptions = {
// //weekday: "short",
// //year: "numeric",
// //month: "short",
// //day: "numeric",
// hour: "2-digit",
// minute: "2-digit"
// };
// return this.toLocaleTimeString(locales, options);
// } |
f5af1e91356527eb5d685f57986a63f3cc187b56 | 1,350 | ts | TypeScript | archguard/src/pages/systemEvolving/BadSmellThreshold/components/BadSmellThresholdTable.config.ts | tianweiliutw/archguard-frontend | 3a230853b452a1b4d77daf49311b4f6da923e02a | [
"MIT"
] | 2 | 2022-02-22T02:30:20.000Z | 2022-02-24T11:52:46.000Z | archguard/src/pages/systemEvolving/BadSmellThreshold/components/BadSmellThresholdTable.config.ts | tianweiliutw/archguard-frontend | 3a230853b452a1b4d77daf49311b4f6da923e02a | [
"MIT"
] | 1 | 2022-02-22T04:34:35.000Z | 2022-02-22T04:34:35.000Z | archguard/src/pages/systemEvolving/BadSmellThreshold/components/BadSmellThresholdTable.config.ts | tianweiliutw/archguard-frontend | 3a230853b452a1b4d77daf49311b4f6da923e02a | [
"MIT"
] | 1 | 2022-02-22T02:22:06.000Z | 2022-02-22T02:22:06.000Z | export interface BadSmellTableData {
key?: string;
dimension: string;
badSmell: string;
condition: string;
threshold: number;
rowspan?: number;
}
export const BadSmellThresholdTableColumns = [
{
title: "评估维度",
dataIndex: "dimension",
key: "dimension",
render: (text: string, row: BadSmellTableData) => {
if (row.rowspan !== undefined) {
return {
children: text,
props: {
rowSpan: row.rowspan,
},
};
}
return text;
},
},
{
title: "坏味道",
dataIndex: "badSmell",
key: "badSmell",
},
{
title: "判断条件",
dataIndex: "condition",
key: "condition",
},
{
title: "指标阈值",
dataIndex: "threshold",
key: "threshold",
},
];
export const BadSmellThresholdTableData = [
{
name: "体量维度",
threshold: [
{
name: "过大的方法",
condition: "方法代码行数 > 指标阈值",
value: 30,
},
{
name: "过大的方法",
condition: "方法个数 > 指标阈值",
value: 20,
},
],
},
{
name: "耦合维度",
threshold: [
{
key: "dataMud",
name: "数据泥团",
condition: "缺乏内聚指标LCOM4 > 指标阈值",
value: 6,
},
{
key: "deepInheritance",
name: "过深继承",
condition: "继承深度 > 指标阈值",
value: 6,
},
],
},
];
| 17.307692 | 55 | 0.480741 | 75 | 1 | 0 | 2 | 2 | 6 | 0 | 0 | 7 | 1 | 0 | 9 | 430 | 0.006977 | 0.004651 | 0.013953 | 0.002326 | 0 | 0 | 0.636364 | 0.204483 | export interface BadSmellTableData {
key?;
dimension;
badSmell;
condition;
threshold;
rowspan?;
}
export const BadSmellThresholdTableColumns = [
{
title: "评估维度",
dataIndex: "dimension",
key: "dimension",
render: (text, row) => {
if (row.rowspan !== undefined) {
return {
children: text,
props: {
rowSpan: row.rowspan,
},
};
}
return text;
},
},
{
title: "坏味道",
dataIndex: "badSmell",
key: "badSmell",
},
{
title: "判断条件",
dataIndex: "condition",
key: "condition",
},
{
title: "指标阈值",
dataIndex: "threshold",
key: "threshold",
},
];
export const BadSmellThresholdTableData = [
{
name: "体量维度",
threshold: [
{
name: "过大的方法",
condition: "方法代码行数 > 指标阈值",
value: 30,
},
{
name: "过大的方法",
condition: "方法个数 > 指标阈值",
value: 20,
},
],
},
{
name: "耦合维度",
threshold: [
{
key: "dataMud",
name: "数据泥团",
condition: "缺乏内聚指标LCOM4 > 指标阈值",
value: 6,
},
{
key: "deepInheritance",
name: "过深继承",
condition: "继承深度 > 指标阈值",
value: 6,
},
],
},
];
|
67153e5b35f0b672d7742a020b28194aa27c93e2 | 1,771 | ts | TypeScript | utils/JsonTree.ts | L4ne/dc-demostore-core | d0bb159dda3d82caee934ecbf37f58926502695b | [
"Apache-2.0"
] | 1 | 2022-03-30T07:23:36.000Z | 2022-03-30T07:23:36.000Z | utils/JsonTree.ts | L4ne/dc-demostore-core | d0bb159dda3d82caee934ecbf37f58926502695b | [
"Apache-2.0"
] | null | null | null | utils/JsonTree.ts | L4ne/dc-demostore-core | d0bb159dda3d82caee934ecbf37f58926502695b | [
"Apache-2.0"
] | 4 | 2022-03-24T14:07:32.000Z | 2022-03-31T13:32:51.000Z | /**
* @hidden
*/
export type JsonVisitor = (value: any) => any;
/**
* @hidden
*/
export class JsonTree {
public static visit(
data: any,
visitor: JsonVisitor,
depth: number = 0,
): void {
if (depth > 1000) {
throw new Error(
'Tree depth exceeded maximum of 1000, verify the data is not self-referential',
);
}
if (data == null) {
return;
} else if (Array.isArray(data)) {
for (let i = 0; i < data.length; i++) {
const item = data[i];
JsonTree.visit(item, visitor, depth + 1);
const newValue = visitor(item);
if (newValue !== undefined) {
data[i] = newValue;
}
}
} else if (typeof data === 'object') {
const keys = Object.keys(data);
for (const key of keys) {
JsonTree.visit(data[key], visitor, depth + 1);
const newValue = visitor(data[key]);
if (newValue !== undefined) {
data[key] = newValue;
}
}
}
}
public static async asyncVisit(
data: any,
visitor: (value: any) => Promise<any>,
depth: number = 0,
): Promise<void> {
if (depth > 1000) {
throw new Error(
'Tree depth exceeded maximum of 1000, verify the data is not self-referential',
);
}
if (data == null) {
return;
} else if (Array.isArray(data)) {
for (let i = 0; i < data.length; i++) {
const item = data[i];
await JsonTree.asyncVisit(item, visitor, depth + 1);
await visitor(item);
}
} else if (typeof data === 'object') {
const keys = Object.keys(data);
for (const key of keys) {
await JsonTree.asyncVisit(data[key], visitor, depth + 1);
await visitor(data[key]);
}
}
}
}
| 24.260274 | 87 | 0.532468 | 61 | 2 | 0 | 6 | 8 | 0 | 2 | 6 | 4 | 2 | 2 | 23 | 507 | 0.015779 | 0.015779 | 0 | 0.003945 | 0.003945 | 0.375 | 0.25 | 0.258584 | /**
* @hidden
*/
export type JsonVisitor = (value) => any;
/**
* @hidden
*/
export class JsonTree {
public static visit(
data,
visitor,
depth = 0,
) {
if (depth > 1000) {
throw new Error(
'Tree depth exceeded maximum of 1000, verify the data is not self-referential',
);
}
if (data == null) {
return;
} else if (Array.isArray(data)) {
for (let i = 0; i < data.length; i++) {
const item = data[i];
JsonTree.visit(item, visitor, depth + 1);
const newValue = visitor(item);
if (newValue !== undefined) {
data[i] = newValue;
}
}
} else if (typeof data === 'object') {
const keys = Object.keys(data);
for (const key of keys) {
JsonTree.visit(data[key], visitor, depth + 1);
const newValue = visitor(data[key]);
if (newValue !== undefined) {
data[key] = newValue;
}
}
}
}
public static async asyncVisit(
data,
visitor,
depth = 0,
) {
if (depth > 1000) {
throw new Error(
'Tree depth exceeded maximum of 1000, verify the data is not self-referential',
);
}
if (data == null) {
return;
} else if (Array.isArray(data)) {
for (let i = 0; i < data.length; i++) {
const item = data[i];
await JsonTree.asyncVisit(item, visitor, depth + 1);
await visitor(item);
}
} else if (typeof data === 'object') {
const keys = Object.keys(data);
for (const key of keys) {
await JsonTree.asyncVisit(data[key], visitor, depth + 1);
await visitor(data[key]);
}
}
}
}
|
676437dd76b783f6b7dd23617fba4d4305e30076 | 2,722 | ts | TypeScript | src/libs/colors.ts | niiree/t80sz | 4fafb063b8a47b018d502d0cdc77eca46e29f2de | [
"ISC"
] | null | null | null | src/libs/colors.ts | niiree/t80sz | 4fafb063b8a47b018d502d0cdc77eca46e29f2de | [
"ISC"
] | 6 | 2022-03-07T18:15:11.000Z | 2022-03-12T22:53:16.000Z | src/libs/colors.ts | niiree/t80sz | 4fafb063b8a47b018d502d0cdc77eca46e29f2de | [
"ISC"
] | null | null | null | const gradients = [
"linear-gradient(90deg, rgba(255,229,0,1) 0%, rgba(249,190,17,1) 100%)",
"linear-gradient(90deg, rgba(242,139,39,1) 0%, rgba(249,190,17,1) 100%)",
"linear-gradient(90deg, rgba(196,41,169,1) 0%, rgba(141,53,206,1) 100%)",
"linear-gradient(90deg, rgba(68,69,255,1) 0%, rgba(51,121,193,1) 100%)",
"linear-gradient(90deg, rgba(11,241,49,1) 0%, rgba(32,179,123,1) 100%)",
"linear-gradient(90deg, #FFE500, #F28B27, #C429A9, #4445FF, #0BF131)"
]
export class colors {
lightColors = [ "#FFEA33", "#F39132", "#D054BA", "#696AFF", "#3CF45A" ]
stdColors = [ "#FFE500", "#F28B27", "#C429A9", "#4445FF", "#0BF131" ]
patterns = [
{ sequence: 1, scheme: [2] },
{ sequence: 2, scheme: [0, 4] },
{ sequence: 3, scheme: [0, 2, 4] },
{ sequence: 4, scheme: [0, 1, 2, 4] },
{ sequence: 3, scheme: [0, 1, 2, 3, 4] },
]
async setGradient(grad: string) {
return new Promise((resolve) => {
switch (grad) {
case "yellow":
resolve(gradients[0])
break
case "orange":
resolve(gradients[1])
break
case "purple":
resolve(gradients[2])
break
case "blue":
resolve(gradients[3])
break
case "green":
resolve(gradients[4])
break
case "rainbow":
resolve(gradients[5])
break
}
})
}
async setLight(clr: string) {
return new Promise((resolve) => {
switch(clr) {
case "yellow":
resolve(this.lightColors[0])
break;
case "orange":
resolve(this.lightColors[1])
break;
case "purple":
resolve(this.lightColors[2])
break;
case "blue":
resolve(this.lightColors[3])
break;
case "green":
resolve(this.lightColors[4])
break;
}
});
}
async splitHex(clr: string) {
return new Promise((resolve) => {
switch(clr) {
case "yellow":
resolve([this.stdColors[0], this.stdColors[1]])
break;
case "orange":
resolve([this.stdColors[1], this.stdColors[0]])
break;
case "purple":
resolve([this.stdColors[2], this.stdColors[3]])
break;
case "blue":
resolve(["#3379C1", this.stdColors[3]])
break;
case "green":
resolve([this.stdColors[3], this.stdColors[4]])
break;
case "rainbow":
resolve([
this.stdColors[0],
this.stdColors[1],
this.stdColors[2],
this.stdColors[3],
this.stdColors[4]
])
break;
}
})
}
}
| 28.652632 | 75 | 0.505511 | 94 | 6 | 0 | 6 | 1 | 3 | 0 | 0 | 3 | 1 | 0 | 22 | 934 | 0.012848 | 0.001071 | 0.003212 | 0.001071 | 0 | 0 | 0.1875 | 0.205137 | const gradients = [
"linear-gradient(90deg, rgba(255,229,0,1) 0%, rgba(249,190,17,1) 100%)",
"linear-gradient(90deg, rgba(242,139,39,1) 0%, rgba(249,190,17,1) 100%)",
"linear-gradient(90deg, rgba(196,41,169,1) 0%, rgba(141,53,206,1) 100%)",
"linear-gradient(90deg, rgba(68,69,255,1) 0%, rgba(51,121,193,1) 100%)",
"linear-gradient(90deg, rgba(11,241,49,1) 0%, rgba(32,179,123,1) 100%)",
"linear-gradient(90deg, #FFE500, #F28B27, #C429A9, #4445FF, #0BF131)"
]
export class colors {
lightColors = [ "#FFEA33", "#F39132", "#D054BA", "#696AFF", "#3CF45A" ]
stdColors = [ "#FFE500", "#F28B27", "#C429A9", "#4445FF", "#0BF131" ]
patterns = [
{ sequence: 1, scheme: [2] },
{ sequence: 2, scheme: [0, 4] },
{ sequence: 3, scheme: [0, 2, 4] },
{ sequence: 4, scheme: [0, 1, 2, 4] },
{ sequence: 3, scheme: [0, 1, 2, 3, 4] },
]
async setGradient(grad) {
return new Promise((resolve) => {
switch (grad) {
case "yellow":
resolve(gradients[0])
break
case "orange":
resolve(gradients[1])
break
case "purple":
resolve(gradients[2])
break
case "blue":
resolve(gradients[3])
break
case "green":
resolve(gradients[4])
break
case "rainbow":
resolve(gradients[5])
break
}
})
}
async setLight(clr) {
return new Promise((resolve) => {
switch(clr) {
case "yellow":
resolve(this.lightColors[0])
break;
case "orange":
resolve(this.lightColors[1])
break;
case "purple":
resolve(this.lightColors[2])
break;
case "blue":
resolve(this.lightColors[3])
break;
case "green":
resolve(this.lightColors[4])
break;
}
});
}
async splitHex(clr) {
return new Promise((resolve) => {
switch(clr) {
case "yellow":
resolve([this.stdColors[0], this.stdColors[1]])
break;
case "orange":
resolve([this.stdColors[1], this.stdColors[0]])
break;
case "purple":
resolve([this.stdColors[2], this.stdColors[3]])
break;
case "blue":
resolve(["#3379C1", this.stdColors[3]])
break;
case "green":
resolve([this.stdColors[3], this.stdColors[4]])
break;
case "rainbow":
resolve([
this.stdColors[0],
this.stdColors[1],
this.stdColors[2],
this.stdColors[3],
this.stdColors[4]
])
break;
}
})
}
}
|
6781a323d7aeeb9d66f44123c6a9d6a22abb3ae8 | 4,243 | ts | TypeScript | src/heightmap/models/PerlinNoiseModel.ts | Ziagl/HeightmapGenerator | 1e9804628ba4460e9ba8b34383e68212a6076076 | [
"MIT"
] | null | null | null | src/heightmap/models/PerlinNoiseModel.ts | Ziagl/HeightmapGenerator | 1e9804628ba4460e9ba8b34383e68212a6076076 | [
"MIT"
] | null | null | null | src/heightmap/models/PerlinNoiseModel.ts | Ziagl/HeightmapGenerator | 1e9804628ba4460e9ba8b34383e68212a6076076 | [
"MIT"
] | 1 | 2022-03-19T17:48:38.000Z | 2022-03-19T17:48:38.000Z | export class PerlinNoiseModel {
private _persistence: number
private _frequency: number
private _amplitude: number
private _octaves: number
private _seed: number
constructor(
persistence: number,
frequency: number,
amplitude: number,
octaves: number,
seed: number
) {
this._persistence = persistence
this._frequency = frequency
this._amplitude = amplitude
this._octaves = octaves
this._seed = 2 + seed * seed
}
public getHeight(x: number, y: number): number {
return this._amplitude * this.total(x, y)
}
private total(x: number, y: number): number {
let t = 0.0
let ampl = 1
let freq = this._frequency
for (let k = 0; k < this._octaves; ++k) {
t += this.getValue(x * freq + this._seed, y * freq + this._seed) * ampl
ampl *= this._persistence
freq *= 2
}
return t
}
private getValue(x: number, y: number): number {
let xInt = Math.floor(x)
let yInt = Math.floor(y)
let xFrac = x - xInt
let yFrac = y - yInt
let n01 = this.noise(xInt - 1, yInt - 1)
let n02 = this.noise(xInt + 1, yInt - 1)
let n03 = this.noise(xInt - 1, yInt + 1)
let n04 = this.noise(xInt + 1, yInt + 1)
let n05 = this.noise(xInt - 1, yInt)
let n06 = this.noise(xInt + 1, yInt)
let n07 = this.noise(xInt, yInt - 1)
let n08 = this.noise(xInt, yInt + 1)
let n09 = this.noise(xInt, yInt)
let n12 = this.noise(xInt + 2, yInt - 1)
let n14 = this.noise(xInt + 2, yInt + 1)
let n16 = this.noise(xInt + 2, yInt)
let n23 = this.noise(xInt - 1, yInt + 2)
let n24 = this.noise(xInt + 1, yInt + 2)
let n28 = this.noise(xInt, yInt + 2)
let n34 = this.noise(xInt + 2, yInt + 2)
let x0y0 = 0.0625 * (n01 + n02 + n03 + n04) + 0.125 * (n05 + n06 + n07 + n08) + 0.25 * n09
let x1y0 = 0.0625 * (n07 + n12 + n08 + n14) + 0.125 * (n09 + n16 + n02 + n04) + 0.25 * n06
let x0y1 = 0.0625 * (n05 + n06 + n23 + n24) + 0.125 * (n03 + n04 + n09 + n28) + 0.25 * n08
let x1y1 = 0.0625 * (n09 + n16 + n28 + n34) + 0.125 * (n08 + n14 + n06 + n24) + 0.25 * n04
let v1 = this.interpolate(x0y0, x1y0, xFrac)
let v2 = this.interpolate(x0y1, x1y1, xFrac)
return this.interpolate(v1, v2, yFrac)
}
private interpolate(x: number, y: number, a: number): number {
let negA = 1.0 - a
let negASqr = negA * negA
let fac1 = 3.0 * negASqr - 2.0 * (negASqr * negA)
let aSqr = a * a
let fac2 = 3.0 * aSqr - 2.0 * (aSqr * a)
return x * fac1 + y * fac2
}
private noise(x: number, y: number): number {
let n = x + y * 57
n = (n << 13) ^ n
let t = (n * (n * n * 15731 + 789221) + 1376312589) & 0x7fffffff
return 1.0 - t * 0.931322574615478515625e-9
}
/*
public perlin(x: number, y: number): number {
let x0 = x
let x1 = x0 + 1
let y0 = y
let y1 = y0 + 1
let sx = x - x0
let sy = y - y0
let n0 = this.dotGridGradient(x0, y0, x, y)
let n1 = this.dotGridGradient(x1, y0, x, y)
let ix0 = this.interpolate(n0, n1, sx)
n0 = this.dotGridGradient(x0, y1, x, y)
n1 = this.dotGridGradient(x1, y1, x, y)
let ix1 = this.interpolate(n0, n1, sx)
let value = this.interpolate(ix0, ix1, sy)
return value
}
private randomGradient(ix: number, iy: number): [number, number] {
let random =
2920.0 *
Math.sin(ix * 21942.0 + iy * 171324.0 + 8912.0) *
Math.cos(ix * 23157.0 + iy * 217832.0 + 9758.0)
return [Math.cos(random), Math.sin(random)]
}
private dotGridGradient(ix: number, iy: number, x: number, y: number): number {
let gradient = this.randomGradient(ix, iy)
let dx = x - ix
let dy = y - iy
return dx * gradient[0] + dy * gradient[1]
}
private interpolate(a0: number, a1: number, w: number): number {
return (a1 - a0) * w + a0
}
*/
}
| 30.970803 | 98 | 0.524157 | 77 | 6 | 0 | 16 | 37 | 5 | 4 | 0 | 26 | 1 | 0 | 8.666667 | 1,618 | 0.013597 | 0.022868 | 0.00309 | 0.000618 | 0 | 0 | 0.40625 | 0.278075 | export class PerlinNoiseModel {
private _persistence
private _frequency
private _amplitude
private _octaves
private _seed
constructor(
persistence,
frequency,
amplitude,
octaves,
seed
) {
this._persistence = persistence
this._frequency = frequency
this._amplitude = amplitude
this._octaves = octaves
this._seed = 2 + seed * seed
}
public getHeight(x, y) {
return this._amplitude * this.total(x, y)
}
private total(x, y) {
let t = 0.0
let ampl = 1
let freq = this._frequency
for (let k = 0; k < this._octaves; ++k) {
t += this.getValue(x * freq + this._seed, y * freq + this._seed) * ampl
ampl *= this._persistence
freq *= 2
}
return t
}
private getValue(x, y) {
let xInt = Math.floor(x)
let yInt = Math.floor(y)
let xFrac = x - xInt
let yFrac = y - yInt
let n01 = this.noise(xInt - 1, yInt - 1)
let n02 = this.noise(xInt + 1, yInt - 1)
let n03 = this.noise(xInt - 1, yInt + 1)
let n04 = this.noise(xInt + 1, yInt + 1)
let n05 = this.noise(xInt - 1, yInt)
let n06 = this.noise(xInt + 1, yInt)
let n07 = this.noise(xInt, yInt - 1)
let n08 = this.noise(xInt, yInt + 1)
let n09 = this.noise(xInt, yInt)
let n12 = this.noise(xInt + 2, yInt - 1)
let n14 = this.noise(xInt + 2, yInt + 1)
let n16 = this.noise(xInt + 2, yInt)
let n23 = this.noise(xInt - 1, yInt + 2)
let n24 = this.noise(xInt + 1, yInt + 2)
let n28 = this.noise(xInt, yInt + 2)
let n34 = this.noise(xInt + 2, yInt + 2)
let x0y0 = 0.0625 * (n01 + n02 + n03 + n04) + 0.125 * (n05 + n06 + n07 + n08) + 0.25 * n09
let x1y0 = 0.0625 * (n07 + n12 + n08 + n14) + 0.125 * (n09 + n16 + n02 + n04) + 0.25 * n06
let x0y1 = 0.0625 * (n05 + n06 + n23 + n24) + 0.125 * (n03 + n04 + n09 + n28) + 0.25 * n08
let x1y1 = 0.0625 * (n09 + n16 + n28 + n34) + 0.125 * (n08 + n14 + n06 + n24) + 0.25 * n04
let v1 = this.interpolate(x0y0, x1y0, xFrac)
let v2 = this.interpolate(x0y1, x1y1, xFrac)
return this.interpolate(v1, v2, yFrac)
}
private interpolate(x, y, a) {
let negA = 1.0 - a
let negASqr = negA * negA
let fac1 = 3.0 * negASqr - 2.0 * (negASqr * negA)
let aSqr = a * a
let fac2 = 3.0 * aSqr - 2.0 * (aSqr * a)
return x * fac1 + y * fac2
}
private noise(x, y) {
let n = x + y * 57
n = (n << 13) ^ n
let t = (n * (n * n * 15731 + 789221) + 1376312589) & 0x7fffffff
return 1.0 - t * 0.931322574615478515625e-9
}
/*
public perlin(x: number, y: number): number {
let x0 = x
let x1 = x0 + 1
let y0 = y
let y1 = y0 + 1
let sx = x - x0
let sy = y - y0
let n0 = this.dotGridGradient(x0, y0, x, y)
let n1 = this.dotGridGradient(x1, y0, x, y)
let ix0 = this.interpolate(n0, n1, sx)
n0 = this.dotGridGradient(x0, y1, x, y)
n1 = this.dotGridGradient(x1, y1, x, y)
let ix1 = this.interpolate(n0, n1, sx)
let value = this.interpolate(ix0, ix1, sy)
return value
}
private randomGradient(ix: number, iy: number): [number, number] {
let random =
2920.0 *
Math.sin(ix * 21942.0 + iy * 171324.0 + 8912.0) *
Math.cos(ix * 23157.0 + iy * 217832.0 + 9758.0)
return [Math.cos(random), Math.sin(random)]
}
private dotGridGradient(ix: number, iy: number, x: number, y: number): number {
let gradient = this.randomGradient(ix, iy)
let dx = x - ix
let dy = y - iy
return dx * gradient[0] + dy * gradient[1]
}
private interpolate(a0: number, a1: number, w: number): number {
return (a1 - a0) * w + a0
}
*/
}
|
67a8007ac3342faf5c0b42ff8d661ca68fc6e926 | 2,270 | ts | TypeScript | problemset/wiggle-sort-2/index.ts | OUDUIDUI/leet-code | 50e61ce16d1c419ccefc075ae9ead721cdd1cdbb | [
"MIT"
] | 6 | 2022-01-17T03:19:56.000Z | 2022-01-17T05:45:39.000Z | problemset/wiggle-sort-2/index.ts | OUDUIDUI/leet-code | 50e61ce16d1c419ccefc075ae9ead721cdd1cdbb | [
"MIT"
] | null | null | null | problemset/wiggle-sort-2/index.ts | OUDUIDUI/leet-code | 50e61ce16d1c419ccefc075ae9ead721cdd1cdbb | [
"MIT"
] | null | null | null | /**
* 排序
* @desc 时间复杂度 O(NlogN) 空间复杂度 O(N)
* @param nums
*/
export function wiggleSort(nums: number[]): void {
const sorted = nums.sort((a, b) => a - b).slice()
let i = nums.length - 1
let j = i >> 1
let k = 0
while (k < sorted.length) {
nums[k] = (k & 1) ? sorted[i--] : sorted[j--]
k++
}
}
/**
* 快速排序 + 中位数
* @desc 时间复杂度 O(N) 空间复杂度 O(N)
* @param nums
*/
export function wiggleSort2(nums: number[]): void {
const len = nums.length
const mid = getMedian(0, 0, nums) // 中位数
const leftArr: number[] = []
const rightArr: number[] = []
let count = 0 // 记录与中位数相等的数量
for (const num of nums) {
if (num > mid)
rightArr.push(num)
else if (num < mid)
leftArr.push(num)
else
count++
}
// 将mid放入数组中,保证leftArr和rightArr长度相差不超过1
const diff = leftArr.length - rightArr.length
if (diff === 0) {
leftArr.splice(0, 0, ...new Array(Math.ceil(count / 2)).fill(mid))
rightArr.push(...new Array(count >> 1).fill(mid))
}
else if (diff > 0) {
count -= diff
leftArr.splice(0, 0, ...new Array(Math.ceil(count / 2)).fill(mid))
rightArr.push(...new Array((count >> 1) + diff).fill(mid))
}
else {
count += diff
leftArr.splice(0, 0, ...new Array(Math.ceil(count / 2) - diff).fill(mid))
rightArr.push(...new Array(count >> 1).fill(mid))
}
for (let i = 0; i < len; i++) {
if (i % 2)
nums[i] = rightArr.shift()!
else
nums[i] = leftArr.shift()!
}
/**
* 使用快排获取中位数
* @param left
* @param right
* @param nums
* @returns
*/
function getMedian(left: number, right: number, nums: number[]): number {
const len = nums.length
const mid = nums[len >> 1]
const leftArr: number[] = []
const rightArr: number[] = []
// 记录与 mid 相等的数量
let count = 0
for (const num of nums) {
if (num > mid)
rightArr.push(num)
else if (num < mid)
leftArr.push(num)
else
count++
}
if (Math.abs(left + leftArr.length - right - rightArr.length) <= count)
return mid
if (left + leftArr.length > right + rightArr.length)
return getMedian(left, right + rightArr.length + count, leftArr)
else
return getMedian(left + leftArr.length + count, right, rightArr)
}
}
| 23.894737 | 77 | 0.566079 | 67 | 4 | 0 | 7 | 16 | 0 | 1 | 0 | 12 | 0 | 0 | 20.75 | 812 | 0.013547 | 0.019704 | 0 | 0 | 0 | 0 | 0.444444 | 0.265862 | /**
* 排序
* @desc 时间复杂度 O(NlogN) 空间复杂度 O(N)
* @param nums
*/
export function wiggleSort(nums) {
const sorted = nums.sort((a, b) => a - b).slice()
let i = nums.length - 1
let j = i >> 1
let k = 0
while (k < sorted.length) {
nums[k] = (k & 1) ? sorted[i--] : sorted[j--]
k++
}
}
/**
* 快速排序 + 中位数
* @desc 时间复杂度 O(N) 空间复杂度 O(N)
* @param nums
*/
export function wiggleSort2(nums) {
const len = nums.length
const mid = getMedian(0, 0, nums) // 中位数
const leftArr = []
const rightArr = []
let count = 0 // 记录与中位数相等的数量
for (const num of nums) {
if (num > mid)
rightArr.push(num)
else if (num < mid)
leftArr.push(num)
else
count++
}
// 将mid放入数组中,保证leftArr和rightArr长度相差不超过1
const diff = leftArr.length - rightArr.length
if (diff === 0) {
leftArr.splice(0, 0, ...new Array(Math.ceil(count / 2)).fill(mid))
rightArr.push(...new Array(count >> 1).fill(mid))
}
else if (diff > 0) {
count -= diff
leftArr.splice(0, 0, ...new Array(Math.ceil(count / 2)).fill(mid))
rightArr.push(...new Array((count >> 1) + diff).fill(mid))
}
else {
count += diff
leftArr.splice(0, 0, ...new Array(Math.ceil(count / 2) - diff).fill(mid))
rightArr.push(...new Array(count >> 1).fill(mid))
}
for (let i = 0; i < len; i++) {
if (i % 2)
nums[i] = rightArr.shift()!
else
nums[i] = leftArr.shift()!
}
/**
* 使用快排获取中位数
* @param left
* @param right
* @param nums
* @returns
*/
/* Example usages of 'getMedian' are shown below:
getMedian(0, 0, nums) // 中位数
;
getMedian(left, right + rightArr.length + count, leftArr);
getMedian(left + leftArr.length + count, right, rightArr);
*/
function getMedian(left, right, nums) {
const len = nums.length
const mid = nums[len >> 1]
const leftArr = []
const rightArr = []
// 记录与 mid 相等的数量
let count = 0
for (const num of nums) {
if (num > mid)
rightArr.push(num)
else if (num < mid)
leftArr.push(num)
else
count++
}
if (Math.abs(left + leftArr.length - right - rightArr.length) <= count)
return mid
if (left + leftArr.length > right + rightArr.length)
return getMedian(left, right + rightArr.length + count, leftArr)
else
return getMedian(left + leftArr.length + count, right, rightArr)
}
}
|
67c92204927aafe048bd5e567c068990724074a8 | 4,166 | ts | TypeScript | app/src/services/JSUniverse.ts | rob893/algo-visualizer | 143315e1d0158bf32933ec58724a7b7e44c1bcfa | [
"MIT"
] | 3 | 2022-01-29T20:51:18.000Z | 2022-02-14T00:02:13.000Z | app/src/services/JSUniverse.ts | rob893/algo-visualizer | 143315e1d0158bf32933ec58724a7b7e44c1bcfa | [
"MIT"
] | null | null | null | app/src/services/JSUniverse.ts | rob893/algo-visualizer | 143315e1d0158bf32933ec58724a7b7e44c1bcfa | [
"MIT"
] | null | null | null | interface JSNode {
x: number;
y: number;
weight: number;
passable: boolean;
}
interface PathResult {
path: JSNode[];
processed: JSNode[];
}
// For use to compare performance with web assembly only.
// Not used for more than comparing at this time.
export class JSUniverse {
public readonly width: number;
public readonly height: number;
private readonly nodes: JSNode[][] = [];
public constructor(width: number, height: number) {
for (let y = 0; y < height; y++) {
this.nodes.push([]);
for (let x = 0; x < width; x++) {
this.nodes[y].push({
x,
y,
weight: 0,
passable: true
});
}
}
this.width = width;
this.height = height;
}
public bfs(startX: number, startY: number, endX: number, endY: number): PathResult {
const result: PathResult = {
path: [],
processed: []
};
const frontier: JSNode[] = [];
const startNode = this.nodes[startY][startX];
const endNode = this.nodes[endY][endX];
const visited = new Set<JSNode>();
const cameFrom = new Map<JSNode, JSNode>();
visited.add(startNode);
frontier.unshift(startNode);
while (frontier.length > 0) {
const current = frontier.pop();
if (!current) {
throw new Error('Invalid');
}
result.processed.push(current);
if (current === endNode) {
return this.constructPath(result, cameFrom, endNode);
}
for (const neighbor of this.getNeighbors(current.x, current.y)) {
if (!visited.has(neighbor)) {
visited.add(neighbor);
cameFrom.set(neighbor, current);
frontier.unshift(neighbor);
}
}
}
return result;
}
public dijkstra(startX: number, startY: number, endX: number, endY: number): PathResult {
const result: PathResult = {
path: [],
processed: []
};
const frontier = this.nodes.flat();
const startNode = this.nodes[startY][startX];
const endNode = this.nodes[endY][endX];
const times = new Map<JSNode, number>();
const cameFrom = new Map<JSNode, JSNode>();
times.set(startNode, 0);
while (frontier.length > 0) {
const index = this.getClosestNode(frontier, times);
const current = frontier[index];
frontier.splice(index, 1);
result.processed.push(current);
if (current === endNode) {
return this.constructPath(result, cameFrom, endNode);
}
for (const neighbor of this.getNeighbors(current.x, current.y)) {
const prevTime = times.get(current) ?? Number.MAX_SAFE_INTEGER;
const newTime = prevTime + neighbor.weight + 1;
if (newTime < (times.get(neighbor) ?? Number.MAX_SAFE_INTEGER)) {
times.set(neighbor, newTime);
cameFrom.set(neighbor, current);
}
}
}
return result;
}
private getClosestNode(nodes: JSNode[], times: Map<JSNode, number>): number {
let currClosetsIndex = 0;
for (let i = 0; i < nodes.length; i++) {
if (
(times.get(nodes[currClosetsIndex]) ?? Number.MAX_SAFE_INTEGER) >
(times.get(nodes[i]) ?? Number.MAX_SAFE_INTEGER)
) {
currClosetsIndex = i;
}
}
return currClosetsIndex;
}
private getNeighbors(x: number, y: number): JSNode[] {
const res: JSNode[] = [];
if (y > 0 && this.nodes[y - 1][x].passable) {
res.push(this.nodes[y - 1][x]);
}
if (y < this.height - 1 && this.nodes[y + 1][x].passable) {
res.push(this.nodes[y + 1][x]);
}
if (x > 0 && this.nodes[y][x - 1].passable) {
res.push(this.nodes[y][x - 1]);
}
if (x < this.width - 1 && this.nodes[y][x + 1].passable) {
res.push(this.nodes[y][x + 1]);
}
return res;
}
private constructPath(result: PathResult, cameFrom: Map<JSNode, JSNode>, endNode: JSNode): PathResult {
let current = endNode;
result.path.push(current);
let next = cameFrom.get(current);
while (next) {
current = next;
result.path.push(current);
next = cameFrom.get(current);
}
result.path.reverse();
return result;
}
}
| 23.670455 | 105 | 0.584494 | 131 | 6 | 0 | 17 | 24 | 9 | 3 | 0 | 21 | 3 | 0 | 17.333333 | 1,204 | 0.019103 | 0.019934 | 0.007475 | 0.002492 | 0 | 0 | 0.375 | 0.284224 | interface JSNode {
x;
y;
weight;
passable;
}
interface PathResult {
path;
processed;
}
// For use to compare performance with web assembly only.
// Not used for more than comparing at this time.
export class JSUniverse {
public readonly width;
public readonly height;
private readonly nodes = [];
public constructor(width, height) {
for (let y = 0; y < height; y++) {
this.nodes.push([]);
for (let x = 0; x < width; x++) {
this.nodes[y].push({
x,
y,
weight: 0,
passable: true
});
}
}
this.width = width;
this.height = height;
}
public bfs(startX, startY, endX, endY) {
const result = {
path: [],
processed: []
};
const frontier = [];
const startNode = this.nodes[startY][startX];
const endNode = this.nodes[endY][endX];
const visited = new Set<JSNode>();
const cameFrom = new Map<JSNode, JSNode>();
visited.add(startNode);
frontier.unshift(startNode);
while (frontier.length > 0) {
const current = frontier.pop();
if (!current) {
throw new Error('Invalid');
}
result.processed.push(current);
if (current === endNode) {
return this.constructPath(result, cameFrom, endNode);
}
for (const neighbor of this.getNeighbors(current.x, current.y)) {
if (!visited.has(neighbor)) {
visited.add(neighbor);
cameFrom.set(neighbor, current);
frontier.unshift(neighbor);
}
}
}
return result;
}
public dijkstra(startX, startY, endX, endY) {
const result = {
path: [],
processed: []
};
const frontier = this.nodes.flat();
const startNode = this.nodes[startY][startX];
const endNode = this.nodes[endY][endX];
const times = new Map<JSNode, number>();
const cameFrom = new Map<JSNode, JSNode>();
times.set(startNode, 0);
while (frontier.length > 0) {
const index = this.getClosestNode(frontier, times);
const current = frontier[index];
frontier.splice(index, 1);
result.processed.push(current);
if (current === endNode) {
return this.constructPath(result, cameFrom, endNode);
}
for (const neighbor of this.getNeighbors(current.x, current.y)) {
const prevTime = times.get(current) ?? Number.MAX_SAFE_INTEGER;
const newTime = prevTime + neighbor.weight + 1;
if (newTime < (times.get(neighbor) ?? Number.MAX_SAFE_INTEGER)) {
times.set(neighbor, newTime);
cameFrom.set(neighbor, current);
}
}
}
return result;
}
private getClosestNode(nodes, times) {
let currClosetsIndex = 0;
for (let i = 0; i < nodes.length; i++) {
if (
(times.get(nodes[currClosetsIndex]) ?? Number.MAX_SAFE_INTEGER) >
(times.get(nodes[i]) ?? Number.MAX_SAFE_INTEGER)
) {
currClosetsIndex = i;
}
}
return currClosetsIndex;
}
private getNeighbors(x, y) {
const res = [];
if (y > 0 && this.nodes[y - 1][x].passable) {
res.push(this.nodes[y - 1][x]);
}
if (y < this.height - 1 && this.nodes[y + 1][x].passable) {
res.push(this.nodes[y + 1][x]);
}
if (x > 0 && this.nodes[y][x - 1].passable) {
res.push(this.nodes[y][x - 1]);
}
if (x < this.width - 1 && this.nodes[y][x + 1].passable) {
res.push(this.nodes[y][x + 1]);
}
return res;
}
private constructPath(result, cameFrom, endNode) {
let current = endNode;
result.path.push(current);
let next = cameFrom.get(current);
while (next) {
current = next;
result.path.push(current);
next = cameFrom.get(current);
}
result.path.reverse();
return result;
}
}
|
67d4203cb30f364e5b8a02b0a3a0764497ad1b9d | 1,877 | ts | TypeScript | plugins/prebuffer-mixin/src/sps-parser/bitstream.ts | bjia56/scrypted | f505b6c53813cdd52d31581141b41a1bb18a79ce | [
"MIT"
] | null | null | null | plugins/prebuffer-mixin/src/sps-parser/bitstream.ts | bjia56/scrypted | f505b6c53813cdd52d31581141b41a1bb18a79ce | [
"MIT"
] | null | null | null | plugins/prebuffer-mixin/src/sps-parser/bitstream.ts | bjia56/scrypted | f505b6c53813cdd52d31581141b41a1bb18a79ce | [
"MIT"
] | 1 | 2022-01-29T12:57:34.000Z | 2022-01-29T12:57:34.000Z | function ExpGolomInit(view: DataView, bitoffset: number): { zeros: number; skip: number; byt: number; byteoffset: number } {
let bit = 0;
let byteoffset = bitoffset >> 3;
let skip = bitoffset & 7;
let zeros = -1;
let byt = view.getUint8(byteoffset) << skip;
do {
bit = byt & 0x80;
byt <<= 1;
zeros++;
skip++;
if (skip === 8) {
skip = 0;
byteoffset++;
byt = view.getUint8(byteoffset);
}
} while (!bit);
return { zeros, skip, byt, byteoffset };
}
export class Bitstream {
public bitoffset = 0;
constructor (public view: DataView) {}
ExpGolomb(): number {
const { view } = this;
let {
zeros, skip, byt, byteoffset,
} = ExpGolomInit(view, this.bitoffset);
let code = 1;
while (zeros > 0) {
code = (code << 1) | ((byt & 0x80) >>> 7);
byt <<= 1;
skip++;
zeros--;
if (skip === 8) {
skip = 0;
byteoffset++;
byt = view.getUint8(byteoffset);
}
}
this.bitoffset = (byteoffset << 3) | skip;
return code - 1;
}
SignedExpGolomb(): number {
const code = this.ExpGolomb();
return code & 1 ? (code + 1) >>> 1 : -(code >>> 1);
}
readBit(): 0 | 1 {
const skip = this.bitoffset & 7;
const byteoffset = this.bitoffset >> 3;
this.bitoffset++;
return ((this.view.getUint8(byteoffset) >> (7 - skip)) & 1) as 0|1;
}
readByte(): number {
const skip = this.bitoffset & 7;
const byteoffset = this.bitoffset >> 3;
this.bitoffset += 8;
const high = this.view.getUint8(byteoffset);
if (skip === 0) return high;
const low = this.view.getUint8(byteoffset + 1);
return (high << skip) | (low >> (8 - skip));
}
}
| 25.026667 | 124 | 0.501332 | 62 | 6 | 0 | 3 | 15 | 1 | 2 | 0 | 8 | 1 | 1 | 8 | 568 | 0.015845 | 0.026408 | 0.001761 | 0.001761 | 0.001761 | 0 | 0.32 | 0.296083 | /* Example usages of 'ExpGolomInit' are shown below:
ExpGolomInit(view, this.bitoffset);
*/
function ExpGolomInit(view, bitoffset) {
let bit = 0;
let byteoffset = bitoffset >> 3;
let skip = bitoffset & 7;
let zeros = -1;
let byt = view.getUint8(byteoffset) << skip;
do {
bit = byt & 0x80;
byt <<= 1;
zeros++;
skip++;
if (skip === 8) {
skip = 0;
byteoffset++;
byt = view.getUint8(byteoffset);
}
} while (!bit);
return { zeros, skip, byt, byteoffset };
}
export class Bitstream {
public bitoffset = 0;
constructor (public view) {}
ExpGolomb() {
const { view } = this;
let {
zeros, skip, byt, byteoffset,
} = ExpGolomInit(view, this.bitoffset);
let code = 1;
while (zeros > 0) {
code = (code << 1) | ((byt & 0x80) >>> 7);
byt <<= 1;
skip++;
zeros--;
if (skip === 8) {
skip = 0;
byteoffset++;
byt = view.getUint8(byteoffset);
}
}
this.bitoffset = (byteoffset << 3) | skip;
return code - 1;
}
SignedExpGolomb() {
const code = this.ExpGolomb();
return code & 1 ? (code + 1) >>> 1 : -(code >>> 1);
}
readBit() {
const skip = this.bitoffset & 7;
const byteoffset = this.bitoffset >> 3;
this.bitoffset++;
return ((this.view.getUint8(byteoffset) >> (7 - skip)) & 1) as 0|1;
}
readByte() {
const skip = this.bitoffset & 7;
const byteoffset = this.bitoffset >> 3;
this.bitoffset += 8;
const high = this.view.getUint8(byteoffset);
if (skip === 0) return high;
const low = this.view.getUint8(byteoffset + 1);
return (high << skip) | (low >> (8 - skip));
}
}
|
f741c8e17bb0750ae4b3d2d33f0efe89c64fd173 | 2,546 | ts | TypeScript | src/algorithms/skoblitz.ts | norkator/hash-numbers | 5dfebcfc14bbeae1d3437a32516bd804156508d0 | [
"MIT"
] | 1 | 2022-03-18T11:42:12.000Z | 2022-03-18T11:42:12.000Z | src/algorithms/skoblitz.ts | norkator/hash-numbers | 5dfebcfc14bbeae1d3437a32516bd804156508d0 | [
"MIT"
] | 2 | 2022-03-10T09:10:02.000Z | 2022-03-14T20:49:13.000Z | src/algorithms/skoblitz.ts | norkator/hash-numbers | 5dfebcfc14bbeae1d3437a32516bd804156508d0 | [
"MIT"
] | 1 | 2022-03-09T14:37:42.000Z | 2022-03-09T14:37:42.000Z | /**
* Encoding method
* @param value which is always number
* @param salt (seed) which can be anything
* @constructor
*/
export function SKoblitzEncode(value: number, salt: string): string {
const pos = value % salt.length;
const saltedValue = salt.slice(0, pos) + value + salt.slice(pos);
// console.log(saltedValue)
return KoblitzEncode(saltedValue).toLocaleString('fullwide', {useGrouping: false});
}
/**
* Decoding method
* @param value which is encoding result number
* @param salt (seed) which can be anything
* @constructor
*/
export function SKoblitzDecode(value: number, salt: string): number {
const saltedValue = KoblitzDecode(value);
let id = 0;
let a = 0, b = 0;
while (a < salt.length) {
if (salt[a] == saltedValue[b]) {
a++;
b++;
} else {
id = id * 10 + Number(saltedValue[b]);
b++;
}
}
return id;
}
/**
* Returns koblitz encoding for a string
* @param salt must be a string to encode
* @constructor
*/
function KoblitzEncode(salt: string): number {
const chars = salt.split("").reverse();
let sum = 0;
chars.forEach((c, i) => {
const n = RetCharNumVal(c);
sum = sum + (n * Math.pow(63, i));
});
return sum;
}
/**
* Returns numerical value for character (a-z,A-Z,0-9) => (1-26,27-52,53-62)
* @param char must be a character
* @constructor
*/
function RetCharNumVal(char: any): number {
if ((/[a-z]/).test(char)) {
return char.charCodeAt(0) - 96;
}
if ((/[A-Z]/).test(char)) {
return char.charCodeAt(0) - 38;
}
if ((/[0-9]/).test(char)) {
return char.charCodeAt(0) + 5;
}
return 0;
}
/**
* Returns koblitz decoding for a string
* @param hash must be a string to encode
* @constructor
*/
function KoblitzDecode(hash: number): string {
let plainSalt = '';
while (hash > 0) {
const numVal = hash % 63;
plainSalt += RetNumCharVal(numVal);
hash = Math.floor(hash / 63);
}
return plainSalt.split('').reverse().join('');
}
/**
* Returns character value for number (1-26,27-52,53-62) => (a-z,A-Z,0-9)
* @param num must be a number
* @constructor
*/
function RetNumCharVal(num: number): any {
if (num >= 1 && num <= 26) {
return String.fromCharCode(num + 96);
}
if (num >= 27 && num <= 52) {
return String.fromCharCode(num + 38);
}
if (num >= 53 && num <= 62) {
return String.fromCharCode(num - 5);
}
return 0;
}
| 24.018868 | 87 | 0.576591 | 62 | 7 | 0 | 10 | 11 | 0 | 4 | 2 | 12 | 0 | 0 | 7.428571 | 821 | 0.020706 | 0.013398 | 0 | 0 | 0 | 0.071429 | 0.428571 | 0.261603 | /**
* Encoding method
* @param value which is always number
* @param salt (seed) which can be anything
* @constructor
*/
export function SKoblitzEncode(value, salt) {
const pos = value % salt.length;
const saltedValue = salt.slice(0, pos) + value + salt.slice(pos);
// console.log(saltedValue)
return KoblitzEncode(saltedValue).toLocaleString('fullwide', {useGrouping: false});
}
/**
* Decoding method
* @param value which is encoding result number
* @param salt (seed) which can be anything
* @constructor
*/
export function SKoblitzDecode(value, salt) {
const saltedValue = KoblitzDecode(value);
let id = 0;
let a = 0, b = 0;
while (a < salt.length) {
if (salt[a] == saltedValue[b]) {
a++;
b++;
} else {
id = id * 10 + Number(saltedValue[b]);
b++;
}
}
return id;
}
/**
* Returns koblitz encoding for a string
* @param salt must be a string to encode
* @constructor
*/
/* Example usages of 'KoblitzEncode' are shown below:
KoblitzEncode(saltedValue).toLocaleString('fullwide', { useGrouping: false });
*/
function KoblitzEncode(salt) {
const chars = salt.split("").reverse();
let sum = 0;
chars.forEach((c, i) => {
const n = RetCharNumVal(c);
sum = sum + (n * Math.pow(63, i));
});
return sum;
}
/**
* Returns numerical value for character (a-z,A-Z,0-9) => (1-26,27-52,53-62)
* @param char must be a character
* @constructor
*/
/* Example usages of 'RetCharNumVal' are shown below:
RetCharNumVal(c);
*/
function RetCharNumVal(char) {
if ((/[a-z]/).test(char)) {
return char.charCodeAt(0) - 96;
}
if ((/[A-Z]/).test(char)) {
return char.charCodeAt(0) - 38;
}
if ((/[0-9]/).test(char)) {
return char.charCodeAt(0) + 5;
}
return 0;
}
/**
* Returns koblitz decoding for a string
* @param hash must be a string to encode
* @constructor
*/
/* Example usages of 'KoblitzDecode' are shown below:
KoblitzDecode(value);
*/
function KoblitzDecode(hash) {
let plainSalt = '';
while (hash > 0) {
const numVal = hash % 63;
plainSalt += RetNumCharVal(numVal);
hash = Math.floor(hash / 63);
}
return plainSalt.split('').reverse().join('');
}
/**
* Returns character value for number (1-26,27-52,53-62) => (a-z,A-Z,0-9)
* @param num must be a number
* @constructor
*/
/* Example usages of 'RetNumCharVal' are shown below:
plainSalt += RetNumCharVal(numVal);
*/
function RetNumCharVal(num) {
if (num >= 1 && num <= 26) {
return String.fromCharCode(num + 96);
}
if (num >= 27 && num <= 52) {
return String.fromCharCode(num + 38);
}
if (num >= 53 && num <= 62) {
return String.fromCharCode(num - 5);
}
return 0;
}
|
f75da4d20bad79621fb7f1bdd86c9ec5299efd00 | 1,714 | ts | TypeScript | src/events/createAsyncIterator.ts | openland/patterns | fd9ce385917df4b447d3952f6b9180d815288d18 | [
"MIT"
] | null | null | null | src/events/createAsyncIterator.ts | openland/patterns | fd9ce385917df4b447d3952f6b9180d815288d18 | [
"MIT"
] | null | null | null | src/events/createAsyncIterator.ts | openland/patterns | fd9ce385917df4b447d3952f6b9180d815288d18 | [
"MIT"
] | 1 | 2022-01-09T23:31:04.000Z | 2022-01-09T23:31:04.000Z | export function createAsyncIterator<T>(onExit: () => void): AsyncIterable<T> & { push(data: T): void, complete(): void } {
let events: (T | null)[] = [];
let resolvers: any[] = [];
const getValue = () => {
return new Promise<IteratorResult<T>>((resolve => {
if (events.length > 0) {
let val = events.shift();
if (val === null) {
resolve({ value: undefined, done: true } as any);
} else {
resolve({ value: val!, done: false });
}
} else {
resolvers.push(resolve);
}
}));
};
let onReturn = () => {
events = [];
resolvers = [];
onExit();
return Promise.resolve({ value: undefined, done: true } as any);
};
return {
[Symbol.asyncIterator]() {
return {
next(): Promise<IteratorResult<T>> {
return getValue();
},
return: onReturn,
throw(error: any) {
return Promise.reject(error);
}
};
},
push(data: T) {
if (resolvers.length > 0) {
resolvers.shift()({
value: data,
done: false
});
} else {
events.push(data);
}
},
complete() {
if (resolvers.length > 0) {
resolvers.shift()({
value: null,
done: true
});
} else {
events.push(null);
}
}
};
} | 28.098361 | 122 | 0.375146 | 57 | 9 | 2 | 5 | 5 | 0 | 2 | 4 | 3 | 0 | 2 | 12 | 351 | 0.039886 | 0.014245 | 0 | 0 | 0.005698 | 0.190476 | 0.142857 | 0.306393 | export function createAsyncIterator<T>(onExit) {
let events = [];
let resolvers = [];
/* Example usages of 'getValue' are shown below:
getValue();
*/
const getValue = () => {
return new Promise<IteratorResult<T>>((resolve => {
if (events.length > 0) {
let val = events.shift();
if (val === null) {
resolve({ value: undefined, done: true } as any);
} else {
resolve({ value: val!, done: false });
}
} else {
resolvers.push(resolve);
}
}));
};
/* Example usages of 'onReturn' are shown below:
;
*/
let onReturn = () => {
events = [];
resolvers = [];
onExit();
return Promise.resolve({ value: undefined, done: true } as any);
};
return {
[Symbol.asyncIterator]() {
return {
next() {
return getValue();
},
return: onReturn,
throw(error) {
return Promise.reject(error);
}
};
},
push(data) {
if (resolvers.length > 0) {
resolvers.shift()({
value: data,
done: false
});
} else {
events.push(data);
}
},
complete() {
if (resolvers.length > 0) {
resolvers.shift()({
value: null,
done: true
});
} else {
events.push(null);
}
}
};
} |
f7d94fb0f8122c96ae50b2159262f8b6d025cc5b | 2,735 | ts | TypeScript | problemset/pacific-atlantic-water-flow/index.ts | OUDUIDUI/leet-code | 50e61ce16d1c419ccefc075ae9ead721cdd1cdbb | [
"MIT"
] | 6 | 2022-01-17T03:19:56.000Z | 2022-01-17T05:45:39.000Z | problemset/pacific-atlantic-water-flow/index.ts | OUDUIDUI/leet-code | 50e61ce16d1c419ccefc075ae9ead721cdd1cdbb | [
"MIT"
] | null | null | null | problemset/pacific-atlantic-water-flow/index.ts | OUDUIDUI/leet-code | 50e61ce16d1c419ccefc075ae9ead721cdd1cdbb | [
"MIT"
] | null | null | null | /**
* 深度优先搜索
* @desc 时间复杂度 O(MN) 空间复杂度 O(MN)
* @param heights
* @returns
*/
export function pacificAtlantic(heights: number[][]): number[][] {
const dirs = [[-1, 0], [1, 0], [0, -1], [0, 1]]
const m = heights.length
const n = heights[0].length
const pacific = new Array(m).fill([]).map(() => new Array(n).fill(false))
const atlantic = new Array(m).fill([]).map(() => new Array(n).fill(false))
for (let i = 0; i < m; i++)
dfs(i, 0, pacific)
for (let i = 1; i < n; i++)
dfs(0, i, pacific)
for (let i = 0; i < m; i++)
dfs(i, n - 1, atlantic)
for (let i = 0; i < n - 1; i++)
dfs(m - 1, i, atlantic)
const result: number[][] = []
for (let i = 0; i < m; i++) {
for (let j = 0; j < n; j++) {
if (pacific[i][j] && atlantic[i][j])
result.push([i, j])
}
}
return result
function dfs(row: number, col: number, ocean: boolean[][]) {
if (ocean[row][col]) return
ocean[row][col] = true
for (const dir of dirs) {
const newRow = row + dir[0]
const newCol = col + dir[1]
if (
newRow >= 0
&& newCol >= 0
&& newRow < m
&& newCol < n
&& heights[newRow][newCol] >= heights[row][col]
)
dfs(newRow, newCol, ocean)
}
}
}
/**
* 广度优先搜索
* @desc 时间复杂度 O(MN) 空间复杂度 O(MN)
* @param heights
* @returns
*/
export function pacificAtlantic2(heights: number[][]): number[][] {
const dirs = [[-1, 0], [1, 0], [0, -1], [0, 1]]
const m = heights.length
const n = heights[0].length
const pacific = new Array(m).fill([]).map(() => new Array(n).fill(false))
const atlantic = new Array(m).fill([]).map(() => new Array(n).fill(false))
for (let i = 0; i < m; i++)
bfs(i, 0, pacific)
for (let i = 1; i < n; i++)
bfs(0, i, pacific)
for (let i = 0; i < m; i++)
bfs(i, n - 1, atlantic)
for (let i = 0; i < n - 1; i++)
bfs(m - 1, i, atlantic)
const result: number[][] = []
for (let i = 0; i < m; i++) {
for (let j = 0; j < n; j++) {
if (pacific[i][j] && atlantic[i][j])
result.push([i, j])
}
}
return result
function bfs(row: number, col: number, ocean: boolean[][]) {
if (ocean[row][col]) return
ocean[row][col] = true
const queue = [[row, col]]
while (queue.length) {
const [r, c] = queue.pop()!
for (const dir of dirs) {
const newRow = r + dir[0]
const newCol = c + dir[1]
if (
newRow >= 0
&& newCol >= 0
&& newRow < m
&& newCol < n
&& heights[newRow][newCol] >= heights[r][c]
&& !ocean[newRow][newCol]
) {
ocean[newRow][newCol] = true
queue.unshift([newRow, newCol])
}
}
}
}
}
| 23.177966 | 76 | 0.49287 | 85 | 8 | 0 | 8 | 30 | 0 | 2 | 0 | 12 | 0 | 0 | 15 | 1,021 | 0.015671 | 0.029383 | 0 | 0 | 0 | 0 | 0.26087 | 0.302929 | /**
* 深度优先搜索
* @desc 时间复杂度 O(MN) 空间复杂度 O(MN)
* @param heights
* @returns
*/
export function pacificAtlantic(heights) {
const dirs = [[-1, 0], [1, 0], [0, -1], [0, 1]]
const m = heights.length
const n = heights[0].length
const pacific = new Array(m).fill([]).map(() => new Array(n).fill(false))
const atlantic = new Array(m).fill([]).map(() => new Array(n).fill(false))
for (let i = 0; i < m; i++)
dfs(i, 0, pacific)
for (let i = 1; i < n; i++)
dfs(0, i, pacific)
for (let i = 0; i < m; i++)
dfs(i, n - 1, atlantic)
for (let i = 0; i < n - 1; i++)
dfs(m - 1, i, atlantic)
const result = []
for (let i = 0; i < m; i++) {
for (let j = 0; j < n; j++) {
if (pacific[i][j] && atlantic[i][j])
result.push([i, j])
}
}
return result
/* Example usages of 'dfs' are shown below:
dfs(i, 0, pacific);
dfs(0, i, pacific);
dfs(i, n - 1, atlantic);
dfs(m - 1, i, atlantic);
dfs(newRow, newCol, ocean);
*/
function dfs(row, col, ocean) {
if (ocean[row][col]) return
ocean[row][col] = true
for (const dir of dirs) {
const newRow = row + dir[0]
const newCol = col + dir[1]
if (
newRow >= 0
&& newCol >= 0
&& newRow < m
&& newCol < n
&& heights[newRow][newCol] >= heights[row][col]
)
dfs(newRow, newCol, ocean)
}
}
}
/**
* 广度优先搜索
* @desc 时间复杂度 O(MN) 空间复杂度 O(MN)
* @param heights
* @returns
*/
export function pacificAtlantic2(heights) {
const dirs = [[-1, 0], [1, 0], [0, -1], [0, 1]]
const m = heights.length
const n = heights[0].length
const pacific = new Array(m).fill([]).map(() => new Array(n).fill(false))
const atlantic = new Array(m).fill([]).map(() => new Array(n).fill(false))
for (let i = 0; i < m; i++)
bfs(i, 0, pacific)
for (let i = 1; i < n; i++)
bfs(0, i, pacific)
for (let i = 0; i < m; i++)
bfs(i, n - 1, atlantic)
for (let i = 0; i < n - 1; i++)
bfs(m - 1, i, atlantic)
const result = []
for (let i = 0; i < m; i++) {
for (let j = 0; j < n; j++) {
if (pacific[i][j] && atlantic[i][j])
result.push([i, j])
}
}
return result
/* Example usages of 'bfs' are shown below:
bfs(i, 0, pacific);
bfs(0, i, pacific);
bfs(i, n - 1, atlantic);
bfs(m - 1, i, atlantic);
*/
function bfs(row, col, ocean) {
if (ocean[row][col]) return
ocean[row][col] = true
const queue = [[row, col]]
while (queue.length) {
const [r, c] = queue.pop()!
for (const dir of dirs) {
const newRow = r + dir[0]
const newCol = c + dir[1]
if (
newRow >= 0
&& newCol >= 0
&& newRow < m
&& newCol < n
&& heights[newRow][newCol] >= heights[r][c]
&& !ocean[newRow][newCol]
) {
ocean[newRow][newCol] = true
queue.unshift([newRow, newCol])
}
}
}
}
}
|
f7e47331af0dd029c6d3b06ee900ca217b5ac014 | 3,153 | ts | TypeScript | components/_utils/gradient.ts | wscodinglover/ss-ui-library | c3009125b70797fd37e90e418570c53207c4e124 | [
"MIT"
] | 1 | 2022-03-23T02:22:54.000Z | 2022-03-23T02:22:54.000Z | components/_utils/gradient.ts | wscodinglover/ss-ui-library | c3009125b70797fd37e90e418570c53207c4e124 | [
"MIT"
] | null | null | null | components/_utils/gradient.ts | wscodinglover/ss-ui-library | c3009125b70797fd37e90e418570c53207c4e124 | [
"MIT"
] | null | null | null | /*
* @Author Davis.qi
* @Date 2020/8/25
* */
const colorArrList = ["#DF201F", "#F9C152", "#00A74F", "#2E3DB5"]
// rgb to hex
function rgbToHex(r: number, g: number, b: number){
// eslint-disable-next-line no-bitwise
const hex = ((r<<16) | (g<<8) | b).toString(16);
return `#${ new Array(Math.abs(hex.length-7)).join("0") }${hex}`;
}
// hex to rgb
function hexToRgb(hex: any){
const rgb = [];
for(let i=1; i<7; i+=2){
// eslint-disable-next-line radix
rgb.push(parseInt(`0x${ hex.slice(i,i+2)}`));
}
return rgb;
}
function getColorRange (sliderValue: any, props: any) {
const colorUseList: { parse: number; sliderValue: any; colorArrList: string[]; }[] = []
function lotParse (val: any) {
// eslint-disable-next-line radix
val = parseInt(String((val - props.min) / (props.max - props.min) * 100))
// eslint-disable-next-line radix
let parse = parseInt(String(val / (100 / (colorArrList.length - 1)))) + 1
parse = parse > colorArrList.length - 1 ? colorArrList.length - 1 : parse
// console.log(val, parse);
colorUseList.push({
parse,
sliderValue: val,
colorArrList: colorArrList.slice(parse -1, parse + 1),
})
}
// sliderValue是否为Array类型
if (Array.isArray(sliderValue)) {
sliderValue.forEach(item => {
lotParse(item)
})
} else {
lotParse(sliderValue)
}
return colorUseList
}
function transformEnd (colorUse: any) {
const startColor = colorUse.colorArrList[0];
const endColor = colorUse.colorArrList[1];
const sliderValue = colorUse.sliderValue;
// 默认步长100
const step = 100;
// 将 hex 转换为rgb
const sColor = hexToRgb(startColor);
const eColor = hexToRgb(endColor);
// 计算R\G\B每一步的差值
const rStep = (eColor[0] - sColor[0]) / step;
const gStep = (eColor[1] - sColor[1]) / step;
const bStep = (eColor[2] - sColor[2]) / step;
const gradientColorArr = [];
for(let i=0;i<step;i++){
// 计算每一步的hex值
// eslint-disable-next-line radix
gradientColorArr.push(rgbToHex(parseInt(String(rStep * i + sColor[0])),parseInt(String(gStep * i + sColor[1])),parseInt(String(bStep * i + sColor[2]))));
}
// eslint-disable-next-line radix
let mo = parseInt(String(sliderValue % 33))
if (mo === 0) {
mo = sliderValue === 0 ? 0 : 33
}
if (sliderValue === 100) {
mo = 33
}
// eslint-disable-next-line radix
const cIndex = parseInt(String(mo * 3))
return gradientColorArr[cIndex];
}
// 计算渐变过渡色
function gradient (sliderValue: [number], props: any){
const {min, max} = props
if (Array.isArray(sliderValue)) {
sliderValue[0] = sliderValue[0] < min ? min : sliderValue[0]
// @ts-ignore
sliderValue[1] = sliderValue[1] > max ? max : sliderValue[1]
}
const colorUseList = getColorRange(sliderValue, props);
// sliderValue是否为Array类型
colorUseList.forEach((item: object) => {
// @ts-ignore
item.handelColor = transformEnd(item);
})
return colorUseList
}
export default gradient
| 29.194444 | 161 | 0.599112 | 70 | 8 | 0 | 12 | 21 | 0 | 5 | 7 | 7 | 0 | 0 | 8.5 | 1,028 | 0.019455 | 0.020428 | 0 | 0 | 0 | 0.170732 | 0.170732 | 0.28066 | /*
* @Author Davis.qi
* @Date 2020/8/25
* */
const colorArrList = ["#DF201F", "#F9C152", "#00A74F", "#2E3DB5"]
// rgb to hex
/* Example usages of 'rgbToHex' are shown below:
// 计算每一步的hex值
// eslint-disable-next-line radix
gradientColorArr.push(rgbToHex(parseInt(String(rStep * i + sColor[0])), parseInt(String(gStep * i + sColor[1])), parseInt(String(bStep * i + sColor[2]))));
*/
function rgbToHex(r, g, b){
// eslint-disable-next-line no-bitwise
const hex = ((r<<16) | (g<<8) | b).toString(16);
return `#${ new Array(Math.abs(hex.length-7)).join("0") }${hex}`;
}
// hex to rgb
/* Example usages of 'hexToRgb' are shown below:
hexToRgb(startColor);
hexToRgb(endColor);
*/
function hexToRgb(hex){
const rgb = [];
for(let i=1; i<7; i+=2){
// eslint-disable-next-line radix
rgb.push(parseInt(`0x${ hex.slice(i,i+2)}`));
}
return rgb;
}
/* Example usages of 'getColorRange' are shown below:
getColorRange(sliderValue, props);
*/
function getColorRange (sliderValue, props) {
const colorUseList = []
/* Example usages of 'lotParse' are shown below:
lotParse(item);
lotParse(sliderValue);
*/
function lotParse (val) {
// eslint-disable-next-line radix
val = parseInt(String((val - props.min) / (props.max - props.min) * 100))
// eslint-disable-next-line radix
let parse = parseInt(String(val / (100 / (colorArrList.length - 1)))) + 1
parse = parse > colorArrList.length - 1 ? colorArrList.length - 1 : parse
// console.log(val, parse);
colorUseList.push({
parse,
sliderValue: val,
colorArrList: colorArrList.slice(parse -1, parse + 1),
})
}
// sliderValue是否为Array类型
if (Array.isArray(sliderValue)) {
sliderValue.forEach(item => {
lotParse(item)
})
} else {
lotParse(sliderValue)
}
return colorUseList
}
/* Example usages of 'transformEnd' are shown below:
// @ts-ignore
item.handelColor = transformEnd(item);
*/
function transformEnd (colorUse) {
const startColor = colorUse.colorArrList[0];
const endColor = colorUse.colorArrList[1];
const sliderValue = colorUse.sliderValue;
// 默认步长100
const step = 100;
// 将 hex 转换为rgb
const sColor = hexToRgb(startColor);
const eColor = hexToRgb(endColor);
// 计算R\G\B每一步的差值
const rStep = (eColor[0] - sColor[0]) / step;
const gStep = (eColor[1] - sColor[1]) / step;
const bStep = (eColor[2] - sColor[2]) / step;
const gradientColorArr = [];
for(let i=0;i<step;i++){
// 计算每一步的hex值
// eslint-disable-next-line radix
gradientColorArr.push(rgbToHex(parseInt(String(rStep * i + sColor[0])),parseInt(String(gStep * i + sColor[1])),parseInt(String(bStep * i + sColor[2]))));
}
// eslint-disable-next-line radix
let mo = parseInt(String(sliderValue % 33))
if (mo === 0) {
mo = sliderValue === 0 ? 0 : 33
}
if (sliderValue === 100) {
mo = 33
}
// eslint-disable-next-line radix
const cIndex = parseInt(String(mo * 3))
return gradientColorArr[cIndex];
}
// 计算渐变过渡色
/* Example usages of 'gradient' are shown below:
;
*/
function gradient (sliderValue, props){
const {min, max} = props
if (Array.isArray(sliderValue)) {
sliderValue[0] = sliderValue[0] < min ? min : sliderValue[0]
// @ts-ignore
sliderValue[1] = sliderValue[1] > max ? max : sliderValue[1]
}
const colorUseList = getColorRange(sliderValue, props);
// sliderValue是否为Array类型
colorUseList.forEach((item) => {
// @ts-ignore
item.handelColor = transformEnd(item);
})
return colorUseList
}
export default gradient
|
80dba80d424b1b0e099e8e826e1dc83010f57152 | 3,381 | ts | TypeScript | src/blorb/iff.ts | curiousdannii/asyncglk | 029c627afb06a0d2f4450fe9d948b69b0987d7c0 | [
"MIT"
] | 1 | 2022-01-17T22:50:17.000Z | 2022-01-17T22:50:17.000Z | src/blorb/iff.ts | curiousdannii/asyncglk | 029c627afb06a0d2f4450fe9d948b69b0987d7c0 | [
"MIT"
] | 14 | 2022-01-13T00:26:43.000Z | 2022-01-29T04:02:43.000Z | src/blorb/iff.ts | curiousdannii/asyncglk | 029c627afb06a0d2f4450fe9d948b69b0987d7c0 | [
"MIT"
] | 1 | 2022-01-18T06:27:55.000Z | 2022-01-18T06:27:55.000Z | /*
Interchange File Format
=======================
Copyright (c) 2022 Dannii Willis
MIT licenced
https://github.com/curiousdannii/asyncglk
*/
/** A DataView with support for getting and setting arrays and four character codes */
export class FileView extends DataView {
constructor(array: Uint8Array);
constructor(buffer: ArrayBuffer, byteOffset?: number, byteLength?: number);
constructor(data: Uint8Array | ArrayBuffer, byteOffset?: number, byteLength?: number) {
if (data instanceof Uint8Array) {
super(data.buffer, data.byteOffset, data.byteLength)
}
else {
super(data, byteOffset, byteLength)
}
}
getFourCC(index: number) {
return String.fromCharCode(this.getUint8(index), this.getUint8(index + 1), this.getUint8(index + 2), this.getUint8(index + 3))
}
getUint8Subarray(index?: number, length?: number): Uint8Array {
return new Uint8Array(this.buffer, this.byteOffset + (index || 0), length)
}
setFourCC(index: number, text: string) {
this.setUint8(index, text.charCodeAt(0) )
this.setUint8(index + 1, text.charCodeAt(1))
this.setUint8(index + 2, text.charCodeAt(2))
this.setUint8(index + 3, text.charCodeAt(3))
}
setUint8Array(index: number, data: Uint8Array) {
const subarray = this.getUint8Subarray(index, data.length)
subarray.set(data)
}
}
export interface IFFChunk {
data: Uint8Array,
offset: number,
type: string,
}
/** An Interchange File Format reader and writer */
export class IFF {
type = ''
chunks: IFFChunk[] = []
parse(data: Uint8Array) {
const view = new FileView(data)
// Check this is actually an IFF file
if (view.getFourCC(0) !== 'FORM') {
throw new Error('Not an IFF file')
}
// Parse the file
this.type = view.getFourCC(8)
let i = 12
const length = view.getUint32(4) + 8
while (i < length) {
const chunk_length = view.getUint32(i + 4)
if (chunk_length < 0 || (chunk_length + i) > length) {
throw new Error('IFF chunk out of range')
}
this.chunks.push({
data: view.getUint8Subarray(i + 8, chunk_length),
offset: i,
type: view.getFourCC(i),
})
i += 8 + chunk_length
if (i % 2) {
i++
}
}
}
write(): Uint8Array {
// First calculate the required buffer length
let buffer_length = 12
for (const chunk of this.chunks) {
buffer_length += 8 + chunk.data.length
if (buffer_length % 2) {
buffer_length++
}
}
// Now make the IFF file and return it
const view = new FileView(new ArrayBuffer(buffer_length))
view.setFourCC(0, 'FORM')
view.setUint32(4, buffer_length - 8)
view.setFourCC(8, this.type)
let i = 12
for (const chunk of this.chunks) {
view.setFourCC(i, chunk.type)
view.setUint32(i + 4, chunk.data.length)
view.setUint8Array(i + 8, chunk.data)
i += 8 + chunk.data.length
if (i % 2) {
i++
}
}
return view.getUint8Subarray()
}
} | 29.920354 | 134 | 0.562851 | 85 | 7 | 2 | 15 | 8 | 5 | 4 | 0 | 12 | 3 | 1 | 8.285714 | 924 | 0.02381 | 0.008658 | 0.005411 | 0.003247 | 0.001082 | 0 | 0.324324 | 0.259726 | /*
Interchange File Format
=======================
Copyright (c) 2022 Dannii Willis
MIT licenced
https://github.com/curiousdannii/asyncglk
*/
/** A DataView with support for getting and setting arrays and four character codes */
export class FileView extends DataView {
constructor(array);
constructor(buffer, byteOffset?, byteLength?);
constructor(data, byteOffset?, byteLength?) {
if (data instanceof Uint8Array) {
super(data.buffer, data.byteOffset, data.byteLength)
}
else {
super(data, byteOffset, byteLength)
}
}
getFourCC(index) {
return String.fromCharCode(this.getUint8(index), this.getUint8(index + 1), this.getUint8(index + 2), this.getUint8(index + 3))
}
getUint8Subarray(index?, length?) {
return new Uint8Array(this.buffer, this.byteOffset + (index || 0), length)
}
setFourCC(index, text) {
this.setUint8(index, text.charCodeAt(0) )
this.setUint8(index + 1, text.charCodeAt(1))
this.setUint8(index + 2, text.charCodeAt(2))
this.setUint8(index + 3, text.charCodeAt(3))
}
setUint8Array(index, data) {
const subarray = this.getUint8Subarray(index, data.length)
subarray.set(data)
}
}
export interface IFFChunk {
data,
offset,
type,
}
/** An Interchange File Format reader and writer */
export class IFF {
type = ''
chunks = []
parse(data) {
const view = new FileView(data)
// Check this is actually an IFF file
if (view.getFourCC(0) !== 'FORM') {
throw new Error('Not an IFF file')
}
// Parse the file
this.type = view.getFourCC(8)
let i = 12
const length = view.getUint32(4) + 8
while (i < length) {
const chunk_length = view.getUint32(i + 4)
if (chunk_length < 0 || (chunk_length + i) > length) {
throw new Error('IFF chunk out of range')
}
this.chunks.push({
data: view.getUint8Subarray(i + 8, chunk_length),
offset: i,
type: view.getFourCC(i),
})
i += 8 + chunk_length
if (i % 2) {
i++
}
}
}
write() {
// First calculate the required buffer length
let buffer_length = 12
for (const chunk of this.chunks) {
buffer_length += 8 + chunk.data.length
if (buffer_length % 2) {
buffer_length++
}
}
// Now make the IFF file and return it
const view = new FileView(new ArrayBuffer(buffer_length))
view.setFourCC(0, 'FORM')
view.setUint32(4, buffer_length - 8)
view.setFourCC(8, this.type)
let i = 12
for (const chunk of this.chunks) {
view.setFourCC(i, chunk.type)
view.setUint32(i + 4, chunk.data.length)
view.setUint8Array(i + 8, chunk.data)
i += 8 + chunk.data.length
if (i % 2) {
i++
}
}
return view.getUint8Subarray()
}
} |
80dd11e19a7d827820048db4a760e40ccb54f576 | 11,996 | ts | TypeScript | src/l10n/jalaliDate.ts | mojtaba-khallash/flatpickr | c1cd55bb950430afd2809e50bf89f75a38ba3924 | [
"MIT"
] | null | null | null | src/l10n/jalaliDate.ts | mojtaba-khallash/flatpickr | c1cd55bb950430afd2809e50bf89f75a38ba3924 | [
"MIT"
] | null | null | null | src/l10n/jalaliDate.ts | mojtaba-khallash/flatpickr | c1cd55bb950430afd2809e50bf89f75a38ba3924 | [
"MIT"
] | 1 | 2022-02-21T04:53:03.000Z | 2022-02-21T04:53:03.000Z | class Jalalidate extends Date {
jalaliToGregorian(
j_y: number | string,
j_m: number | string,
j_d: number | string
): number[] {
var self: any = this;
var jy = parseInt(String(j_y), 10) - 979;
var jm = parseInt(String(j_m), 10) - 1;
var jd = parseInt(String(j_d), 10) - 1;
var j_day_no =
365 * jy + Math.floor(jy / 33) * 8 + Math.floor(((jy % 33) + 3) / 4);
for (var i = 0; i < jm; ++i) j_day_no += self.j_days_in_month[i];
j_day_no += jd;
var g_day_no = j_day_no + 79;
var gy =
1600 +
400 *
Math.floor(
g_day_no / 146097
); /* 146097 = 365*400 + 400/4 - 400/100 + 400/400 */
g_day_no = g_day_no % 146097;
var leap = true;
if (g_day_no >= 36525) {
/* 36525 = 365*100 + 100/4 */ g_day_no--;
gy +=
100 *
Math.floor(g_day_no / 36524); /* 36524 = 365*100 + 100/4 - 100/100 */
g_day_no = g_day_no % 36524;
if (g_day_no >= 365) g_day_no++;
else leap = false;
}
gy += 4 * Math.floor(g_day_no / 1461); /* 1461 = 365*4 + 4/4 */
g_day_no %= 1461;
if (g_day_no >= 366) {
leap = false;
g_day_no--;
gy += Math.floor(g_day_no / 365);
g_day_no = g_day_no % 365;
}
for (
var i = 0;
g_day_no >= self.g_days_in_month[i] + (i == 1 && leap ? 1 : 0);
i++
)
g_day_no -= self.g_days_in_month[i] + (i == 1 && leap ? 1 : 0);
var gm = i + 1;
var gd = g_day_no + 1;
return [gy, gm, gd];
}
checkDate(j_y: number, j_m: number, j_d: number): boolean {
var self: any = this;
return !(
j_y < 0 ||
j_y > 32767 ||
j_m < 1 ||
j_m > 12 ||
j_d < 1 ||
j_d >
self.j_days_in_month[j_m - 1] +
(j_m == 12 && !(((j_y - 979) % 33) % 4) ? 1 : 0)
);
}
gregorianToJalali(
g_y: number | string,
g_m: number | string,
g_d: number | string
): number[] {
var self: any = this;
var gy = parseInt(String(g_y), 10) - 1600;
var gm = parseInt(String(g_m), 10) - 1;
var gd = parseInt(String(g_d), 10) - 1;
var g_day_no =
365 * gy +
Math.floor((gy + 3) / 4) -
Math.floor((gy + 99) / 100) +
Math.floor((gy + 399) / 400);
for (var i = 0; i < gm; ++i) g_day_no += self.g_days_in_month[i];
if (gm > 1 && ((gy % 4 == 0 && gy % 100 != 0) || gy % 400 == 0))
/* leap and after Feb */
++g_day_no;
g_day_no += gd;
var j_day_no = g_day_no - 79;
var j_np = Math.floor(j_day_no / 12053);
j_day_no %= 12053;
var jy = 979 + 33 * j_np + 4 * Math.floor(j_day_no / 1461);
j_day_no %= 1461;
if (j_day_no >= 366) {
jy += Math.floor((j_day_no - 1) / 365);
j_day_no = (j_day_no - 1) % 365;
}
for (var i = 0; i < 11 && j_day_no >= self.j_days_in_month[i]; ++i) {
j_day_no -= self.j_days_in_month[i];
}
var jm = i + 1;
var jd = j_day_no + 1;
return [jy, jm, jd];
}
setJalali(): void {
var self: any = this;
self.jalalidate = self.gregorianToJalali(
self.gregoriandate.getFullYear(),
self.gregoriandate.getMonth() + 1,
self.gregoriandate.getDate()
);
self.jalalidate[1]--;
}
getDate(): number {
return (this as any).jalalidate[2];
}
getDay(): number {
return (this as any).gregoriandate.getDay();
}
getFullYear(): number {
return (this as any).jalalidate[0];
}
getHours(): number {
return (this as any).gregoriandate.getHours();
}
getMilliseconds(): number {
return (this as any).gregoriandate.getMilliseconds();
}
getMinutes(): number {
return (this as any).gregoriandate.getMinutes();
}
getMonth(): number {
return (this as any).jalalidate[1];
}
getSeconds(): number {
return (this as any).gregoriandate.getSeconds();
}
getTime(): number {
return (this as any).gregoriandate.getTime();
}
getTimezoneOffset(): number {
return (this as any).gregoriandate.getTimezoneOffset();
}
getUTCDate(): number {
return (this as any).gregoriandate.getUTCDate();
}
getUTCDay(): number {
return (this as any).gregoriandate.getUTCDay();
}
getUTCFullYear(): number {
return (this as any).gregoriandate.getUTCFullYear();
}
getUTCHours(): number {
return (this as any).gregoriandate.getUTCHours();
}
getUTCMilliseconds(): number {
return (this as any).gregoriandate.getUTCMilliseconds();
}
getUTCMinutes(): number {
return (this as any).gregoriandate.getUTCMinutes();
}
getUTCMonth(): number {
return (this as any).gregoriandate.getUTCMonth();
}
getUTCSeconds(): number {
return (this as any).gregoriandate.getUTCSeconds();
}
getYear(): number {
return (this as any).gregoriandate.getFullYear() - 1900;
}
setDate(day: number): number {
var self: any = this;
var diff = -1 * (self.jalalidate[2] - day);
var g = self.gregoriandate.setDate(self.gregoriandate.getDate() + diff);
this.setJalali();
return g;
}
setFullYear(
year: number,
month?: number | undefined,
date?: number | undefined
): number {
var self: any = this;
var m = 0;
var d = 1;
if (self.jalalidate !== undefined) {
m = self.jalalidate[1];
d = self.jalalidate[2];
}
if (month !== undefined) m = month;
var negativeMonth = m < 0;
if (negativeMonth) m = 0;
else if (m == 12) {
year++;
m = 0;
}
if (date !== undefined) d = date;
var negativeDate = d < 1;
if (negativeDate) d = 1;
var gDate = self.jalaliToGregorian(year, m + 1, d);
var retval = self.gregoriandate.setFullYear(
gDate[0],
gDate[1] - 1,
gDate[2]
);
if (negativeMonth || negativeDate) {
if (negativeMonth)
retval = self.gregoriandate.setMonth(
self.gregoriandate.getMonth() + month
);
if (negativeDate)
retval = self.gregoriandate.setDate(
self.gregoriandate.getDate() + date - 1
);
this.setJalali();
} else self.jalalidate = [year, m, d];
return retval;
}
setHours(hour: number, min: number, sec: number, millisec: number): number {
var self: any = this;
var retval;
if (min == undefined) retval = self.gregoriandate.setHours(hour);
else if (sec == undefined) retval = self.gregoriandate.setHours(hour, min);
else if (millisec == undefined)
retval = self.gregoriandate.setHours(hour, min, sec);
else retval = self.gregoriandate.setHours(hour, min, sec, millisec);
this.setJalali();
return retval;
}
setMilliseconds(m: number): number {
var retval = (this as any).gregoriandate.setMilliseconds(m);
this.setJalali();
return retval;
}
setMinutes(m: number): number {
var retval = (this as any).gregoriandate.setMinutes(m);
this.setJalali();
return retval;
}
setMonth(month: number, date?: number | undefined): number {
var self: any = this;
var y = self.jalalidate[0];
var m = parseInt(String(month), 10);
var d = self.jalalidate[2];
if (date !== undefined) {
var dTemp = parseInt(String(date), 10);
if (!isNaN(dTemp)) d = dTemp;
}
return this.setFullYear(y, m, d);
}
setSeconds(s: number, m: number): number {
var retval =
m != undefined
? (this as any).gregoriandate.setSeconds(s, m)
: (this as any).gregoriandate.setSeconds(s);
this.setJalali();
return retval;
}
setTime(m: number): number {
var retval = (this as any).gregoriandate.setTime(m);
this.setJalali();
return retval;
}
setUTCDate(d: number): number {
return (this as any).gregoriandate.setUTCDate(d);
}
setUTCFullYear(y: number, m: number, d: number): number {
return (this as any).gregoriandate.setUTCFullYear(y, m, d);
}
setUTCHours(h: number, m: number, s: number, mi: number): number {
return (this as any).gregoriandate.setUTCHours(h, m, s, mi);
}
setUTCMilliseconds(m: number): number {
return (this as any).gregoriandate.setUTCMilliseconds(m);
}
setUTCMinutes(m: number, s: number, mi: number): number {
return (this as any).gregoriandate.setUTCMinutes(m, s, mi);
}
setUTCMonth(m: number, d: number): number {
return (this as any).gregoriandate.setUTCMonth(m, d);
}
setUTCSeconds(s: number, m: number): number {
return (this as any).gregoriandate.setUTCSeconds(s, m);
}
toDateString(): string {
var self: any = this;
return (
self.jalalidate[0] + "/" + self.jalalidate[1] + "/" + self.jalalidate[2]
);
}
toISOString(): string {
return (this as any).gregoriandate.toISOString();
}
toJSON(): string {
return this.toDateString();
}
toLocaleDateString(): string {
return this.toDateString();
}
toLocaleTimeString(): string {
return (this as any).gregoriandate.toLocaleTimeString();
}
toLocaleString(): string {
return this.toDateString() + " " + this.toLocaleTimeString();
}
toString(): string {
return this.toLocaleString();
}
toTimeString(): string {
return this.toLocaleTimeString();
}
toUTCString(): string {
return (this as any).gregoriandate.toUTCString();
}
valueOf(): number {
return (this as any).gregoriandate.valueOf();
}
static UTC(
y: number,
m: number,
d: number,
h: number,
mi: number,
s: number,
ml: number
): number {
return Date.UTC(y, m, d, h, mi, s, ml);
}
static parse(datestring: string): number {
try {
if (datestring.indexOf("Date(") > -1) {
var date = new Date(
parseInt(datestring.replace(/^\/Date\((.*?)\)\/$/, "$1"), 10)
);
var y = new Jalalidate(date).getFullYear(),
m = new Jalalidate(date).getMonth(),
d = new Jalalidate(date).getDate();
return new Jalalidate(y, m, d).getTime();
} else {
var y = parseInt(datestring.substring(0, 4)),
m = parseInt(datestring.substring(5, 7)),
d = parseInt(datestring.substring(8, 10));
return new Jalalidate(y, m - 1, d).getTime();
}
} catch (e) {
return new Jalalidate(1300, 1, 1).getTime();
}
}
constructor(
year?: number | string | Date | undefined,
month?: number | undefined,
day?: number | undefined,
hours?: number | undefined,
minutes?: number | undefined,
seconds?: number | undefined,
miliseconds?: number | undefined
) {
super();
// Set the prototype explicitly.
var self: any = {};
Object.setPrototypeOf(self, Jalalidate.prototype);
self.g_days_in_month = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31];
self.j_days_in_month = [31, 31, 31, 31, 31, 31, 30, 30, 30, 30, 30, 29];
self.gregoriandate = new Date();
self.jalalidate = [];
if (year !== undefined) {
switch (typeof year) {
case "string":
self.gregoriandate = new Date(year);
break;
case "object":
if (year instanceof Jalalidate)
self.gregoriandate = new Date(
(year as any).gregoriandate.getTime()
);
else if (year instanceof Date)
self.gregoriandate = new Date(year.getTime());
break;
case "number":
if (month === undefined) {
self.gregoriandate.setTime(year);
} else {
if (day === undefined) day = 1;
if (year == 1900 || year == 2099)
self.gregoriandate.setFullYear(year, month, day);
else self.setFullYear(year, month, day);
if (hours === undefined) hours = 0;
if (minutes === undefined) minutes = 0;
if (seconds === undefined) seconds = 0;
if (miliseconds === undefined) miliseconds = 0;
self.setHours(hours, minutes, seconds, miliseconds);
}
break;
}
}
self.setJalali();
return self;
}
}
export default Jalalidate;
| 24.887967 | 79 | 0.573108 | 392 | 51 | 0 | 55 | 56 | 0 | 43 | 46 | 112 | 1 | 39 | 5.078431 | 4,168 | 0.025432 | 0.013436 | 0 | 0.00024 | 0.009357 | 0.283951 | 0.691358 | 0.278012 | class Jalalidate extends Date {
jalaliToGregorian(
j_y,
j_m,
j_d
) {
var self = this;
var jy = parseInt(String(j_y), 10) - 979;
var jm = parseInt(String(j_m), 10) - 1;
var jd = parseInt(String(j_d), 10) - 1;
var j_day_no =
365 * jy + Math.floor(jy / 33) * 8 + Math.floor(((jy % 33) + 3) / 4);
for (var i = 0; i < jm; ++i) j_day_no += self.j_days_in_month[i];
j_day_no += jd;
var g_day_no = j_day_no + 79;
var gy =
1600 +
400 *
Math.floor(
g_day_no / 146097
); /* 146097 = 365*400 + 400/4 - 400/100 + 400/400 */
g_day_no = g_day_no % 146097;
var leap = true;
if (g_day_no >= 36525) {
/* 36525 = 365*100 + 100/4 */ g_day_no--;
gy +=
100 *
Math.floor(g_day_no / 36524); /* 36524 = 365*100 + 100/4 - 100/100 */
g_day_no = g_day_no % 36524;
if (g_day_no >= 365) g_day_no++;
else leap = false;
}
gy += 4 * Math.floor(g_day_no / 1461); /* 1461 = 365*4 + 4/4 */
g_day_no %= 1461;
if (g_day_no >= 366) {
leap = false;
g_day_no--;
gy += Math.floor(g_day_no / 365);
g_day_no = g_day_no % 365;
}
for (
var i = 0;
g_day_no >= self.g_days_in_month[i] + (i == 1 && leap ? 1 : 0);
i++
)
g_day_no -= self.g_days_in_month[i] + (i == 1 && leap ? 1 : 0);
var gm = i + 1;
var gd = g_day_no + 1;
return [gy, gm, gd];
}
checkDate(j_y, j_m, j_d) {
var self = this;
return !(
j_y < 0 ||
j_y > 32767 ||
j_m < 1 ||
j_m > 12 ||
j_d < 1 ||
j_d >
self.j_days_in_month[j_m - 1] +
(j_m == 12 && !(((j_y - 979) % 33) % 4) ? 1 : 0)
);
}
gregorianToJalali(
g_y,
g_m,
g_d
) {
var self = this;
var gy = parseInt(String(g_y), 10) - 1600;
var gm = parseInt(String(g_m), 10) - 1;
var gd = parseInt(String(g_d), 10) - 1;
var g_day_no =
365 * gy +
Math.floor((gy + 3) / 4) -
Math.floor((gy + 99) / 100) +
Math.floor((gy + 399) / 400);
for (var i = 0; i < gm; ++i) g_day_no += self.g_days_in_month[i];
if (gm > 1 && ((gy % 4 == 0 && gy % 100 != 0) || gy % 400 == 0))
/* leap and after Feb */
++g_day_no;
g_day_no += gd;
var j_day_no = g_day_no - 79;
var j_np = Math.floor(j_day_no / 12053);
j_day_no %= 12053;
var jy = 979 + 33 * j_np + 4 * Math.floor(j_day_no / 1461);
j_day_no %= 1461;
if (j_day_no >= 366) {
jy += Math.floor((j_day_no - 1) / 365);
j_day_no = (j_day_no - 1) % 365;
}
for (var i = 0; i < 11 && j_day_no >= self.j_days_in_month[i]; ++i) {
j_day_no -= self.j_days_in_month[i];
}
var jm = i + 1;
var jd = j_day_no + 1;
return [jy, jm, jd];
}
setJalali() {
var self = this;
self.jalalidate = self.gregorianToJalali(
self.gregoriandate.getFullYear(),
self.gregoriandate.getMonth() + 1,
self.gregoriandate.getDate()
);
self.jalalidate[1]--;
}
getDate() {
return (this as any).jalalidate[2];
}
getDay() {
return (this as any).gregoriandate.getDay();
}
getFullYear() {
return (this as any).jalalidate[0];
}
getHours() {
return (this as any).gregoriandate.getHours();
}
getMilliseconds() {
return (this as any).gregoriandate.getMilliseconds();
}
getMinutes() {
return (this as any).gregoriandate.getMinutes();
}
getMonth() {
return (this as any).jalalidate[1];
}
getSeconds() {
return (this as any).gregoriandate.getSeconds();
}
getTime() {
return (this as any).gregoriandate.getTime();
}
getTimezoneOffset() {
return (this as any).gregoriandate.getTimezoneOffset();
}
getUTCDate() {
return (this as any).gregoriandate.getUTCDate();
}
getUTCDay() {
return (this as any).gregoriandate.getUTCDay();
}
getUTCFullYear() {
return (this as any).gregoriandate.getUTCFullYear();
}
getUTCHours() {
return (this as any).gregoriandate.getUTCHours();
}
getUTCMilliseconds() {
return (this as any).gregoriandate.getUTCMilliseconds();
}
getUTCMinutes() {
return (this as any).gregoriandate.getUTCMinutes();
}
getUTCMonth() {
return (this as any).gregoriandate.getUTCMonth();
}
getUTCSeconds() {
return (this as any).gregoriandate.getUTCSeconds();
}
getYear() {
return (this as any).gregoriandate.getFullYear() - 1900;
}
setDate(day) {
var self = this;
var diff = -1 * (self.jalalidate[2] - day);
var g = self.gregoriandate.setDate(self.gregoriandate.getDate() + diff);
this.setJalali();
return g;
}
setFullYear(
year,
month?,
date?
) {
var self = this;
var m = 0;
var d = 1;
if (self.jalalidate !== undefined) {
m = self.jalalidate[1];
d = self.jalalidate[2];
}
if (month !== undefined) m = month;
var negativeMonth = m < 0;
if (negativeMonth) m = 0;
else if (m == 12) {
year++;
m = 0;
}
if (date !== undefined) d = date;
var negativeDate = d < 1;
if (negativeDate) d = 1;
var gDate = self.jalaliToGregorian(year, m + 1, d);
var retval = self.gregoriandate.setFullYear(
gDate[0],
gDate[1] - 1,
gDate[2]
);
if (negativeMonth || negativeDate) {
if (negativeMonth)
retval = self.gregoriandate.setMonth(
self.gregoriandate.getMonth() + month
);
if (negativeDate)
retval = self.gregoriandate.setDate(
self.gregoriandate.getDate() + date - 1
);
this.setJalali();
} else self.jalalidate = [year, m, d];
return retval;
}
setHours(hour, min, sec, millisec) {
var self = this;
var retval;
if (min == undefined) retval = self.gregoriandate.setHours(hour);
else if (sec == undefined) retval = self.gregoriandate.setHours(hour, min);
else if (millisec == undefined)
retval = self.gregoriandate.setHours(hour, min, sec);
else retval = self.gregoriandate.setHours(hour, min, sec, millisec);
this.setJalali();
return retval;
}
setMilliseconds(m) {
var retval = (this as any).gregoriandate.setMilliseconds(m);
this.setJalali();
return retval;
}
setMinutes(m) {
var retval = (this as any).gregoriandate.setMinutes(m);
this.setJalali();
return retval;
}
setMonth(month, date?) {
var self = this;
var y = self.jalalidate[0];
var m = parseInt(String(month), 10);
var d = self.jalalidate[2];
if (date !== undefined) {
var dTemp = parseInt(String(date), 10);
if (!isNaN(dTemp)) d = dTemp;
}
return this.setFullYear(y, m, d);
}
setSeconds(s, m) {
var retval =
m != undefined
? (this as any).gregoriandate.setSeconds(s, m)
: (this as any).gregoriandate.setSeconds(s);
this.setJalali();
return retval;
}
setTime(m) {
var retval = (this as any).gregoriandate.setTime(m);
this.setJalali();
return retval;
}
setUTCDate(d) {
return (this as any).gregoriandate.setUTCDate(d);
}
setUTCFullYear(y, m, d) {
return (this as any).gregoriandate.setUTCFullYear(y, m, d);
}
setUTCHours(h, m, s, mi) {
return (this as any).gregoriandate.setUTCHours(h, m, s, mi);
}
setUTCMilliseconds(m) {
return (this as any).gregoriandate.setUTCMilliseconds(m);
}
setUTCMinutes(m, s, mi) {
return (this as any).gregoriandate.setUTCMinutes(m, s, mi);
}
setUTCMonth(m, d) {
return (this as any).gregoriandate.setUTCMonth(m, d);
}
setUTCSeconds(s, m) {
return (this as any).gregoriandate.setUTCSeconds(s, m);
}
toDateString() {
var self = this;
return (
self.jalalidate[0] + "/" + self.jalalidate[1] + "/" + self.jalalidate[2]
);
}
toISOString() {
return (this as any).gregoriandate.toISOString();
}
toJSON() {
return this.toDateString();
}
toLocaleDateString() {
return this.toDateString();
}
toLocaleTimeString() {
return (this as any).gregoriandate.toLocaleTimeString();
}
toLocaleString() {
return this.toDateString() + " " + this.toLocaleTimeString();
}
toString() {
return this.toLocaleString();
}
toTimeString() {
return this.toLocaleTimeString();
}
toUTCString() {
return (this as any).gregoriandate.toUTCString();
}
valueOf() {
return (this as any).gregoriandate.valueOf();
}
static UTC(
y,
m,
d,
h,
mi,
s,
ml
) {
return Date.UTC(y, m, d, h, mi, s, ml);
}
static parse(datestring) {
try {
if (datestring.indexOf("Date(") > -1) {
var date = new Date(
parseInt(datestring.replace(/^\/Date\((.*?)\)\/$/, "$1"), 10)
);
var y = new Jalalidate(date).getFullYear(),
m = new Jalalidate(date).getMonth(),
d = new Jalalidate(date).getDate();
return new Jalalidate(y, m, d).getTime();
} else {
var y = parseInt(datestring.substring(0, 4)),
m = parseInt(datestring.substring(5, 7)),
d = parseInt(datestring.substring(8, 10));
return new Jalalidate(y, m - 1, d).getTime();
}
} catch (e) {
return new Jalalidate(1300, 1, 1).getTime();
}
}
constructor(
year?,
month?,
day?,
hours?,
minutes?,
seconds?,
miliseconds?
) {
super();
// Set the prototype explicitly.
var self = {};
Object.setPrototypeOf(self, Jalalidate.prototype);
self.g_days_in_month = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31];
self.j_days_in_month = [31, 31, 31, 31, 31, 31, 30, 30, 30, 30, 30, 29];
self.gregoriandate = new Date();
self.jalalidate = [];
if (year !== undefined) {
switch (typeof year) {
case "string":
self.gregoriandate = new Date(year);
break;
case "object":
if (year instanceof Jalalidate)
self.gregoriandate = new Date(
(year as any).gregoriandate.getTime()
);
else if (year instanceof Date)
self.gregoriandate = new Date(year.getTime());
break;
case "number":
if (month === undefined) {
self.gregoriandate.setTime(year);
} else {
if (day === undefined) day = 1;
if (year == 1900 || year == 2099)
self.gregoriandate.setFullYear(year, month, day);
else self.setFullYear(year, month, day);
if (hours === undefined) hours = 0;
if (minutes === undefined) minutes = 0;
if (seconds === undefined) seconds = 0;
if (miliseconds === undefined) miliseconds = 0;
self.setHours(hours, minutes, seconds, miliseconds);
}
break;
}
}
self.setJalali();
return self;
}
}
export default Jalalidate;
|
80fa0621f4bb2a3e7a7309955e7800bdb64e35e9 | 1,491 | tsx | TypeScript | frontend/src/Reducer/SampleReducer.tsx | TheMrPhantom/react-vorlage | 5d9db221536ce7846b1b5e7fa29fdc2563254bcf | [
"MIT"
] | 1 | 2022-03-28T12:16:03.000Z | 2022-03-28T12:16:03.000Z | frontend/src/Reducer/SampleReducer.tsx | TheMrPhantom/beachify | cb5111ff459b26efed3327a595391e034c7af970 | [
"MIT"
] | null | null | null | frontend/src/Reducer/SampleReducer.tsx | TheMrPhantom/beachify | cb5111ff459b26efed3327a595391e034c7af970 | [
"MIT"
] | 1 | 2022-03-28T12:16:13.000Z | 2022-03-28T12:16:13.000Z | const initialState: EventCreationType = {
eventInformations: {
name: "",
place: "",
informations: "",
owner: {
name: "",
mail: ""
}
}, timeslots: {
days: []
}, settings: {
optional: false,
hasMaxParticipants: false,
maxParticipants: 0,
onlyOneOption: false,
secretPoll: false,
hasDeadline: false,
sendResult: false
}
}
export type EventCreationType = {
eventInformations: {
name: string,
place: string,
informations: string,
owner: {
name: string,
mail: string
}
}, timeslots: {
days: Array<{
day: Date,
times: Array<Array<Date>>,
id: number
}>
},
settings: {
optional: boolean,
hasMaxParticipants: boolean,
maxParticipants: number,
onlyOneOption: boolean,
secretPoll: boolean,
hasDeadline: boolean,
sendResult: boolean
}
}
const reducer = (state = initialState, { type, payload }: {
type: string, payload: any | {
day: Date,
times: Array<Array<Date>>,
id: number
}
}) => {
var newState = { ...state }
switch (type) {
case "ADD_DAY_TO_EVENT_CREATION":
newState.timeslots.days.push(payload)
return newState
default:
return state
}
}
export default reducer
| 21.608696 | 59 | 0.507042 | 64 | 1 | 0 | 2 | 3 | 3 | 0 | 1 | 15 | 1 | 0 | 8 | 343 | 0.008746 | 0.008746 | 0.008746 | 0.002915 | 0 | 0.111111 | 1.666667 | 0.219868 | const initialState = {
eventInformations: {
name: "",
place: "",
informations: "",
owner: {
name: "",
mail: ""
}
}, timeslots: {
days: []
}, settings: {
optional: false,
hasMaxParticipants: false,
maxParticipants: 0,
onlyOneOption: false,
secretPoll: false,
hasDeadline: false,
sendResult: false
}
}
export type EventCreationType = {
eventInformations, timeslots,
settings
}
/* Example usages of 'reducer' are shown below:
;
*/
const reducer = (state = initialState, { type, payload }) => {
var newState = { ...state }
switch (type) {
case "ADD_DAY_TO_EVENT_CREATION":
newState.timeslots.days.push(payload)
return newState
default:
return state
}
}
export default reducer
|
cc1bd8633c28b192a5a91afcf98250d0c41d1b53 | 1,888 | ts | TypeScript | lib/utils/URLUtils.ts | siaikin/utils | 703cea3d5f3000bdfa10f09c3a6279eb6065c7eb | [
"MIT"
] | 1 | 2022-03-17T10:08:07.000Z | 2022-03-17T10:08:07.000Z | lib/utils/URLUtils.ts | siaikin/utils | 703cea3d5f3000bdfa10f09c3a6279eb6065c7eb | [
"MIT"
] | 5 | 2022-01-22T12:46:17.000Z | 2022-01-24T01:50:09.000Z | lib/utils/URLUtils.ts | siaikin/utils | 703cea3d5f3000bdfa10f09c3a6279eb6065c7eb | [
"MIT"
] | null | null | null | type ParseredURL = {
protocol: string,
hostname: string,
port: string,
host: string,
isSecurity: boolean
};
/**
* 解析URL
* @param {string} str
*/
export function parse(str: string): ParseredURL {
str = str.replace('://', ':');
let offset = [str.indexOf(':')];
const res: Partial<ParseredURL> = {},
protocolIndex = [0, offset[0]],
hostnameIndex = [0, 0],
portIndex = [0, 0];
offset.push(str.indexOf(':', offset[0] + 1), str.indexOf('/', offset[0] + 4), str.indexOf('?'), str.indexOf('#'), str.length);
offset = offset.filter(i => i > 0).sort((a, b) => a - b);
hostnameIndex[0] = protocolIndex[1] + 1;
hostnameIndex[1] = offset[1];
if (str.indexOf(':', offset[0] + 1) !== -1) {
portIndex[0] = hostnameIndex[1] + 1;
portIndex[1] = offset[2] || portIndex[0];
}
res.protocol = str.slice(...protocolIndex);
res.hostname = str.slice(...hostnameIndex);
res.port = str.slice(...portIndex);
res.host = `${res.hostname}${res.port.length <= 0 ? '' : (':' + res.port)}`;
res.isSecurity = res.protocol[res.protocol.length - 1] === 's';
return res as ParseredURL;
}
export function parseToServerInfo(url: string): ServerInfo {
const temp = parse(url);
return {
host: temp.host,
hostname: temp.hostname,
port: Number.parseInt(temp.port),
security: temp.isSecurity,
httpAddress: `http${temp.isSecurity ? 's' : ''}://${temp.host}`,
wsAddress: `ws${temp.isSecurity ? 's' : ''}://${temp.host}`
};
}
export function isIpAddress(hostname: string): boolean {
const parts = hostname.split('.');
if (parts.length !== 4) return false;
for (let i = parts.length; i--;)
if (!/^\d*$/.test(parts[i])) return false;
return true;
}
export interface ServerInfo {
host: string;
hostname: string;
port: number;
security: boolean;
httpAddress: string;
wsAddress: string;
}
| 26.591549 | 128 | 0.603814 | 55 | 5 | 0 | 6 | 8 | 11 | 1 | 0 | 15 | 2 | 1 | 7.2 | 597 | 0.018425 | 0.0134 | 0.018425 | 0.00335 | 0.001675 | 0 | 0.5 | 0.2617 | type ParseredURL = {
protocol,
hostname,
port,
host,
isSecurity
};
/**
* 解析URL
* @param {string} str
*/
export /* Example usages of 'parse' are shown below:
parse(url);
*/
function parse(str) {
str = str.replace('://', ':');
let offset = [str.indexOf(':')];
const res = {},
protocolIndex = [0, offset[0]],
hostnameIndex = [0, 0],
portIndex = [0, 0];
offset.push(str.indexOf(':', offset[0] + 1), str.indexOf('/', offset[0] + 4), str.indexOf('?'), str.indexOf('#'), str.length);
offset = offset.filter(i => i > 0).sort((a, b) => a - b);
hostnameIndex[0] = protocolIndex[1] + 1;
hostnameIndex[1] = offset[1];
if (str.indexOf(':', offset[0] + 1) !== -1) {
portIndex[0] = hostnameIndex[1] + 1;
portIndex[1] = offset[2] || portIndex[0];
}
res.protocol = str.slice(...protocolIndex);
res.hostname = str.slice(...hostnameIndex);
res.port = str.slice(...portIndex);
res.host = `${res.hostname}${res.port.length <= 0 ? '' : (':' + res.port)}`;
res.isSecurity = res.protocol[res.protocol.length - 1] === 's';
return res as ParseredURL;
}
export function parseToServerInfo(url) {
const temp = parse(url);
return {
host: temp.host,
hostname: temp.hostname,
port: Number.parseInt(temp.port),
security: temp.isSecurity,
httpAddress: `http${temp.isSecurity ? 's' : ''}://${temp.host}`,
wsAddress: `ws${temp.isSecurity ? 's' : ''}://${temp.host}`
};
}
export function isIpAddress(hostname) {
const parts = hostname.split('.');
if (parts.length !== 4) return false;
for (let i = parts.length; i--;)
if (!/^\d*$/.test(parts[i])) return false;
return true;
}
export interface ServerInfo {
host;
hostname;
port;
security;
httpAddress;
wsAddress;
}
|
cc299aea3f88db08cc45e1c9563848e05f2be195 | 2,340 | ts | TypeScript | solutions/day09.ts | GiyoMoon/aoc2021 | 83d7e9018ed3b628353bc9a0a37b70a1462ecd74 | [
"Unlicense"
] | null | null | null | solutions/day09.ts | GiyoMoon/aoc2021 | 83d7e9018ed3b628353bc9a0a37b70a1462ecd74 | [
"Unlicense"
] | 1 | 2022-02-03T11:04:17.000Z | 2022-02-03T11:04:17.000Z | solutions/day09.ts | GiyoMoon/aoc2021 | 83d7e9018ed3b628353bc9a0a37b70a1462ecd74 | [
"Unlicense"
] | null | null | null | export default class Day9 {
public solve(input: string): { part1: any, part2: any; } {
const lavaTubes = input.split('\n').map(line => line.split('').map(v => parseInt(v)));
// part 1
const lowestPoints: number[][] = [];
lavaTubes.forEach((line, y) => {
line.forEach((point, x) => {
if (
(line[x - 1] === undefined || line[x - 1] > point) &&
(line[x + 1] === undefined || line[x + 1] > point) &&
(lavaTubes[y - 1] === undefined || lavaTubes[y - 1] && lavaTubes[y - 1][x] > point) &&
(lavaTubes[y + 1] === undefined || lavaTubes[y + 1] && lavaTubes[y + 1][x] > point)
) {
lowestPoints.push([y, x]);
}
});
});
const riskLevel = lowestPoints.map(lp => lavaTubes[lp[0]][lp[1]]).reduce((x, a) => x + a) + lowestPoints.length;
// part 2
const basins: number[] = [];
lowestPoints.forEach(lp => {
const basinSize = this._getBasinSize(lp, lavaTubes);
basins.push(basinSize);
});
const multipliedTopBasins = basins.sort((a, b) => b - a).slice(0, 3).reduce((x, a) => x * a);
return { part1: riskLevel, part2: multipliedTopBasins };
}
private _getBasinSize(lp: number[], lavaTubes: number[][]) {
let basinFlow: number[][][] = [[lp]];
for (let position = 0; position < basinFlow.length; position++) {
if (!basinFlow[position + 1]) {
basinFlow[position + 1] = [];
}
const positions = basinFlow[position];
positions.forEach(pos => {
let posX = [pos[1] - 1, pos[1] + 1, pos[1], pos[1]];
let posY = [pos[0], pos[0], pos[0] - 1, pos[0] + 1];
for (let i = 0; i < posX.length; i++) {
if (
lavaTubes[posY[i]] && lavaTubes[posY[i]][posX[i]] > lavaTubes[pos[0]][pos[1]] &&
lavaTubes[posY[i]][posX[i]] !== 9
) {
basinFlow[position + 1].push([posY[i], posX[i]]);
}
}
});
if (basinFlow[position + 1].length === 0) {
basinFlow.pop();
}
}
let uniquePositions: number[][] = [];
basinFlow.filter(basinFlow => {
basinFlow.forEach(pos => {
if (!uniquePositions.some(up => up[0] === pos[0] && up[1] === pos[1])) {
uniquePositions.push(pos);
}
});
});
return uniquePositions.length;
}
}
| 32.054795 | 116 | 0.507692 | 59 | 15 | 0 | 21 | 13 | 0 | 1 | 2 | 7 | 1 | 0 | 6.533333 | 780 | 0.046154 | 0.016667 | 0 | 0.001282 | 0 | 0.040816 | 0.142857 | 0.334006 | export default class Day9 {
public solve(input) {
const lavaTubes = input.split('\n').map(line => line.split('').map(v => parseInt(v)));
// part 1
const lowestPoints = [];
lavaTubes.forEach((line, y) => {
line.forEach((point, x) => {
if (
(line[x - 1] === undefined || line[x - 1] > point) &&
(line[x + 1] === undefined || line[x + 1] > point) &&
(lavaTubes[y - 1] === undefined || lavaTubes[y - 1] && lavaTubes[y - 1][x] > point) &&
(lavaTubes[y + 1] === undefined || lavaTubes[y + 1] && lavaTubes[y + 1][x] > point)
) {
lowestPoints.push([y, x]);
}
});
});
const riskLevel = lowestPoints.map(lp => lavaTubes[lp[0]][lp[1]]).reduce((x, a) => x + a) + lowestPoints.length;
// part 2
const basins = [];
lowestPoints.forEach(lp => {
const basinSize = this._getBasinSize(lp, lavaTubes);
basins.push(basinSize);
});
const multipliedTopBasins = basins.sort((a, b) => b - a).slice(0, 3).reduce((x, a) => x * a);
return { part1: riskLevel, part2: multipliedTopBasins };
}
private _getBasinSize(lp, lavaTubes) {
let basinFlow = [[lp]];
for (let position = 0; position < basinFlow.length; position++) {
if (!basinFlow[position + 1]) {
basinFlow[position + 1] = [];
}
const positions = basinFlow[position];
positions.forEach(pos => {
let posX = [pos[1] - 1, pos[1] + 1, pos[1], pos[1]];
let posY = [pos[0], pos[0], pos[0] - 1, pos[0] + 1];
for (let i = 0; i < posX.length; i++) {
if (
lavaTubes[posY[i]] && lavaTubes[posY[i]][posX[i]] > lavaTubes[pos[0]][pos[1]] &&
lavaTubes[posY[i]][posX[i]] !== 9
) {
basinFlow[position + 1].push([posY[i], posX[i]]);
}
}
});
if (basinFlow[position + 1].length === 0) {
basinFlow.pop();
}
}
let uniquePositions = [];
basinFlow.filter(basinFlow => {
basinFlow.forEach(pos => {
if (!uniquePositions.some(up => up[0] === pos[0] && up[1] === pos[1])) {
uniquePositions.push(pos);
}
});
});
return uniquePositions.length;
}
}
|
cc385db443069762ff1495e56965825d8c6162d6 | 2,013 | ts | TypeScript | problemset/longest-palindromic-substring/index.ts | OUDUIDUI/leet-code | 50e61ce16d1c419ccefc075ae9ead721cdd1cdbb | [
"MIT"
] | 6 | 2022-01-17T03:19:56.000Z | 2022-01-17T05:45:39.000Z | problemset/longest-palindromic-substring/index.ts | OUDUIDUI/leet-code | 50e61ce16d1c419ccefc075ae9ead721cdd1cdbb | [
"MIT"
] | null | null | null | problemset/longest-palindromic-substring/index.ts | OUDUIDUI/leet-code | 50e61ce16d1c419ccefc075ae9ead721cdd1cdbb | [
"MIT"
] | null | null | null | /**
* 中心扩展
* @desc 时间复杂度 O(N^2) 空间复杂度 O(1)
* @param s {string}
* @return {string}
*/
export function longestPalindrome(s: string): string {
if (s.length < 2) return s
// 初始化结果,默认为第一个字符
let res: string = s[0]
// 遍历,以i为中心点
for (let i = 0; i < s.length; i++) {
// 中心点为一个字符的情况
if (i > 0 && s[i - 1] === s[i + 1])
findPalindrome(i, i)
// 中心点为两个个字符的情况
if (s[i] === s[i + 1])
findPalindrome(i, i + 1)
}
return res
/**
* 查找回文子串
* @param left {number}
* @param right {number}
*/
function findPalindrome(left: number, right: number): void {
// 初始化中心点
let palindrome = left === right ? s[left] : s[left] + s[right]
// 向左右散开,一一比较
while (s[--left] === s[++right] && left >= 0 && right < s.length)
palindrome = s[left] + palindrome + s[right]
// 返回最长值
res = res.length < palindrome.length ? palindrome : res
}
}
export function longestPalindrome2(s: string): string {
if (s.length < 2) return s
// 将s转换为加了特殊字符#的字符数组,目的是统一奇偶数的回文中心差异性问题
s = `#${s.split('').join('#')}#`
let start = 0
let end = -1
const armLen: Array<number> = [] // 当前集合
let right = -1
let j = -1 // 中心点
for (let i = 0; i < s.length; i++) {
let curArmLen: number // 当前臂长
if (right >= i) {
const iSym = j * 2 - i
const minArmLen = Math.min(armLen[iSym], right - i)
curArmLen = expand(i - minArmLen, i + minArmLen)
}
else {
curArmLen = expand(i, i)
}
armLen.push(curArmLen)
if (i + curArmLen > right) {
j = i
right = i + curArmLen
}
if (2 * curArmLen + 1 > end - start) {
start = i - curArmLen
end = i + curArmLen
}
}
let ans = ''
for (let i: number = start; i <= end; i++) {
if (s[i] !== '#')
ans += s[i]
}
return ans
function expand(left: number, right: number): number {
while (left >= 0 && right < s.length && s[left] === s[right]) {
left--
right++
}
return Math.floor((right - left - 2) / 2)
}
}
| 21.880435 | 69 | 0.529061 | 59 | 4 | 0 | 6 | 14 | 0 | 2 | 0 | 14 | 0 | 0 | 16 | 757 | 0.01321 | 0.018494 | 0 | 0 | 0 | 0 | 0.583333 | 0.261174 | /**
* 中心扩展
* @desc 时间复杂度 O(N^2) 空间复杂度 O(1)
* @param s {string}
* @return {string}
*/
export function longestPalindrome(s) {
if (s.length < 2) return s
// 初始化结果,默认为第一个字符
let res = s[0]
// 遍历,以i为中心点
for (let i = 0; i < s.length; i++) {
// 中心点为一个字符的情况
if (i > 0 && s[i - 1] === s[i + 1])
findPalindrome(i, i)
// 中心点为两个个字符的情况
if (s[i] === s[i + 1])
findPalindrome(i, i + 1)
}
return res
/**
* 查找回文子串
* @param left {number}
* @param right {number}
*/
/* Example usages of 'findPalindrome' are shown below:
findPalindrome(i, i);
findPalindrome(i, i + 1);
*/
function findPalindrome(left, right) {
// 初始化中心点
let palindrome = left === right ? s[left] : s[left] + s[right]
// 向左右散开,一一比较
while (s[--left] === s[++right] && left >= 0 && right < s.length)
palindrome = s[left] + palindrome + s[right]
// 返回最长值
res = res.length < palindrome.length ? palindrome : res
}
}
export function longestPalindrome2(s) {
if (s.length < 2) return s
// 将s转换为加了特殊字符#的字符数组,目的是统一奇偶数的回文中心差异性问题
s = `#${s.split('').join('#')}#`
let start = 0
let end = -1
const armLen = [] // 当前集合
let right = -1
let j = -1 // 中心点
for (let i = 0; i < s.length; i++) {
let curArmLen // 当前臂长
if (right >= i) {
const iSym = j * 2 - i
const minArmLen = Math.min(armLen[iSym], right - i)
curArmLen = expand(i - minArmLen, i + minArmLen)
}
else {
curArmLen = expand(i, i)
}
armLen.push(curArmLen)
if (i + curArmLen > right) {
j = i
right = i + curArmLen
}
if (2 * curArmLen + 1 > end - start) {
start = i - curArmLen
end = i + curArmLen
}
}
let ans = ''
for (let i = start; i <= end; i++) {
if (s[i] !== '#')
ans += s[i]
}
return ans
/* Example usages of 'expand' are shown below:
curArmLen = expand(i - minArmLen, i + minArmLen);
curArmLen = expand(i, i);
*/
function expand(left, right) {
while (left >= 0 && right < s.length && s[left] === s[right]) {
left--
right++
}
return Math.floor((right - left - 2) / 2)
}
}
|
ccb196e52b7cb4052c3419c0b71cb8628a6eb217 | 5,577 | ts | TypeScript | mechanics/tests/icosphere/lib/icomesh.ts | tomm2000/StarForge-Prototypes | 72e9b152ef2e07707ac26157344a8cff3587bdf5 | [
"MIT"
] | 1 | 2022-03-13T11:21:21.000Z | 2022-03-13T11:21:21.000Z | mechanics/tests/icosphere/lib/icomesh.ts | tomm2000/StarForge-Prototypes | 72e9b152ef2e07707ac26157344a8cff3587bdf5 | [
"MIT"
] | null | null | null | mechanics/tests/icosphere/lib/icomesh.ts | tomm2000/StarForge-Prototypes | 72e9b152ef2e07707ac26157344a8cff3587bdf5 | [
"MIT"
] | null | null | null | export type icoMesh = {
vertices: Float32Array,
triangles: Uint32Array | Uint16Array,
uv?: Float32Array,
}
export default function icomesh(order = 4, uvMap = false): icoMesh {
if (order > 10) throw new Error(`Max order is 10, but given ${order}.`);
// set up an icosahedron (12 vertices / 20 triangles)
const f = (1 + Math.sqrt(5)) / 2;
const T = Math.pow(4, order);
const numVertices = 10 * T + 2;
const numDuplicates = !uvMap ? 0 : order === 0 ? 3 : Math.pow(2, order) * 3 + 9;
const vertices = new Float32Array((numVertices + numDuplicates) * 3);
vertices.set(Float32Array.of(
-1, f, 0, 1, f, 0, -1, -f, 0, 1, -f, 0,
0, -1, f, 0, 1, f, 0, -1, -f, 0, 1, -f,
f, 0, -1, f, 0, 1, -f, 0, -1, -f, 0, 1
));
let triangles: Uint32Array | Uint16Array = Uint16Array.of(
0, 11, 5, 0, 5, 1, 0, 1, 7, 0, 7, 10, 0, 10, 11,
11, 10, 2, 5, 11, 4, 1, 5, 9, 7, 1, 8, 10, 7, 6,
3, 9, 4, 3, 4, 2, 3, 2, 6, 3, 6, 8, 3, 8, 9,
9, 8, 1, 4, 9, 5, 2, 4, 11, 6, 2, 10, 8, 6, 7
);
function invertTriangles(triangles: Uint32Array | Uint16Array) {
for (let i = 0; i < triangles.length; i += 3) {
let a = triangles[i], b = triangles[i + 1], c = triangles[i + 2];
triangles[i] = c;
triangles[i + 1] = b;
triangles[i + 2] = a;
}
}
invertTriangles(triangles);
let v = 12;
const midCache = order ? new Map() : null; // midpoint vertices cache to avoid duplicating shared vertices
function addMidPoint(a: number, b: number) {
const key = Math.floor(((a + b) * (a + b + 1) / 2) + Math.min(a, b)); // Cantor's pairing function
if (!midCache) {
throw new Error(`Midpoint cache is not initialized.`);
}
const i = midCache.get(key);
if (i !== undefined && i !== null) {
midCache.delete(key); // midpoint is only reused once, so we delete it for performance
return i;
}
midCache.set(key, v);
vertices[3 * v + 0] = (vertices[3 * a + 0] + vertices[3 * b + 0]) * 0.5;
vertices[3 * v + 1] = (vertices[3 * a + 1] + vertices[3 * b + 1]) * 0.5;
vertices[3 * v + 2] = (vertices[3 * a + 2] + vertices[3 * b + 2]) * 0.5;
return v++;
}
let trianglesPrev: Uint32Array | Uint16Array = triangles;
const IndexArray = order > 5 ? Uint32Array : Uint16Array;
for (let i = 0; i < order; i++) { // repeatedly subdivide each triangle into 4 triangles
const prevLen: number = trianglesPrev.length;
triangles = new IndexArray(prevLen * 4);
for (let k = 0; k < prevLen; k += 3) {
const v1 = trianglesPrev[k + 0];
const v2 = trianglesPrev[k + 1];
const v3 = trianglesPrev[k + 2];
const a = addMidPoint(v1, v2);
const b = addMidPoint(v2, v3);
const c = addMidPoint(v3, v1);
let t = k * 4;
triangles[t++] = v1; triangles[t++] = a; triangles[t++] = c;
triangles[t++] = v2; triangles[t++] = b; triangles[t++] = a;
triangles[t++] = v3; triangles[t++] = c; triangles[t++] = b;
triangles[t++] = a; triangles[t++] = b; triangles[t++] = c;
}
trianglesPrev = triangles;
}
// normalize vertices
for (let i = 0; i < numVertices * 3; i += 3) {
const v1 = vertices[i + 0];
const v2 = vertices[i + 1];
const v3 = vertices[i + 2];
const m = 1 / Math.sqrt(v1 * v1 + v2 * v2 + v3 * v3);
vertices[i + 0] *= m;
vertices[i + 1] *= m;
vertices[i + 2] *= m;
}
if (!uvMap) return { vertices, triangles };
// uv mapping
const uv = new Float32Array((numVertices + numDuplicates) * 2);
for (let i = 0; i < numVertices; i++) {
uv[2 * i + 0] = Math.atan2(vertices[3 * i + 2], vertices[3 * i]) / (2 * Math.PI) + 0.5;
uv[2 * i + 1] = Math.asin(vertices[3 * i + 1]) / Math.PI + 0.5;
}
const duplicates = new Map();
function addDuplicate(i: number, uvx: number, uvy: number, cached: boolean) {
if (cached) {
const dupe = duplicates.get(i);
if (dupe !== undefined) return dupe;
}
vertices[3 * v + 0] = vertices[3 * i + 0];
vertices[3 * v + 1] = vertices[3 * i + 1];
vertices[3 * v + 2] = vertices[3 * i + 2];
uv[2 * v + 0] = uvx;
uv[2 * v + 1] = uvy;
if (cached) duplicates.set(i, v);
return v++;
}
for (let i = 0; i < triangles.length; i += 3) {
const a = triangles[i + 0];
const b = triangles[i + 1];
const c = triangles[i + 2];
let ax = uv[2 * a];
let bx = uv[2 * b];
let cx = uv[2 * c];
const ay = uv[2 * a + 1];
const by = uv[2 * b + 1];
const cy = uv[2 * c + 1];
// uv fixing code; don't ask me how I got here
if (bx - ax >= 0.5 && ay !== 1) bx -= 1;
if (cx - bx > 0.5) cx -= 1;
if (ax > 0.5 && ax - cx > 0.5 || ax === 1 && cy === 0) ax -= 1;
if (bx > 0.5 && bx - ax > 0.5) bx -= 1;
if (ay === 0 || ay === 1) {
ax = (bx + cx) / 2;
if (ay === bx) uv[2 * a] = ax;
else triangles[i + 0] = addDuplicate(a, ax, ay, false);
} else if (by === 0 || by === 1) {
bx = (ax + cx) / 2;
if (by === ax) uv[2 * b] = bx;
else triangles[i + 1] = addDuplicate(b, bx, by, false);
} else if (cy === 0 || cy === 1) {
cx = (ax + bx) / 2;
if (cy === ax) uv[2 * c] = cx;
else triangles[i + 2] = addDuplicate(c, cx, cy, false);
}
// if (ax !== uv[2 * a] && ay !== 0 && ay !== 1) triangles[i + 0] = addDuplicate(a, ax, ay, true);
if (bx !== uv[2 * b] && by !== 0 && by !== 1) triangles[i + 1] = addDuplicate(b, bx, by, true);
if (cx !== uv[2 * c] && cy !== 0 && cy !== 1) triangles[i + 2] = addDuplicate(c, cx, cy, true);
}
return { vertices, triangles, uv };
} | 34.214724 | 108 | 0.519455 | 131 | 4 | 0 | 9 | 45 | 3 | 3 | 0 | 7 | 1 | 0 | 38.75 | 2,222 | 0.005851 | 0.020252 | 0.00135 | 0.00045 | 0 | 0 | 0.114754 | 0.251381 | export type icoMesh = {
vertices,
triangles,
uv?,
}
export default function icomesh(order = 4, uvMap = false) {
if (order > 10) throw new Error(`Max order is 10, but given ${order}.`);
// set up an icosahedron (12 vertices / 20 triangles)
const f = (1 + Math.sqrt(5)) / 2;
const T = Math.pow(4, order);
const numVertices = 10 * T + 2;
const numDuplicates = !uvMap ? 0 : order === 0 ? 3 : Math.pow(2, order) * 3 + 9;
const vertices = new Float32Array((numVertices + numDuplicates) * 3);
vertices.set(Float32Array.of(
-1, f, 0, 1, f, 0, -1, -f, 0, 1, -f, 0,
0, -1, f, 0, 1, f, 0, -1, -f, 0, 1, -f,
f, 0, -1, f, 0, 1, -f, 0, -1, -f, 0, 1
));
let triangles = Uint16Array.of(
0, 11, 5, 0, 5, 1, 0, 1, 7, 0, 7, 10, 0, 10, 11,
11, 10, 2, 5, 11, 4, 1, 5, 9, 7, 1, 8, 10, 7, 6,
3, 9, 4, 3, 4, 2, 3, 2, 6, 3, 6, 8, 3, 8, 9,
9, 8, 1, 4, 9, 5, 2, 4, 11, 6, 2, 10, 8, 6, 7
);
/* Example usages of 'invertTriangles' are shown below:
invertTriangles(triangles);
*/
function invertTriangles(triangles) {
for (let i = 0; i < triangles.length; i += 3) {
let a = triangles[i], b = triangles[i + 1], c = triangles[i + 2];
triangles[i] = c;
triangles[i + 1] = b;
triangles[i + 2] = a;
}
}
invertTriangles(triangles);
let v = 12;
const midCache = order ? new Map() : null; // midpoint vertices cache to avoid duplicating shared vertices
/* Example usages of 'addMidPoint' are shown below:
addMidPoint(v1, v2);
addMidPoint(v2, v3);
addMidPoint(v3, v1);
*/
function addMidPoint(a, b) {
const key = Math.floor(((a + b) * (a + b + 1) / 2) + Math.min(a, b)); // Cantor's pairing function
if (!midCache) {
throw new Error(`Midpoint cache is not initialized.`);
}
const i = midCache.get(key);
if (i !== undefined && i !== null) {
midCache.delete(key); // midpoint is only reused once, so we delete it for performance
return i;
}
midCache.set(key, v);
vertices[3 * v + 0] = (vertices[3 * a + 0] + vertices[3 * b + 0]) * 0.5;
vertices[3 * v + 1] = (vertices[3 * a + 1] + vertices[3 * b + 1]) * 0.5;
vertices[3 * v + 2] = (vertices[3 * a + 2] + vertices[3 * b + 2]) * 0.5;
return v++;
}
let trianglesPrev = triangles;
const IndexArray = order > 5 ? Uint32Array : Uint16Array;
for (let i = 0; i < order; i++) { // repeatedly subdivide each triangle into 4 triangles
const prevLen = trianglesPrev.length;
triangles = new IndexArray(prevLen * 4);
for (let k = 0; k < prevLen; k += 3) {
const v1 = trianglesPrev[k + 0];
const v2 = trianglesPrev[k + 1];
const v3 = trianglesPrev[k + 2];
const a = addMidPoint(v1, v2);
const b = addMidPoint(v2, v3);
const c = addMidPoint(v3, v1);
let t = k * 4;
triangles[t++] = v1; triangles[t++] = a; triangles[t++] = c;
triangles[t++] = v2; triangles[t++] = b; triangles[t++] = a;
triangles[t++] = v3; triangles[t++] = c; triangles[t++] = b;
triangles[t++] = a; triangles[t++] = b; triangles[t++] = c;
}
trianglesPrev = triangles;
}
// normalize vertices
for (let i = 0; i < numVertices * 3; i += 3) {
const v1 = vertices[i + 0];
const v2 = vertices[i + 1];
const v3 = vertices[i + 2];
const m = 1 / Math.sqrt(v1 * v1 + v2 * v2 + v3 * v3);
vertices[i + 0] *= m;
vertices[i + 1] *= m;
vertices[i + 2] *= m;
}
if (!uvMap) return { vertices, triangles };
// uv mapping
const uv = new Float32Array((numVertices + numDuplicates) * 2);
for (let i = 0; i < numVertices; i++) {
uv[2 * i + 0] = Math.atan2(vertices[3 * i + 2], vertices[3 * i]) / (2 * Math.PI) + 0.5;
uv[2 * i + 1] = Math.asin(vertices[3 * i + 1]) / Math.PI + 0.5;
}
const duplicates = new Map();
/* Example usages of 'addDuplicate' are shown below:
triangles[i + 0] = addDuplicate(a, ax, ay, false);
triangles[i + 1] = addDuplicate(b, bx, by, false);
triangles[i + 2] = addDuplicate(c, cx, cy, false);
triangles[i + 1] = addDuplicate(b, bx, by, true);
triangles[i + 2] = addDuplicate(c, cx, cy, true);
*/
function addDuplicate(i, uvx, uvy, cached) {
if (cached) {
const dupe = duplicates.get(i);
if (dupe !== undefined) return dupe;
}
vertices[3 * v + 0] = vertices[3 * i + 0];
vertices[3 * v + 1] = vertices[3 * i + 1];
vertices[3 * v + 2] = vertices[3 * i + 2];
uv[2 * v + 0] = uvx;
uv[2 * v + 1] = uvy;
if (cached) duplicates.set(i, v);
return v++;
}
for (let i = 0; i < triangles.length; i += 3) {
const a = triangles[i + 0];
const b = triangles[i + 1];
const c = triangles[i + 2];
let ax = uv[2 * a];
let bx = uv[2 * b];
let cx = uv[2 * c];
const ay = uv[2 * a + 1];
const by = uv[2 * b + 1];
const cy = uv[2 * c + 1];
// uv fixing code; don't ask me how I got here
if (bx - ax >= 0.5 && ay !== 1) bx -= 1;
if (cx - bx > 0.5) cx -= 1;
if (ax > 0.5 && ax - cx > 0.5 || ax === 1 && cy === 0) ax -= 1;
if (bx > 0.5 && bx - ax > 0.5) bx -= 1;
if (ay === 0 || ay === 1) {
ax = (bx + cx) / 2;
if (ay === bx) uv[2 * a] = ax;
else triangles[i + 0] = addDuplicate(a, ax, ay, false);
} else if (by === 0 || by === 1) {
bx = (ax + cx) / 2;
if (by === ax) uv[2 * b] = bx;
else triangles[i + 1] = addDuplicate(b, bx, by, false);
} else if (cy === 0 || cy === 1) {
cx = (ax + bx) / 2;
if (cy === ax) uv[2 * c] = cx;
else triangles[i + 2] = addDuplicate(c, cx, cy, false);
}
// if (ax !== uv[2 * a] && ay !== 0 && ay !== 1) triangles[i + 0] = addDuplicate(a, ax, ay, true);
if (bx !== uv[2 * b] && by !== 0 && by !== 1) triangles[i + 1] = addDuplicate(b, bx, by, true);
if (cx !== uv[2 * c] && cy !== 0 && cy !== 1) triangles[i + 2] = addDuplicate(c, cx, cy, true);
}
return { vertices, triangles, uv };
} |
ccee70850d7be59ff29044ffd01e8ec90a3de543 | 3,119 | ts | TypeScript | client/src/plugins/simplify.ts | microsoft/OneLabeler | 316175e98a1cba72d651567d9fac08fc6c7bdf4f | [
"MIT"
] | 8 | 2022-03-26T17:45:01.000Z | 2022-03-30T14:12:20.000Z | client/src/plugins/simplify.ts | microsoft/OneLabeler | 316175e98a1cba72d651567d9fac08fc6c7bdf4f | [
"MIT"
] | null | null | null | client/src/plugins/simplify.ts | microsoft/OneLabeler | 316175e98a1cba72d651567d9fac08fc6c7bdf4f | [
"MIT"
] | 1 | 2022-03-27T06:11:24.000Z | 2022-03-27T06:11:24.000Z | // Copyright (c) Microsoft Corporation.
// Licensed under the MIT License.
/*
(c) 2017, Vladimir Agafonkin
Simplify.js, a high-performance JS polyline simplification library
mourner.github.io/simplify-js
*/
// to suit your point format, run search/replace for '[0]' and '[1]';
// for 3D version, see 3d branch (configurability would draw significant performance overhead)
type Point = [number, number];
// square distance between 2 points
const getSqDist = (p1: Point, p2: Point): number => {
const dx = p1[0] - p2[0];
const dy = p1[1] - p2[1];
return dx * dx + dy * dy;
};
// square distance from a point to a segment
const getSqSegDist = (p: Point, p1: Point, p2: Point): number => {
let [x, y] = p1;
let dx = p2[0] - x;
let dy = p2[1] - y;
if (dx !== 0 || dy !== 0) {
const t = ((p[0] - x) * dx + (p[1] - y) * dy) / (dx * dx + dy * dy);
if (t > 1) {
[x, y] = p2;
} else if (t > 0) {
x += dx * t;
y += dy * t;
}
}
dx = p[0] - x;
dy = p[1] - y;
return dx * dx + dy * dy;
};
// rest of the code doesn't care about point format
// basic distance-based simplification
const simplifyRadialDist = (points: Point[], sqTolerance: number): Point[] => {
if (points.length === 0) return [];
let prevPoint = points[0];
const newPoints = [prevPoint];
let point: Point | null = null;
points.forEach((d) => {
point = d;
if (getSqDist(point, prevPoint) > sqTolerance) {
newPoints.push(point);
prevPoint = point;
}
});
if (prevPoint !== point) newPoints.push(point as unknown as Point);
return newPoints;
};
const simplifyDPStep = (
points: Point[],
first: number,
last: number,
sqTolerance: number,
simplified: Point[],
): void => {
let maxSqDist = sqTolerance;
let index: number | null = null;
for (let i = first + 1; i < last; i += 1) {
const sqDist = getSqSegDist(points[i], points[first], points[last]);
if (sqDist > maxSqDist) {
index = i;
maxSqDist = sqDist;
}
}
if (maxSqDist > sqTolerance) {
if ((index as number) - first > 1) {
simplifyDPStep(points, first, (index as number), sqTolerance, simplified);
}
simplified.push(points[(index as number)]);
if (last - (index as number) > 1) {
simplifyDPStep(points, (index as number), last, sqTolerance, simplified);
}
}
};
// simplification using Ramer-Douglas-Peucker algorithm
const simplifyDouglasPeucker = (points: Point[], sqTolerance: number): Point[] => {
const last = points.length - 1;
const simplified = [points[0]];
simplifyDPStep(points, 0, last, sqTolerance, simplified);
simplified.push(points[last]);
return simplified;
};
// both algorithms combined for awesome performance
export default (
points: Point[],
tolerance: number,
highestQuality: boolean,
): Point[] => {
if (points.length <= 2) return points;
const sqTolerance = tolerance !== undefined ? tolerance * tolerance : 1;
let simplified = highestQuality ? points : simplifyRadialDist(points, sqTolerance);
simplified = simplifyDouglasPeucker(points, sqTolerance);
return simplified;
};
| 26.887931 | 94 | 0.629368 | 82 | 7 | 0 | 18 | 22 | 0 | 5 | 0 | 19 | 1 | 7 | 9.142857 | 973 | 0.025694 | 0.02261 | 0 | 0.001028 | 0.007194 | 0 | 0.404255 | 0.305389 | // Copyright (c) Microsoft Corporation.
// Licensed under the MIT License.
/*
(c) 2017, Vladimir Agafonkin
Simplify.js, a high-performance JS polyline simplification library
mourner.github.io/simplify-js
*/
// to suit your point format, run search/replace for '[0]' and '[1]';
// for 3D version, see 3d branch (configurability would draw significant performance overhead)
type Point = [number, number];
// square distance between 2 points
/* Example usages of 'getSqDist' are shown below:
getSqDist(point, prevPoint) > sqTolerance;
*/
const getSqDist = (p1, p2) => {
const dx = p1[0] - p2[0];
const dy = p1[1] - p2[1];
return dx * dx + dy * dy;
};
// square distance from a point to a segment
/* Example usages of 'getSqSegDist' are shown below:
getSqSegDist(points[i], points[first], points[last]);
*/
const getSqSegDist = (p, p1, p2) => {
let [x, y] = p1;
let dx = p2[0] - x;
let dy = p2[1] - y;
if (dx !== 0 || dy !== 0) {
const t = ((p[0] - x) * dx + (p[1] - y) * dy) / (dx * dx + dy * dy);
if (t > 1) {
[x, y] = p2;
} else if (t > 0) {
x += dx * t;
y += dy * t;
}
}
dx = p[0] - x;
dy = p[1] - y;
return dx * dx + dy * dy;
};
// rest of the code doesn't care about point format
// basic distance-based simplification
/* Example usages of 'simplifyRadialDist' are shown below:
highestQuality ? points : simplifyRadialDist(points, sqTolerance);
*/
const simplifyRadialDist = (points, sqTolerance) => {
if (points.length === 0) return [];
let prevPoint = points[0];
const newPoints = [prevPoint];
let point = null;
points.forEach((d) => {
point = d;
if (getSqDist(point, prevPoint) > sqTolerance) {
newPoints.push(point);
prevPoint = point;
}
});
if (prevPoint !== point) newPoints.push(point as unknown as Point);
return newPoints;
};
/* Example usages of 'simplifyDPStep' are shown below:
simplifyDPStep(points, first, (index as number), sqTolerance, simplified);
simplifyDPStep(points, (index as number), last, sqTolerance, simplified);
simplifyDPStep(points, 0, last, sqTolerance, simplified);
*/
const simplifyDPStep = (
points,
first,
last,
sqTolerance,
simplified,
) => {
let maxSqDist = sqTolerance;
let index = null;
for (let i = first + 1; i < last; i += 1) {
const sqDist = getSqSegDist(points[i], points[first], points[last]);
if (sqDist > maxSqDist) {
index = i;
maxSqDist = sqDist;
}
}
if (maxSqDist > sqTolerance) {
if ((index as number) - first > 1) {
simplifyDPStep(points, first, (index as number), sqTolerance, simplified);
}
simplified.push(points[(index as number)]);
if (last - (index as number) > 1) {
simplifyDPStep(points, (index as number), last, sqTolerance, simplified);
}
}
};
// simplification using Ramer-Douglas-Peucker algorithm
/* Example usages of 'simplifyDouglasPeucker' are shown below:
simplified = simplifyDouglasPeucker(points, sqTolerance);
*/
const simplifyDouglasPeucker = (points, sqTolerance) => {
const last = points.length - 1;
const simplified = [points[0]];
simplifyDPStep(points, 0, last, sqTolerance, simplified);
simplified.push(points[last]);
return simplified;
};
// both algorithms combined for awesome performance
export default (
points,
tolerance,
highestQuality,
) => {
if (points.length <= 2) return points;
const sqTolerance = tolerance !== undefined ? tolerance * tolerance : 1;
let simplified = highestQuality ? points : simplifyRadialDist(points, sqTolerance);
simplified = simplifyDouglasPeucker(points, sqTolerance);
return simplified;
};
|
3222146aea50ffa11b775aeb30ffdf9bd48830ed | 6,318 | ts | TypeScript | client/zip_code.ts | otya128/web-bml | 16c225971aa7ce040d6e99d598cc626734265c6d | [
"MIT"
] | 161 | 2022-03-19T07:01:38.000Z | 2022-03-29T07:56:59.000Z | client/zip_code.ts | otya128/web-bml | 16c225971aa7ce040d6e99d598cc626734265c6d | [
"MIT"
] | 5 | 2022-03-24T06:39:51.000Z | 2022-03-30T11:24:34.000Z | client/zip_code.ts | otya128/web-bml | 16c225971aa7ce040d6e99d598cc626734265c6d | [
"MIT"
] | 7 | 2022-03-19T07:30:24.000Z | 2022-03-26T23:38:00.000Z | export type ZipRange = {
from: number,
to: number,
}
export type ZipCode = {
list: ZipRange[],
excludeList: ZipRange[],
}
function decodeZipList(buffer: Uint8Array, length: number): ZipRange[] {
let result: ZipRange[] = [];
let off = 0;
let prevFlag = 0;
while (off < length) {
if (buffer[off] & 0x80) {
let digits = buffer[off] & 0x7f;
off++;
let flag = buffer[off] >> 4;
let a = buffer[off] & 0xf;
off++;
let b = buffer[off] >> 4;
let c = buffer[off] & 0xf;
off++;
let d = buffer[off] >> 4;
let e = buffer[off] & 0xf;
let digitList = [a, b, c, d, e];
off++;
switch (flag) {
// 3digit list
case 0x8:
for (const d of digitList) {
if (d >= 10 && d <= 0xe) {
throw new Error("d >= 10 && d <= 0xe 3digit list");
}
if (d === 0xf) {
continue;
}
result.push({ from: (digits * 10 + d) * 10000, to: (digits * 10 + d + 1) * 10000 - 1});
}
break;
// 3digit range
case 0x9:
if (a !== 0xf) {
throw new Error("a !== 0xf 3digit range");
}
if (b === 0xf || c === 0xf) {
throw new Error("b === 0xf || c === 0xf 3digit range");
}
result.push({ from: (digits * 10 + b) * 10000, to: (digits * 10 + c + 1) * 10000 - 1 });
if (d === 0xf || e === 0xf) {
} else if (d !== 0xf && e !== 0xf) {
result.push({ from: (digits * 10 + d) * 10000, to: (digits * 10 + e + 1) * 10000 - 1 });
} else {
throw new Error("not allowed d, e 3digit range");
}
break;
// 5digit list
case 0xA:
if (a === 0xf || b === 0xf || c === 0xf) {
throw new Error("a === 0xf || b === 0xf || c === 0xf 5digit list");
}
result.push({ from: (digits * 1000 + a * 100 + b * 10 + c) * 100, to: (digits * 1000 + a * 100 + b * 10 + c + 1) * 100 - 1 });
if (d === 0xf || e === 0xf) {
} else if (d !== 0xf && e !== 0xf) {
result.push({ from: (digits * 1000 + a * 100 + d * 10 + e) * 100, to: (digits * 1000 + a * 100 + d * 10 + e + 1) * 100 - 1});
} else {
throw new Error("not allowed d, e 5digit range");
}
break;
// 5digit range From
case 0xB:
if (a === 0xf || b === 0xf || c === 0xf || d !== 0xf || e !== 0xf) {
throw new Error("a === 0xf || b === 0xf || c === 0xf || d !== 0xf || e !== 0xf 5digit range");
}
result.push({ from: (digits * 1000 + a * 100 + b * 10 + c) * 100, to: (digits * 1000 + a * 100 + b * 10 + c) * 100 });
break;
// 5digit range To
case 0xC:
if (prevFlag !== 0xB) {
throw new Error("prevFlag !== 0xB 5digit range");
}
if (a === 0xf || b === 0xf || c === 0xf || d !== 0xf || e !== 0xf) {
throw new Error("a === 0xf || b === 0xf || c === 0xf || d !== 0xf || e !== 0xf 5digit range");
}
result[result.length - 1].to = (digits * 1000 + a * 100 + b * 10 + c + 1) * 100 - 1;
break;
// 7digit range From
case 0xD:
case 0xF:
if (a === 0xf || b === 0xf || c === 0xf || d === 0xf || e === 0xf) {
throw new Error("a === 0xf || b === 0xf || c === 0xf || d === 0xf || e === 0xf 7digit range/list");
}
result.push({ from: digits * 100000 + a * 10000 + b * 1000 + c * 100 + d * 10 + e, to: digits * 100000 + a * 10000 + b * 1000 + c * 100 + d * 10 + e });
break;
// 7digit range To
case 0xE:
if (prevFlag !== 0xD) {
throw new Error("prevFlag !== 0xD 7digit range");
}
if (a === 0xf || b === 0xf || c === 0xf || d === 0xf || e === 0xf) {
throw new Error("a === 0xf || b === 0xf || c === 0xf || d === 0xf || e === 0xf 7digit range");
}
result[result.length - 1].to = digits * 100000 + a * 10000 + b * 1000 + c * 100 + d * 10 + e;
break;
}
prevFlag = flag;
} else {
let from = buffer[off] & 0x7f;
off++;
let to = buffer[off] & 0x7f;
result.push({ from: from * 100000, to: (to + 1) * 100000 - 1 });
off++;
if (buffer[off] & 0x80) {
let from2 = buffer[off] & 0x7f;
off++;
let to2 = buffer[off] & 0x7f;
off++;
result.push({ from: from2 * 100000, to: (to2 + 1) * 100000 - 1 });
} else {
off += 2;
}
}
}
return result;
}
export function decodeZipCode(buffer: Uint8Array): ZipCode {
let length = buffer[0];
let excludeListLength = buffer[1];
return {
excludeList: decodeZipList(buffer.slice(2), excludeListLength),
list: decodeZipList(buffer.slice(2 + excludeListLength, 1 + length), length - 1 - excludeListLength)
};
}
function zipRangeInclude(zipRange: ZipRange[], compared: number): boolean {
return zipRange.some(zip => zip.from <= compared && zip.to >= compared);
}
export function zipCodeInclude(zipCode: ZipCode, compared: number): boolean {
return zipRangeInclude(zipCode.list, compared) && !zipRangeInclude(zipCode.excludeList, compared);
}
| 43.875 | 172 | 0.382241 | 131 | 5 | 0 | 8 | 17 | 4 | 2 | 0 | 7 | 2 | 0 | 23.2 | 1,946 | 0.00668 | 0.008736 | 0.002055 | 0.001028 | 0 | 0 | 0.205882 | 0.216174 | export type ZipRange = {
from,
to,
}
export type ZipCode = {
list,
excludeList,
}
/* Example usages of 'decodeZipList' are shown below:
decodeZipList(buffer.slice(2), excludeListLength);
decodeZipList(buffer.slice(2 + excludeListLength, 1 + length), length - 1 - excludeListLength);
*/
function decodeZipList(buffer, length) {
let result = [];
let off = 0;
let prevFlag = 0;
while (off < length) {
if (buffer[off] & 0x80) {
let digits = buffer[off] & 0x7f;
off++;
let flag = buffer[off] >> 4;
let a = buffer[off] & 0xf;
off++;
let b = buffer[off] >> 4;
let c = buffer[off] & 0xf;
off++;
let d = buffer[off] >> 4;
let e = buffer[off] & 0xf;
let digitList = [a, b, c, d, e];
off++;
switch (flag) {
// 3digit list
case 0x8:
for (const d of digitList) {
if (d >= 10 && d <= 0xe) {
throw new Error("d >= 10 && d <= 0xe 3digit list");
}
if (d === 0xf) {
continue;
}
result.push({ from: (digits * 10 + d) * 10000, to: (digits * 10 + d + 1) * 10000 - 1});
}
break;
// 3digit range
case 0x9:
if (a !== 0xf) {
throw new Error("a !== 0xf 3digit range");
}
if (b === 0xf || c === 0xf) {
throw new Error("b === 0xf || c === 0xf 3digit range");
}
result.push({ from: (digits * 10 + b) * 10000, to: (digits * 10 + c + 1) * 10000 - 1 });
if (d === 0xf || e === 0xf) {
} else if (d !== 0xf && e !== 0xf) {
result.push({ from: (digits * 10 + d) * 10000, to: (digits * 10 + e + 1) * 10000 - 1 });
} else {
throw new Error("not allowed d, e 3digit range");
}
break;
// 5digit list
case 0xA:
if (a === 0xf || b === 0xf || c === 0xf) {
throw new Error("a === 0xf || b === 0xf || c === 0xf 5digit list");
}
result.push({ from: (digits * 1000 + a * 100 + b * 10 + c) * 100, to: (digits * 1000 + a * 100 + b * 10 + c + 1) * 100 - 1 });
if (d === 0xf || e === 0xf) {
} else if (d !== 0xf && e !== 0xf) {
result.push({ from: (digits * 1000 + a * 100 + d * 10 + e) * 100, to: (digits * 1000 + a * 100 + d * 10 + e + 1) * 100 - 1});
} else {
throw new Error("not allowed d, e 5digit range");
}
break;
// 5digit range From
case 0xB:
if (a === 0xf || b === 0xf || c === 0xf || d !== 0xf || e !== 0xf) {
throw new Error("a === 0xf || b === 0xf || c === 0xf || d !== 0xf || e !== 0xf 5digit range");
}
result.push({ from: (digits * 1000 + a * 100 + b * 10 + c) * 100, to: (digits * 1000 + a * 100 + b * 10 + c) * 100 });
break;
// 5digit range To
case 0xC:
if (prevFlag !== 0xB) {
throw new Error("prevFlag !== 0xB 5digit range");
}
if (a === 0xf || b === 0xf || c === 0xf || d !== 0xf || e !== 0xf) {
throw new Error("a === 0xf || b === 0xf || c === 0xf || d !== 0xf || e !== 0xf 5digit range");
}
result[result.length - 1].to = (digits * 1000 + a * 100 + b * 10 + c + 1) * 100 - 1;
break;
// 7digit range From
case 0xD:
case 0xF:
if (a === 0xf || b === 0xf || c === 0xf || d === 0xf || e === 0xf) {
throw new Error("a === 0xf || b === 0xf || c === 0xf || d === 0xf || e === 0xf 7digit range/list");
}
result.push({ from: digits * 100000 + a * 10000 + b * 1000 + c * 100 + d * 10 + e, to: digits * 100000 + a * 10000 + b * 1000 + c * 100 + d * 10 + e });
break;
// 7digit range To
case 0xE:
if (prevFlag !== 0xD) {
throw new Error("prevFlag !== 0xD 7digit range");
}
if (a === 0xf || b === 0xf || c === 0xf || d === 0xf || e === 0xf) {
throw new Error("a === 0xf || b === 0xf || c === 0xf || d === 0xf || e === 0xf 7digit range");
}
result[result.length - 1].to = digits * 100000 + a * 10000 + b * 1000 + c * 100 + d * 10 + e;
break;
}
prevFlag = flag;
} else {
let from = buffer[off] & 0x7f;
off++;
let to = buffer[off] & 0x7f;
result.push({ from: from * 100000, to: (to + 1) * 100000 - 1 });
off++;
if (buffer[off] & 0x80) {
let from2 = buffer[off] & 0x7f;
off++;
let to2 = buffer[off] & 0x7f;
off++;
result.push({ from: from2 * 100000, to: (to2 + 1) * 100000 - 1 });
} else {
off += 2;
}
}
}
return result;
}
export function decodeZipCode(buffer) {
let length = buffer[0];
let excludeListLength = buffer[1];
return {
excludeList: decodeZipList(buffer.slice(2), excludeListLength),
list: decodeZipList(buffer.slice(2 + excludeListLength, 1 + length), length - 1 - excludeListLength)
};
}
/* Example usages of 'zipRangeInclude' are shown below:
zipRangeInclude(zipCode.list, compared) && !zipRangeInclude(zipCode.excludeList, compared);
*/
function zipRangeInclude(zipRange, compared) {
return zipRange.some(zip => zip.from <= compared && zip.to >= compared);
}
export function zipCodeInclude(zipCode, compared) {
return zipRangeInclude(zipCode.list, compared) && !zipRangeInclude(zipCode.excludeList, compared);
}
|
326d9d855454c3462da30894d82c92685bff1b6e | 2,462 | ts | TypeScript | src/Rule.ts | thomasvolk/cellular-js | e19fc7aa67f3c6da83d1f5afb1d6f7a9ea4f2f71 | [
"Apache-2.0"
] | 1 | 2022-02-11T00:54:39.000Z | 2022-02-11T00:54:39.000Z | src/Rule.ts | thomasvolk/cellular-js | e19fc7aa67f3c6da83d1f5afb1d6f7a9ea4f2f71 | [
"Apache-2.0"
] | null | null | null | src/Rule.ts | thomasvolk/cellular-js | e19fc7aa67f3c6da83d1f5afb1d6f7a9ea4f2f71 | [
"Apache-2.0"
] | null | null | null | export interface Rule {
calculateNewValue(cellValue: number, neighbourValues: Array<number>): number
}
export function normalizeToOneOrZero(values: Array<number>): Array<number> {
return values.map(v => {
if (v > 0) return 1
else return 0
})
}
function countLivingNeighbours(neighbourValues: Array<number>) {
const normalizedValues = normalizeToOneOrZero(neighbourValues)
return normalizedValues.reduce((sum, current) => sum + current, 0)
}
export class BSRule implements Rule {
readonly born: Array<number>
readonly stay: Array<number>
constructor(born: Array<number>, stayAlive: Array<number>) {
this.born = born
this.stay = stayAlive
}
calculateNewValue(cellValue: number, neighbourValues: number[]): number {
const livingNeighbours = countLivingNeighbours(neighbourValues)
if(cellValue > 0 && this.stay.indexOf(livingNeighbours) >= 0) {
return cellValue
}
else if(cellValue == 0 && this.born.indexOf(livingNeighbours) >= 0) {
return 1
}
return 0
}
static convert(rule: Rule): BSRule {
if(rule instanceof EEFFRule) {
const eeffRule = rule as EEFFRule
var born = Array<number>();
for(var i = eeffRule.fl; i <= eeffRule.fu; i++) {
born.push(i)
}
var stay = Array<number>();
for(var i = eeffRule.el; i <= eeffRule.eu; i++) {
stay.push(i)
}
return new BSRule(born, stay)
}
else if(rule instanceof BSRule) {
return rule as BSRule
}
throw new Error(`can not convert rule: ${rule}`)
}
}
export class EEFFRule implements Rule {
readonly el: number
readonly eu: number
readonly fl: number
readonly fu: number
constructor(el: number, eu: number, fl: number, fu: number) {
this.el = el
this.eu = eu
this.fl = fl
this.fu = fu
}
calculateNewValue(cellValue: number, neighbourValues: Array<number>): number {
const livingNeighbours = countLivingNeighbours(neighbourValues)
if(cellValue > 0 && (livingNeighbours < this.el || livingNeighbours > this.eu)) {
return 0
}
else if(cellValue == 0 && (livingNeighbours >= this.fl && livingNeighbours <= this.fu)) {
return 1
}
return cellValue
}
}
| 30.395062 | 97 | 0.59342 | 71 | 9 | 1 | 18 | 8 | 6 | 2 | 0 | 26 | 3 | 4 | 5.222222 | 633 | 0.042654 | 0.012638 | 0.009479 | 0.004739 | 0.006319 | 0 | 0.619048 | 0.317564 | export interface Rule {
calculateNewValue(cellValue, neighbourValues)
}
export /* Example usages of 'normalizeToOneOrZero' are shown below:
normalizeToOneOrZero(neighbourValues);
*/
function normalizeToOneOrZero(values) {
return values.map(v => {
if (v > 0) return 1
else return 0
})
}
/* Example usages of 'countLivingNeighbours' are shown below:
countLivingNeighbours(neighbourValues);
*/
function countLivingNeighbours(neighbourValues) {
const normalizedValues = normalizeToOneOrZero(neighbourValues)
return normalizedValues.reduce((sum, current) => sum + current, 0)
}
export class BSRule implements Rule {
readonly born
readonly stay
constructor(born, stayAlive) {
this.born = born
this.stay = stayAlive
}
calculateNewValue(cellValue, neighbourValues) {
const livingNeighbours = countLivingNeighbours(neighbourValues)
if(cellValue > 0 && this.stay.indexOf(livingNeighbours) >= 0) {
return cellValue
}
else if(cellValue == 0 && this.born.indexOf(livingNeighbours) >= 0) {
return 1
}
return 0
}
static convert(rule) {
if(rule instanceof EEFFRule) {
const eeffRule = rule as EEFFRule
var born = Array<number>();
for(var i = eeffRule.fl; i <= eeffRule.fu; i++) {
born.push(i)
}
var stay = Array<number>();
for(var i = eeffRule.el; i <= eeffRule.eu; i++) {
stay.push(i)
}
return new BSRule(born, stay)
}
else if(rule instanceof BSRule) {
return rule as BSRule
}
throw new Error(`can not convert rule: ${rule}`)
}
}
export class EEFFRule implements Rule {
readonly el
readonly eu
readonly fl
readonly fu
constructor(el, eu, fl, fu) {
this.el = el
this.eu = eu
this.fl = fl
this.fu = fu
}
calculateNewValue(cellValue, neighbourValues) {
const livingNeighbours = countLivingNeighbours(neighbourValues)
if(cellValue > 0 && (livingNeighbours < this.el || livingNeighbours > this.eu)) {
return 0
}
else if(cellValue == 0 && (livingNeighbours >= this.fl && livingNeighbours <= this.fu)) {
return 1
}
return cellValue
}
}
|
32bcd4e76a30ec100affb770f27b7755481f68d6 | 1,820 | ts | TypeScript | ui/packages/app/src/components/utils/utils.ts | aribornstein/gradio | 08ef8b0ed5c748250bfe8b6ffec1c63c5b6e81cd | [
"Apache-2.0"
] | 1 | 2022-03-20T01:44:53.000Z | 2022-03-20T01:44:53.000Z | ui/packages/app/src/components/utils/utils.ts | aribornstein/gradio | 08ef8b0ed5c748250bfe8b6ffec1c63c5b6e81cd | [
"Apache-2.0"
] | null | null | null | ui/packages/app/src/components/utils/utils.ts | aribornstein/gradio | 08ef8b0ed5c748250bfe8b6ffec1c63c5b6e81cd | [
"Apache-2.0"
] | null | null | null | interface XYValue {
x: number;
y: number;
}
interface ObjectValue {
values: XYValue[];
}
export function get_domains(
values: ObjectValue[] | { values: number[] }
): [number, number] {
let _vs: number[];
if (Array.isArray(values)) {
_vs = values.reduce<number[]>((acc, { values }) => {
return [...acc, ...values.map(({ x, y }) => y)];
}, []);
} else {
_vs = values.values;
}
return [Math.min(..._vs), Math.max(..._vs)];
}
interface Row {
name: string;
values: number[];
}
interface RowPoint {
name: string;
values: Array<{ x: number; y: number }>;
}
interface TransformedValues {
x: Row;
y: Array<RowPoint>;
}
export function transform_values(
values: Array<Record<string, string>>,
x?: string,
y?: string[]
) {
const transformed_values = Object.entries(
values[0]
).reduce<TransformedValues>(
(acc, next, i) => {
if ((!x && i === 0) || (x && next[0] === x)) {
acc.x.name = next[0];
} else if (!y || (y && y.includes(next[0]))) {
acc.y.push({ name: next[0], values: [] });
}
return acc;
},
{ x: { name: "", values: [] }, y: [] }
);
for (let i = 0; i < values.length; i++) {
const _a = Object.entries(values[i]);
for (let j = 0; j < _a.length; j++) {
let [name, x] = _a[j];
if (name === transformed_values.x.name) {
transformed_values.x.values.push(parseInt(x, 10));
} else {
transformed_values.y[j - 1].values.push({
y: parseInt(_a[j][1], 10),
x: parseInt(_a[0][1], 10)
});
}
}
}
return transformed_values;
}
let c = 0;
export function get_color(): string {
let default_colors = [
[255, 99, 132],
[54, 162, 235],
[240, 176, 26],
[153, 102, 255],
[75, 192, 192],
[255, 159, 64]
];
if (c >= default_colors.length) c = 0;
const [r, g, b] = default_colors[c++];
return `rgb(${r},${g},${b})`;
}
| 19.569892 | 54 | 0.560989 | 80 | 6 | 0 | 10 | 9 | 9 | 0 | 0 | 17 | 5 | 0 | 9.333333 | 764 | 0.020942 | 0.01178 | 0.01178 | 0.006545 | 0 | 0 | 0.5 | 0.26746 | interface XYValue {
x;
y;
}
interface ObjectValue {
values;
}
export function get_domains(
values
) {
let _vs;
if (Array.isArray(values)) {
_vs = values.reduce<number[]>((acc, { values }) => {
return [...acc, ...values.map(({ x, y }) => y)];
}, []);
} else {
_vs = values.values;
}
return [Math.min(..._vs), Math.max(..._vs)];
}
interface Row {
name;
values;
}
interface RowPoint {
name;
values;
}
interface TransformedValues {
x;
y;
}
export function transform_values(
values,
x?,
y?
) {
const transformed_values = Object.entries(
values[0]
).reduce<TransformedValues>(
(acc, next, i) => {
if ((!x && i === 0) || (x && next[0] === x)) {
acc.x.name = next[0];
} else if (!y || (y && y.includes(next[0]))) {
acc.y.push({ name: next[0], values: [] });
}
return acc;
},
{ x: { name: "", values: [] }, y: [] }
);
for (let i = 0; i < values.length; i++) {
const _a = Object.entries(values[i]);
for (let j = 0; j < _a.length; j++) {
let [name, x] = _a[j];
if (name === transformed_values.x.name) {
transformed_values.x.values.push(parseInt(x, 10));
} else {
transformed_values.y[j - 1].values.push({
y: parseInt(_a[j][1], 10),
x: parseInt(_a[0][1], 10)
});
}
}
}
return transformed_values;
}
let c = 0;
export function get_color() {
let default_colors = [
[255, 99, 132],
[54, 162, 235],
[240, 176, 26],
[153, 102, 255],
[75, 192, 192],
[255, 159, 64]
];
if (c >= default_colors.length) c = 0;
const [r, g, b] = default_colors[c++];
return `rgb(${r},${g},${b})`;
}
|
32fad88cf989fe13e31b63cb2ea82544e40b70b9 | 1,891 | ts | TypeScript | components/unique/NftUtils.ts | atharva3010/nft-gallery | f31ad5d32670186ffceca58321a798a276ca88a3 | [
"MIT"
] | 2 | 2022-01-29T20:14:00.000Z | 2022-02-21T14:39:07.000Z | components/unique/NftUtils.ts | atharva3010/nft-gallery | f31ad5d32670186ffceca58321a798a276ca88a3 | [
"MIT"
] | null | null | null | components/unique/NftUtils.ts | atharva3010/nft-gallery | f31ad5d32670186ffceca58321a798a276ca88a3 | [
"MIT"
] | 1 | 2022-02-21T14:43:32.000Z | 2022-02-21T14:43:32.000Z | type Id = string | number;
type Owner = { Id: string }
export enum NFTAction {
SEND='SEND',
CONSUME='CONSUME',
FREEZE='FREEZE',
DELEGATE='DELEGATE',
THAW='THAW',
REVOKE='REVOKE',
NONE='',
}
export const actionResolver: Record<NFTAction, [string, string]> = {
SEND: ['uniques','transfer'],
CONSUME: ['uniques','burn'],
DELEGATE: ['uniques','approveTransfer'],
FREEZE: ['uniques','freeze'],
THAW: ['uniques','thaw'],
REVOKE: ['uniques','cancelApproval'],
'': ['',''],
}
export const basicUpdateFunction = (name: string, index: number): string => `${name} #${index + 1}`
class NFTUtils {
static createCollection(id: Id, admin: string): [string, Owner] {
return [String(id), { Id: admin }]
}
static createNFT(classId: Id, id: Id, owner: string): [string, string, Owner] {
return [String(classId), String(id), { Id: owner }]
}
static getActionParams(selectedAction: NFTAction, classId: Id, id: Id, meta: string): Id[] {
switch (selectedAction) {
case NFTAction.SEND:
case NFTAction.CONSUME:
case NFTAction.DELEGATE:
case NFTAction.REVOKE:
return [classId, id, meta]
case NFTAction.FREEZE:
case NFTAction.THAW:
return [classId, id]
default:
throw new Error('Action not found')
}
}
static apiCall(selectedAction: NFTAction) {
return actionResolver[selectedAction] || new Error('Action not found')
}
static correctMeta(selectedAction: NFTAction, meta: string, currentOwner: string, delegate: string): string {
switch (selectedAction) {
case NFTAction.SEND:
case NFTAction.DELEGATE:
return meta
case NFTAction.CONSUME:
return currentOwner
case NFTAction.REVOKE:
return delegate
case NFTAction.FREEZE:
case NFTAction.THAW:
return ''
default:
throw new Error('Action not found')
}
}
}
export default NFTUtils
| 24.558442 | 111 | 0.652036 | 63 | 6 | 0 | 16 | 2 | 1 | 0 | 0 | 18 | 3 | 0 | 5 | 566 | 0.038869 | 0.003534 | 0.001767 | 0.0053 | 0 | 0 | 0.72 | 0.280165 | type Id = string | number;
type Owner = { Id }
export enum NFTAction {
SEND='SEND',
CONSUME='CONSUME',
FREEZE='FREEZE',
DELEGATE='DELEGATE',
THAW='THAW',
REVOKE='REVOKE',
NONE='',
}
export const actionResolver = {
SEND: ['uniques','transfer'],
CONSUME: ['uniques','burn'],
DELEGATE: ['uniques','approveTransfer'],
FREEZE: ['uniques','freeze'],
THAW: ['uniques','thaw'],
REVOKE: ['uniques','cancelApproval'],
'': ['',''],
}
export const basicUpdateFunction = (name, index) => `${name} #${index + 1}`
class NFTUtils {
static createCollection(id, admin) {
return [String(id), { Id: admin }]
}
static createNFT(classId, id, owner) {
return [String(classId), String(id), { Id: owner }]
}
static getActionParams(selectedAction, classId, id, meta) {
switch (selectedAction) {
case NFTAction.SEND:
case NFTAction.CONSUME:
case NFTAction.DELEGATE:
case NFTAction.REVOKE:
return [classId, id, meta]
case NFTAction.FREEZE:
case NFTAction.THAW:
return [classId, id]
default:
throw new Error('Action not found')
}
}
static apiCall(selectedAction) {
return actionResolver[selectedAction] || new Error('Action not found')
}
static correctMeta(selectedAction, meta, currentOwner, delegate) {
switch (selectedAction) {
case NFTAction.SEND:
case NFTAction.DELEGATE:
return meta
case NFTAction.CONSUME:
return currentOwner
case NFTAction.REVOKE:
return delegate
case NFTAction.FREEZE:
case NFTAction.THAW:
return ''
default:
throw new Error('Action not found')
}
}
}
export default NFTUtils
|
8c770ae92e7ff909e219b25309a1ff0b791e0a69 | 3,544 | ts | TypeScript | packages/autocomplete-core/src/utils/createCancelablePromise.ts | isabella232/autocomplete | df93858986d085881cb5446114550fd6aaa5d945 | [
"MIT"
] | null | null | null | packages/autocomplete-core/src/utils/createCancelablePromise.ts | isabella232/autocomplete | df93858986d085881cb5446114550fd6aaa5d945 | [
"MIT"
] | 1 | 2022-03-12T18:32:14.000Z | 2022-03-12T18:32:14.000Z | packages/autocomplete-core/src/utils/createCancelablePromise.ts | isabella232/autocomplete | df93858986d085881cb5446114550fd6aaa5d945 | [
"MIT"
] | null | null | null | type PromiseExecutor<TValue> = (
resolve: (value: TValue | PromiseLike<TValue>) => void,
reject: (reason?: any) => void
) => void;
type CancelablePromiseState = {
isCanceled: boolean;
onCancelList: Array<(...args: any[]) => any>;
};
function createInternalCancelablePromise<TValue>(
promise: Promise<TValue>,
initialState: CancelablePromiseState
): CancelablePromise<TValue> {
const state = initialState;
return {
then(onfulfilled, onrejected) {
return createInternalCancelablePromise(
promise.then(
createCallback(onfulfilled, state, promise),
createCallback(onrejected, state, promise)
),
state
);
},
catch(onrejected) {
return createInternalCancelablePromise(
promise.catch(createCallback(onrejected, state, promise)),
state
);
},
finally(onfinally) {
if (onfinally) {
state.onCancelList.push(onfinally);
}
return createInternalCancelablePromise<TValue>(
promise.finally(
createCallback(
onfinally &&
(() => {
state.onCancelList = [];
return onfinally();
}),
state,
promise
)
),
state
);
},
cancel() {
state.isCanceled = true;
const callbacks = state.onCancelList;
state.onCancelList = [];
callbacks.forEach((callback) => {
callback();
});
},
isCanceled() {
return state.isCanceled === true;
},
};
}
export type CancelablePromise<TValue> = {
then<TResultFulfilled = TValue, TResultRejected = never>(
onfulfilled?:
| ((
value: TValue
) =>
| TResultFulfilled
| PromiseLike<TResultFulfilled>
| CancelablePromise<TResultFulfilled>)
| undefined
| null,
onrejected?:
| ((
reason: any
) =>
| TResultRejected
| PromiseLike<TResultRejected>
| CancelablePromise<TResultRejected>)
| undefined
| null
): CancelablePromise<TResultFulfilled | TResultRejected>;
catch<TResult = never>(
onrejected?:
| ((
reason: any
) => TResult | PromiseLike<TResult> | CancelablePromise<TResult>)
| undefined
| null
): CancelablePromise<TValue | TResult>;
finally(
onfinally?: (() => void) | undefined | null
): CancelablePromise<TValue>;
cancel(): void;
isCanceled(): boolean;
};
export function createCancelablePromise<TValue>(
executor: PromiseExecutor<TValue>
): CancelablePromise<TValue> {
return createInternalCancelablePromise(
new Promise<TValue>((resolve, reject) => {
return executor(resolve, reject);
}),
{ isCanceled: false, onCancelList: [] }
);
}
createCancelablePromise.resolve = <TValue>(
value?: TValue | PromiseLike<TValue> | CancelablePromise<TValue>
) => cancelable(Promise.resolve(value));
createCancelablePromise.reject = (reason?: any) =>
cancelable(Promise.reject(reason));
export function cancelable<TValue>(promise: Promise<TValue>) {
return createInternalCancelablePromise(promise, {
isCanceled: false,
onCancelList: [],
});
}
function createCallback(
onResult: ((...args: any[]) => any) | null | undefined,
state: CancelablePromiseState,
fallback: any
) {
if (!onResult) {
return fallback;
}
return function callback(arg?: any) {
if (state.isCanceled) {
return arg;
}
return onResult(arg);
};
}
| 24.108844 | 73 | 0.606095 | 132 | 15 | 5 | 21 | 2 | 2 | 9 | 10 | 9 | 3 | 0 | 7.466667 | 860 | 0.04186 | 0.002326 | 0.002326 | 0.003488 | 0 | 0.222222 | 0.2 | 0.279742 | type PromiseExecutor<TValue> = (
resolve,
reject
) => void;
type CancelablePromiseState = {
isCanceled;
onCancelList;
};
/* Example usages of 'createInternalCancelablePromise' are shown below:
createInternalCancelablePromise(promise.then(createCallback(onfulfilled, state, promise), createCallback(onrejected, state, promise)), state);
createInternalCancelablePromise(promise.catch(createCallback(onrejected, state, promise)), state);
createInternalCancelablePromise<TValue>(promise.finally(createCallback(onfinally &&
(() => {
state.onCancelList = [];
return onfinally();
}), state, promise)), state);
createInternalCancelablePromise(new Promise<TValue>((resolve, reject) => {
return executor(resolve, reject);
}), { isCanceled: false, onCancelList: [] });
createInternalCancelablePromise(promise, {
isCanceled: false,
onCancelList: [],
});
*/
function createInternalCancelablePromise<TValue>(
promise,
initialState
) {
const state = initialState;
return {
then(onfulfilled, onrejected) {
return createInternalCancelablePromise(
promise.then(
createCallback(onfulfilled, state, promise),
createCallback(onrejected, state, promise)
),
state
);
},
catch(onrejected) {
return createInternalCancelablePromise(
promise.catch(createCallback(onrejected, state, promise)),
state
);
},
finally(onfinally) {
if (onfinally) {
state.onCancelList.push(onfinally);
}
return createInternalCancelablePromise<TValue>(
promise.finally(
createCallback(
onfinally &&
(() => {
state.onCancelList = [];
return onfinally();
}),
state,
promise
)
),
state
);
},
cancel() {
state.isCanceled = true;
const callbacks = state.onCancelList;
state.onCancelList = [];
callbacks.forEach((callback) => {
callback();
});
},
isCanceled() {
return state.isCanceled === true;
},
};
}
export type CancelablePromise<TValue> = {
then<TResultFulfilled = TValue, TResultRejected = never>(
onfulfilled?,
onrejected?
);
catch<TResult = never>(
onrejected?
);
finally(
onfinally?
);
cancel();
isCanceled();
};
export /* Example usages of 'createCancelablePromise' are shown below:
createCancelablePromise.resolve = <TValue>(value?) => cancelable(Promise.resolve(value));
createCancelablePromise.reject = (reason?) => cancelable(Promise.reject(reason));
*/
function createCancelablePromise<TValue>(
executor
) {
return createInternalCancelablePromise(
new Promise<TValue>((resolve, reject) => {
return executor(resolve, reject);
}),
{ isCanceled: false, onCancelList: [] }
);
}
createCancelablePromise.resolve = <TValue>(
value?
) => cancelable(Promise.resolve(value));
createCancelablePromise.reject = (reason?) =>
cancelable(Promise.reject(reason));
export /* Example usages of 'cancelable' are shown below:
cancelable(Promise.resolve(value));
cancelable(Promise.reject(reason));
*/
function cancelable<TValue>(promise) {
return createInternalCancelablePromise(promise, {
isCanceled: false,
onCancelList: [],
});
}
/* Example usages of 'createCallback' are shown below:
createInternalCancelablePromise(promise.then(createCallback(onfulfilled, state, promise), createCallback(onrejected, state, promise)), state);
createInternalCancelablePromise(promise.catch(createCallback(onrejected, state, promise)), state);
createInternalCancelablePromise<TValue>(promise.finally(createCallback(onfinally &&
(() => {
state.onCancelList = [];
return onfinally();
}), state, promise)), state);
*/
function createCallback(
onResult,
state,
fallback
) {
if (!onResult) {
return fallback;
}
return function callback(arg?) {
if (state.isCanceled) {
return arg;
}
return onResult(arg);
};
}
|
8cef405e043a12e662399c6b9188849c08f678ed | 3,176 | ts | TypeScript | src/utils/TimeFormatter.ts | JaelysonM/uzm-discord-bot-ts | 92209d334f6590a9354a889fa3212c8589977c4a | [
"MIT"
] | null | null | null | src/utils/TimeFormatter.ts | JaelysonM/uzm-discord-bot-ts | 92209d334f6590a9354a889fa3212c8589977c4a | [
"MIT"
] | null | null | null | src/utils/TimeFormatter.ts | JaelysonM/uzm-discord-bot-ts | 92209d334f6590a9354a889fa3212c8589977c4a | [
"MIT"
] | 2 | 2022-01-22T20:13:56.000Z | 2022-02-01T00:27:35.000Z | const MONTHS_ARRAY = ['janeiro', 'fevereiro', 'março', 'abril', 'maio', 'junho', 'julho', 'agosto', 'setembro', 'outubro', 'novembro', 'dezembro'];
const DAYS_ARRAY = ['domingo', 'segunda-feira', 'terça-feira', 'quarta-feira', 'quinta-feira', 'sexta-feira', 'sábado'];
function findMonth(date: any) {
return MONTHS_ARRAY[date.month];
}
function findDayOfWeek(date: any) {
return DAYS_ARRAY[date.day_of_week];
}
function destructorDate(milliseconds: number) {
const date = new Date(milliseconds);
return {
day: date.getDate(),
day_of_week: date.getDay(),
year: date.getFullYear(),
month: date.getMonth(),
minutes: date.getMinutes(),
hours: date.getHours(),
seconds: date.getSeconds(),
};
}
function zeroLeft(number: number) {
return number < 10 ? `0${number}` : number;
}
export default class TimeFormatter {
public static BR_TIMER = new TimeFormatter((params: any) => {
let ms = Math.ceil(params / 1000);
let sb = '';
if (Math.round(ms / 31449600) > 0) {
const years = Math.round((ms / 31449600));
sb += years + `${years == 1 ? ` ano` : ` anos `}`;
ms -= years * 31449600;
}
if (Math.round(ms / 2620800) > 0) {
const months = Math.round(ms / 2620800);
sb += months + `${months == 1 ? ` mês ` : ` meses `}`;
ms -= months * 2620800;
}
if (Math.round(ms / 604800) > 0) {
const weeks = Math.round(ms / 604800);
sb += weeks + `${weeks == 1 ? ` semana ` : ` semanas `}`;
ms -= weeks * 604800;
}
if (Math.round(ms / 86400) > 0) {
const days = Math.round(ms / 86400);
sb += days + `${days == 1 ? ` dia ` : ` dias `}`;
ms -= days * 86400;
}
if (Math.round(ms / 3600) > 0) {
const hours = Math.round(ms / 3600);
sb += hours + `${hours == 1 ? ` hora ` : ` horas `}`;
ms -= hours * 3600;
}
if (Math.round(ms / 60) > 0) {
const minutes = Math.round(ms / 60);
sb += minutes + `${minutes == 1 ? ` minuto ` : ` minutos `}`;
ms -= minutes * 60;
}
if (ms > 0) {
sb += ms + `${ms == 1 ? ` segundo ` : ` segundos `}`;
}
return sb.trim();
});
public static BR_DATE = new TimeFormatter((params: any) => {
return `${params.day} de ${findMonth(params)} de ${params.year}`;
})
public static VANILLA_TIME = new TimeFormatter((params: any) => {
return `${zeroLeft(params.hours)}:${zeroLeft(params.minutes)}`;
})
public static VANILLA_TIMER = new TimeFormatter((time: any) => {
const date = new Date(time);
return `${zeroLeft(date.getUTCHours())}:${zeroLeft(date.getUTCMinutes())}:${zeroLeft(date.getUTCSeconds())}`;
})
public static BR_COMPLETE_DATE = new TimeFormatter((params: any) => {
const date = destructorDate(params) as any;
return `${findDayOfWeek(date)}, ${TimeFormatter.BR_DATE.format(date)} às ${TimeFormatter.VANILLA_TIME.format(date)}`;
});
constructor(trigger: Function) {
this.trigger = trigger;
}
format(seconds: number): any {
return this.trigger(seconds);
}
private readonly trigger: Function;
} | 33.431579 | 148 | 0.56864 | 84 | 11 | 0 | 11 | 13 | 6 | 5 | 11 | 3 | 1 | 1 | 5.181818 | 1,073 | 0.020503 | 0.012116 | 0.005592 | 0.000932 | 0.000932 | 0.268293 | 0.073171 | 0.255869 | const MONTHS_ARRAY = ['janeiro', 'fevereiro', 'março', 'abril', 'maio', 'junho', 'julho', 'agosto', 'setembro', 'outubro', 'novembro', 'dezembro'];
const DAYS_ARRAY = ['domingo', 'segunda-feira', 'terça-feira', 'quarta-feira', 'quinta-feira', 'sexta-feira', 'sábado'];
/* Example usages of 'findMonth' are shown below:
findMonth(params);
*/
function findMonth(date) {
return MONTHS_ARRAY[date.month];
}
/* Example usages of 'findDayOfWeek' are shown below:
findDayOfWeek(date);
*/
function findDayOfWeek(date) {
return DAYS_ARRAY[date.day_of_week];
}
/* Example usages of 'destructorDate' are shown below:
destructorDate(params);
*/
function destructorDate(milliseconds) {
const date = new Date(milliseconds);
return {
day: date.getDate(),
day_of_week: date.getDay(),
year: date.getFullYear(),
month: date.getMonth(),
minutes: date.getMinutes(),
hours: date.getHours(),
seconds: date.getSeconds(),
};
}
/* Example usages of 'zeroLeft' are shown below:
zeroLeft(params.hours);
zeroLeft(params.minutes);
zeroLeft(date.getUTCHours());
zeroLeft(date.getUTCMinutes());
zeroLeft(date.getUTCSeconds());
*/
function zeroLeft(number) {
return number < 10 ? `0${number}` : number;
}
export default class TimeFormatter {
public static BR_TIMER = new TimeFormatter((params) => {
let ms = Math.ceil(params / 1000);
let sb = '';
if (Math.round(ms / 31449600) > 0) {
const years = Math.round((ms / 31449600));
sb += years + `${years == 1 ? ` ano` : ` anos `}`;
ms -= years * 31449600;
}
if (Math.round(ms / 2620800) > 0) {
const months = Math.round(ms / 2620800);
sb += months + `${months == 1 ? ` mês ` : ` meses `}`;
ms -= months * 2620800;
}
if (Math.round(ms / 604800) > 0) {
const weeks = Math.round(ms / 604800);
sb += weeks + `${weeks == 1 ? ` semana ` : ` semanas `}`;
ms -= weeks * 604800;
}
if (Math.round(ms / 86400) > 0) {
const days = Math.round(ms / 86400);
sb += days + `${days == 1 ? ` dia ` : ` dias `}`;
ms -= days * 86400;
}
if (Math.round(ms / 3600) > 0) {
const hours = Math.round(ms / 3600);
sb += hours + `${hours == 1 ? ` hora ` : ` horas `}`;
ms -= hours * 3600;
}
if (Math.round(ms / 60) > 0) {
const minutes = Math.round(ms / 60);
sb += minutes + `${minutes == 1 ? ` minuto ` : ` minutos `}`;
ms -= minutes * 60;
}
if (ms > 0) {
sb += ms + `${ms == 1 ? ` segundo ` : ` segundos `}`;
}
return sb.trim();
});
public static BR_DATE = new TimeFormatter((params) => {
return `${params.day} de ${findMonth(params)} de ${params.year}`;
})
public static VANILLA_TIME = new TimeFormatter((params) => {
return `${zeroLeft(params.hours)}:${zeroLeft(params.minutes)}`;
})
public static VANILLA_TIMER = new TimeFormatter((time) => {
const date = new Date(time);
return `${zeroLeft(date.getUTCHours())}:${zeroLeft(date.getUTCMinutes())}:${zeroLeft(date.getUTCSeconds())}`;
})
public static BR_COMPLETE_DATE = new TimeFormatter((params) => {
const date = destructorDate(params) as any;
return `${findDayOfWeek(date)}, ${TimeFormatter.BR_DATE.format(date)} às ${TimeFormatter.VANILLA_TIME.format(date)}`;
});
constructor(trigger) {
this.trigger = trigger;
}
format(seconds) {
return this.trigger(seconds);
}
private readonly trigger;
} |
b00acd43fbd124d40864800a8396d2a65d25ef69 | 1,149 | ts | TypeScript | src/service/auth.ts | dnd-side-project/dnd-6th-7-fe-worry-record-service | 4b26a37f27cfa2485eca81303c54215ab2e6d27a | [
"MIT"
] | 3 | 2022-01-18T15:13:48.000Z | 2022-02-16T16:50:10.000Z | src/service/auth.ts | dnd-side-project/dnd-6th-7-fe-worry-record-service | 4b26a37f27cfa2485eca81303c54215ab2e6d27a | [
"MIT"
] | 34 | 2022-01-24T03:33:55.000Z | 2022-03-17T16:41:23.000Z | src/service/auth.ts | dnd-side-project/dnd-6th-7-fe-worry-record-service | 4b26a37f27cfa2485eca81303c54215ab2e6d27a | [
"MIT"
] | 1 | 2022-01-14T12:25:56.000Z | 2022-01-14T12:25:56.000Z | export default class AuthService {
http: any;
constructor(http: any) {
this.http = http;
}
async signup(email: any, password: any) {
return this.http.fetch('/auth/signup', {
method: 'POST',
body: JSON.stringify({
email,
password,
}),
});
}
async login(token: any): Promise<any> {
const { oauthToken, deviceToken } = token;
return this.http.fetch('/auth/kakao', {
method: 'POST',
headers: {
oauthToken,
deviceToken,
},
});
}
async silentRefresh(refreshToken: any) {
return this.http.fetch('/auth/refresh', {
method: 'POST',
headers: {
oauthToken: refreshToken,
deviceToken: '',
},
});
}
async updateFCMToken({ userId, deviceToken }: any): Promise<any> {
return this.http.fetch(
`/auth/refresh?userId=${userId}&deviceToken=${deviceToken}`,
{
method: 'PUT',
},
);
}
async me() {
return this.http.fetch('/auth/me', {
method: 'GET',
});
}
async logout() {
return this.http.fetch('/auth/logout', {
method: 'POST',
});
}
}
| 19.15 | 68 | 0.536118 | 52 | 7 | 0 | 6 | 1 | 1 | 0 | 9 | 0 | 1 | 0 | 5 | 310 | 0.041935 | 0.003226 | 0.003226 | 0.003226 | 0 | 0.6 | 0 | 0.27437 | export default class AuthService {
http;
constructor(http) {
this.http = http;
}
async signup(email, password) {
return this.http.fetch('/auth/signup', {
method: 'POST',
body: JSON.stringify({
email,
password,
}),
});
}
async login(token) {
const { oauthToken, deviceToken } = token;
return this.http.fetch('/auth/kakao', {
method: 'POST',
headers: {
oauthToken,
deviceToken,
},
});
}
async silentRefresh(refreshToken) {
return this.http.fetch('/auth/refresh', {
method: 'POST',
headers: {
oauthToken: refreshToken,
deviceToken: '',
},
});
}
async updateFCMToken({ userId, deviceToken }) {
return this.http.fetch(
`/auth/refresh?userId=${userId}&deviceToken=${deviceToken}`,
{
method: 'PUT',
},
);
}
async me() {
return this.http.fetch('/auth/me', {
method: 'GET',
});
}
async logout() {
return this.http.fetch('/auth/logout', {
method: 'POST',
});
}
}
|
b0ac0ff96d4f4200f2737600684a94a0cd97d2f2 | 2,519 | ts | TypeScript | src/commands/match/types.ts | UkraineNow/sheets-matcher | 9986c03430a2439be9e6be1b45c117141cb3a431 | [
"MIT"
] | 2 | 2022-03-02T18:49:23.000Z | 2022-03-02T18:49:24.000Z | src/commands/match/types.ts | tchief/sheets-matcher | 9986c03430a2439be9e6be1b45c117141cb3a431 | [
"MIT"
] | null | null | null | src/commands/match/types.ts | tchief/sheets-matcher | 9986c03430a2439be9e6be1b45c117141cb3a431 | [
"MIT"
] | null | null | null | export interface Match {
requestId: number;
proposalIds: number[];
}
export const proposalIdsToString = (match: Match) => match.proposalIds.join(",");
export const matchesToString = (matches: Match[]) => matches.map((m) => `${m.requestId}: ${proposalIdsToString(m)}`).join("\n");
export interface Proposal {
rowNumber: number;
status: string;
name: string;
city: string;
country: string;
languages: string;
contact: string;
social: string;
phone: string;
seats: string;
when_from: string;
when_to: string;
pets: string;
transfer: string;
travel_distance: string;
refugee: string;
comments: string;
suggestions: string;
}
export const mapRowToProposal = (row: any): Proposal => ({
rowNumber: row.rowNumber,
status: row["Status"],
name: row["Full name"],
city: row["City where you can host"],
country: row["Country where you can host"],
languages: row["What languages you speak?"],
contact: row["How to contact you?"],
social: row["Link to your social media"],
phone: row["Phone number"],
seats: row["Number of people you can host?"],
when_from: row["What's a start date you can host from?"],
when_to: row["Till what date you can host?"],
pets: row["Available for pets hosting?"],
transfer: row["Do you have a car to help with a transfer?"],
travel_distance: row["How far you're ready to travel to pick people up?"],
refugee: row["Refugee"],
comments: row["Comments"],
suggestions: row["Suggestions"],
});
export interface Request {
rowNumber: number;
status: string;
email: string;
name: string;
from: string;
city: string;
country: string;
languages: string;
contact: string;
seats: string;
when_from: string;
pets: string;
kids: string;
host: string;
comments: string;
suggestions: string;
}
export const mapRowToRequest = (row: any): Request => ({
rowNumber: row.rowNumber,
status: row["статус заявки"],
email: row["Пошта"],
name: row["Ім'я"],
from: row["Ваша теперішня локація"],
city: row["В яке місто прямуєте?"],
country: row["В яку країну прямуєте?"],
languages: row["Якими мовами спілкуєтесь?"],
contact: row["Контактний номер"],
seats: row["Скільки людей"],
when_from: row["Коли виїзд"],
pets: row["Чи є тварини?"],
kids: row["Чи є діти?"],
host: row["Хост"],
comments: row["Комментар"],
suggestions: row["Suggestions"],
});
| 28.625 | 128 | 0.634379 | 82 | 5 | 0 | 5 | 4 | 36 | 1 | 2 | 36 | 3 | 0 | 8.2 | 765 | 0.013072 | 0.005229 | 0.047059 | 0.003922 | 0 | 0.04 | 0.72 | 0.222724 | export interface Match {
requestId;
proposalIds;
}
export /* Example usages of 'proposalIdsToString' are shown below:
proposalIdsToString(m);
*/
const proposalIdsToString = (match) => match.proposalIds.join(",");
export const matchesToString = (matches) => matches.map((m) => `${m.requestId}: ${proposalIdsToString(m)}`).join("\n");
export interface Proposal {
rowNumber;
status;
name;
city;
country;
languages;
contact;
social;
phone;
seats;
when_from;
when_to;
pets;
transfer;
travel_distance;
refugee;
comments;
suggestions;
}
export const mapRowToProposal = (row) => ({
rowNumber: row.rowNumber,
status: row["Status"],
name: row["Full name"],
city: row["City where you can host"],
country: row["Country where you can host"],
languages: row["What languages you speak?"],
contact: row["How to contact you?"],
social: row["Link to your social media"],
phone: row["Phone number"],
seats: row["Number of people you can host?"],
when_from: row["What's a start date you can host from?"],
when_to: row["Till what date you can host?"],
pets: row["Available for pets hosting?"],
transfer: row["Do you have a car to help with a transfer?"],
travel_distance: row["How far you're ready to travel to pick people up?"],
refugee: row["Refugee"],
comments: row["Comments"],
suggestions: row["Suggestions"],
});
export interface Request {
rowNumber;
status;
email;
name;
from;
city;
country;
languages;
contact;
seats;
when_from;
pets;
kids;
host;
comments;
suggestions;
}
export const mapRowToRequest = (row) => ({
rowNumber: row.rowNumber,
status: row["статус заявки"],
email: row["Пошта"],
name: row["Ім'я"],
from: row["Ваша теперішня локація"],
city: row["В яке місто прямуєте?"],
country: row["В яку країну прямуєте?"],
languages: row["Якими мовами спілкуєтесь?"],
contact: row["Контактний номер"],
seats: row["Скільки людей"],
when_from: row["Коли виїзд"],
pets: row["Чи є тварини?"],
kids: row["Чи є діти?"],
host: row["Хост"],
comments: row["Комментар"],
suggestions: row["Suggestions"],
});
|
b0e0669ce5dcfd4592976d1d0e1c92f7fbb44033 | 46,667 | ts | TypeScript | examples/contracts/eosio/typescript/generated/eosio/types.ts | maxifom/eos-abigen-go | 4b62444c995b5fac1d6f6df65b417c173e9e110d | [
"MIT"
] | 2 | 2022-03-21T08:42:00.000Z | 2022-03-27T13:57:33.000Z | examples/contracts/eosio/typescript/generated/eosio/types.ts | maxifom/eos-abigen-go | 4b62444c995b5fac1d6f6df65b417c173e9e110d | [
"MIT"
] | 5 | 2022-03-29T17:57:17.000Z | 2022-03-29T19:11:25.000Z | examples/contracts/eosio/typescript/generated/eosio/types.ts | maxifom/eos-abigen | 4b62444c995b5fac1d6f6df65b417c173e9e110d | [
"MIT"
] | null | null | null | // Generated by eos-abigen version master
export const CONTRACT_NAME = "eosio";
export type Authorization = {
actor: string;
permission: string;
}
export type Action = {
account: string;
name: string;
authorization: Authorization[];
data: object;
}
export type GetTableRowsParams = Partial<{
code: string
scope: string
bounds: string
lower_bound: string
upper_bound: string
index_position: number
key_type: string
limit: number
reverse: boolean
show_payer: boolean
}>
export class Symbol {
readonly raw: string;
readonly precision: number;
readonly symbol_code: string;
public constructor(raw: string) {
this.raw = raw;
const [precision, symbol_code] = raw.split(",", 2)
this.precision = Number.parseInt(precision);
this.symbol_code = symbol_code;
}
}
export class Asset {
readonly raw: string;
readonly raw_quantity: string;
readonly quantity: number;
readonly precision: number;
readonly symbol_code: string;
public constructor(raw: string) {
this.raw = raw;
const [quantity, symbol_code] = raw.split(" ", 2);
this.raw_quantity = quantity;
this.precision = 0;
const splitted = quantity.split(".");
if (splitted.length > 1) {
this.precision = splitted[1].length;
}
this.quantity = Number.parseFloat(quantity);
this.symbol_code = symbol_code;
}
}
export type ExtendedAssetType = {
quantity: string
contract: string
}
export class ExtendedAsset {
readonly asset: Asset;
readonly contract: string;
public constructor(raw: ExtendedAssetType) {
this.asset = new Asset(raw.quantity);
this.contract = raw.contract;
}
}
export type AbiHash = {
owner: string
hash: string
};
export type AbiHashInterm = {
owner: string
hash: string
};
export function mapAbiHash(r: AbiHashInterm): AbiHash {
return {
owner: r.owner,
hash: r.hash,
}
}
export type Activate = {
feature_digest: string
};
export type ActivateInterm = {
feature_digest: string
};
export function mapActivate(r: ActivateInterm): Activate {
return {
feature_digest: r.feature_digest,
}
}
export type Authority = {
threshold: number
keys: KeyWeight[]
accounts: PermissionLevelWeight[]
waits: WaitWeight[]
};
export type AuthorityInterm = {
threshold: number
keys: KeyWeightInterm[]
accounts: PermissionLevelWeightInterm[]
waits: WaitWeightInterm[]
};
export function mapAuthority(r: AuthorityInterm): Authority {
return {
threshold: r.threshold,
keys: r.keys.map(n => mapKeyWeight(n)),
accounts: r.accounts.map(n => mapPermissionLevelWeight(n)),
waits: r.waits.map(n => mapWaitWeight(n)),
}
}
export type BidRefund = {
bidder: string
amount: Asset
};
export type BidRefundInterm = {
bidder: string
amount: string
};
export function mapBidRefund(r: BidRefundInterm): BidRefund {
return {
bidder: r.bidder,
amount: new Asset(r.amount),
}
}
export type Bidname = {
bidder: string
newname: string
bid: Asset
};
export type BidnameInterm = {
bidder: string
newname: string
bid: string
};
export function mapBidname(r: BidnameInterm): Bidname {
return {
bidder: r.bidder,
newname: r.newname,
bid: new Asset(r.bid),
}
}
export type Bidrefund = {
bidder: string
newname: string
};
export type BidrefundInterm = {
bidder: string
newname: string
};
export function mapBidrefund(r: BidrefundInterm): Bidrefund {
return {
bidder: r.bidder,
newname: r.newname,
}
}
export type BlockHeader = {
timestamp: number
producer: string
confirmed: number
previous: string
transaction_mroot: string
action_mroot: string
schedule_version: number
new_producers: unknown
};
export type BlockHeaderInterm = {
timestamp: number
producer: string
confirmed: number
previous: string
transaction_mroot: string
action_mroot: string
schedule_version: number
new_producers: unknown
};
export function mapBlockHeader(r: BlockHeaderInterm): BlockHeader {
return {
timestamp: r.timestamp,
producer: r.producer,
confirmed: r.confirmed,
previous: r.previous,
transaction_mroot: r.transaction_mroot,
action_mroot: r.action_mroot,
schedule_version: r.schedule_version,
new_producers: r.new_producers,
}
}
export type BlockSigningAuthorityV0 = {
threshold: number
keys: KeyWeight[]
};
export type BlockSigningAuthorityV0Interm = {
threshold: number
keys: KeyWeightInterm[]
};
export function mapBlockSigningAuthorityV0(r: BlockSigningAuthorityV0Interm): BlockSigningAuthorityV0 {
return {
threshold: r.threshold,
keys: r.keys.map(n => mapKeyWeight(n)),
}
}
export type BlockchainParameters = {
max_block_net_usage: string
target_block_net_usage_pct: number
max_transaction_net_usage: number
base_per_transaction_net_usage: number
net_usage_leeway: number
context_free_discount_net_usage_num: number
context_free_discount_net_usage_den: number
max_block_cpu_usage: number
target_block_cpu_usage_pct: number
max_transaction_cpu_usage: number
min_transaction_cpu_usage: number
max_transaction_lifetime: number
deferred_trx_expiration_window: number
max_transaction_delay: number
max_inline_action_size: number
max_inline_action_depth: number
max_authority_depth: number
};
export type BlockchainParametersInterm = {
max_block_net_usage: number
target_block_net_usage_pct: number
max_transaction_net_usage: number
base_per_transaction_net_usage: number
net_usage_leeway: number
context_free_discount_net_usage_num: number
context_free_discount_net_usage_den: number
max_block_cpu_usage: number
target_block_cpu_usage_pct: number
max_transaction_cpu_usage: number
min_transaction_cpu_usage: number
max_transaction_lifetime: number
deferred_trx_expiration_window: number
max_transaction_delay: number
max_inline_action_size: number
max_inline_action_depth: number
max_authority_depth: number
};
export function mapBlockchainParameters(r: BlockchainParametersInterm): BlockchainParameters {
return {
max_block_net_usage: r.max_block_net_usage.toString(),
target_block_net_usage_pct: r.target_block_net_usage_pct,
max_transaction_net_usage: r.max_transaction_net_usage,
base_per_transaction_net_usage: r.base_per_transaction_net_usage,
net_usage_leeway: r.net_usage_leeway,
context_free_discount_net_usage_num: r.context_free_discount_net_usage_num,
context_free_discount_net_usage_den: r.context_free_discount_net_usage_den,
max_block_cpu_usage: r.max_block_cpu_usage,
target_block_cpu_usage_pct: r.target_block_cpu_usage_pct,
max_transaction_cpu_usage: r.max_transaction_cpu_usage,
min_transaction_cpu_usage: r.min_transaction_cpu_usage,
max_transaction_lifetime: r.max_transaction_lifetime,
deferred_trx_expiration_window: r.deferred_trx_expiration_window,
max_transaction_delay: r.max_transaction_delay,
max_inline_action_size: r.max_inline_action_size,
max_inline_action_depth: r.max_inline_action_depth,
max_authority_depth: r.max_authority_depth,
}
}
export type Buyram = {
payer: string
receiver: string
quant: Asset
};
export type BuyramInterm = {
payer: string
receiver: string
quant: string
};
export function mapBuyram(r: BuyramInterm): Buyram {
return {
payer: r.payer,
receiver: r.receiver,
quant: new Asset(r.quant),
}
}
export type Buyrambytes = {
payer: string
receiver: string
bytes: number
};
export type BuyrambytesInterm = {
payer: string
receiver: string
bytes: number
};
export function mapBuyrambytes(r: BuyrambytesInterm): Buyrambytes {
return {
payer: r.payer,
receiver: r.receiver,
bytes: r.bytes,
}
}
export type Buyrex = {
from: string
amount: Asset
};
export type BuyrexInterm = {
from: string
amount: string
};
export function mapBuyrex(r: BuyrexInterm): Buyrex {
return {
from: r.from,
amount: new Asset(r.amount),
}
}
export type Canceldelay = {
canceling_auth: PermissionLevel
trx_id: string
};
export type CanceldelayInterm = {
canceling_auth: PermissionLevelInterm
trx_id: string
};
export function mapCanceldelay(r: CanceldelayInterm): Canceldelay {
return {
canceling_auth: mapPermissionLevel(r.canceling_auth),
trx_id: r.trx_id,
}
}
export type Cfgpowerup = {
args: PowerupConfig
};
export type CfgpowerupInterm = {
args: PowerupConfigInterm
};
export function mapCfgpowerup(r: CfgpowerupInterm): Cfgpowerup {
return {
args: mapPowerupConfig(r.args),
}
}
export type Claimrewards = {
owner: string
};
export type ClaimrewardsInterm = {
owner: string
};
export function mapClaimrewards(r: ClaimrewardsInterm): Claimrewards {
return {
owner: r.owner,
}
}
export type Closerex = {
owner: string
};
export type CloserexInterm = {
owner: string
};
export function mapCloserex(r: CloserexInterm): Closerex {
return {
owner: r.owner,
}
}
export type Cnclrexorder = {
owner: string
};
export type CnclrexorderInterm = {
owner: string
};
export function mapCnclrexorder(r: CnclrexorderInterm): Cnclrexorder {
return {
owner: r.owner,
}
}
export type Connector = {
balance: Asset
weight: number
};
export type ConnectorInterm = {
balance: string
weight: string
};
export function mapConnector(r: ConnectorInterm): Connector {
return {
balance: new Asset(r.balance),
weight: Number.parseFloat(r.weight),
}
}
export type Consolidate = {
owner: string
};
export type ConsolidateInterm = {
owner: string
};
export function mapConsolidate(r: ConsolidateInterm): Consolidate {
return {
owner: r.owner,
}
}
export type Defcpuloan = {
from: string
loan_num: string
amount: Asset
};
export type DefcpuloanInterm = {
from: string
loan_num: number
amount: string
};
export function mapDefcpuloan(r: DefcpuloanInterm): Defcpuloan {
return {
from: r.from,
loan_num: r.loan_num.toString(),
amount: new Asset(r.amount),
}
}
export type Defnetloan = {
from: string
loan_num: string
amount: Asset
};
export type DefnetloanInterm = {
from: string
loan_num: number
amount: string
};
export function mapDefnetloan(r: DefnetloanInterm): Defnetloan {
return {
from: r.from,
loan_num: r.loan_num.toString(),
amount: new Asset(r.amount),
}
}
export type Delegatebw = {
from: string
receiver: string
stake_net_quantity: Asset
stake_cpu_quantity: Asset
transfer: boolean
};
export type DelegatebwInterm = {
from: string
receiver: string
stake_net_quantity: string
stake_cpu_quantity: string
transfer: number
};
export function mapDelegatebw(r: DelegatebwInterm): Delegatebw {
return {
from: r.from,
receiver: r.receiver,
stake_net_quantity: new Asset(r.stake_net_quantity),
stake_cpu_quantity: new Asset(r.stake_cpu_quantity),
transfer: !!(r.transfer),
}
}
export type DelegatedBandwidth = {
from: string
to: string
net_weight: Asset
cpu_weight: Asset
};
export type DelegatedBandwidthInterm = {
from: string
to: string
net_weight: string
cpu_weight: string
};
export function mapDelegatedBandwidth(r: DelegatedBandwidthInterm): DelegatedBandwidth {
return {
from: r.from,
to: r.to,
net_weight: new Asset(r.net_weight),
cpu_weight: new Asset(r.cpu_weight),
}
}
export type Deleteauth = {
account: string
permission: string
};
export type DeleteauthInterm = {
account: string
permission: string
};
export function mapDeleteauth(r: DeleteauthInterm): Deleteauth {
return {
account: r.account,
permission: r.permission,
}
}
export type Deposit = {
owner: string
amount: Asset
};
export type DepositInterm = {
owner: string
amount: string
};
export function mapDeposit(r: DepositInterm): Deposit {
return {
owner: r.owner,
amount: new Asset(r.amount),
}
}
export type EosioGlobalState = {
max_ram_size: string
total_ram_bytes_reserved: string
total_ram_stake: string
last_producer_schedule_update: string
last_pervote_bucket_fill: string
pervote_bucket: string
perblock_bucket: string
total_unpaid_blocks: number
total_activated_stake: string
thresh_activated_stake_time: string
last_producer_schedule_size: number
total_producer_vote_weight: number
last_name_close: string
};
export type EosioGlobalStateInterm = {
max_ram_size: number
total_ram_bytes_reserved: number
total_ram_stake: number
last_producer_schedule_update: string
last_pervote_bucket_fill: string
pervote_bucket: number
perblock_bucket: number
total_unpaid_blocks: number
total_activated_stake: number
thresh_activated_stake_time: string
last_producer_schedule_size: number
total_producer_vote_weight: string
last_name_close: string
};
export function mapEosioGlobalState(r: EosioGlobalStateInterm): EosioGlobalState {
return {
max_ram_size: r.max_ram_size.toString(),
total_ram_bytes_reserved: r.total_ram_bytes_reserved.toString(),
total_ram_stake: r.total_ram_stake.toString(),
last_producer_schedule_update: r.last_producer_schedule_update,
last_pervote_bucket_fill: r.last_pervote_bucket_fill,
pervote_bucket: r.pervote_bucket.toString(),
perblock_bucket: r.perblock_bucket.toString(),
total_unpaid_blocks: r.total_unpaid_blocks,
total_activated_stake: r.total_activated_stake.toString(),
thresh_activated_stake_time: r.thresh_activated_stake_time,
last_producer_schedule_size: r.last_producer_schedule_size,
total_producer_vote_weight: Number.parseFloat(r.total_producer_vote_weight),
last_name_close: r.last_name_close,
}
}
export type EosioGlobalState2 = {
new_ram_per_block: number
last_ram_increase: string
last_block_num: string
total_producer_votepay_share: number
revision: number
};
export type EosioGlobalState2Interm = {
new_ram_per_block: number
last_ram_increase: string
last_block_num: string
total_producer_votepay_share: string
revision: number
};
export function mapEosioGlobalState2(r: EosioGlobalState2Interm): EosioGlobalState2 {
return {
new_ram_per_block: r.new_ram_per_block,
last_ram_increase: r.last_ram_increase,
last_block_num: r.last_block_num,
total_producer_votepay_share: Number.parseFloat(r.total_producer_votepay_share),
revision: r.revision,
}
}
export type EosioGlobalState3 = {
last_vpay_state_update: string
total_vpay_share_change_rate: number
};
export type EosioGlobalState3Interm = {
last_vpay_state_update: string
total_vpay_share_change_rate: string
};
export function mapEosioGlobalState3(r: EosioGlobalState3Interm): EosioGlobalState3 {
return {
last_vpay_state_update: r.last_vpay_state_update,
total_vpay_share_change_rate: Number.parseFloat(r.total_vpay_share_change_rate),
}
}
export type EosioGlobalState4 = {
continuous_rate: number
inflation_pay_factor: string
votepay_factor: string
};
export type EosioGlobalState4Interm = {
continuous_rate: string
inflation_pay_factor: number
votepay_factor: number
};
export function mapEosioGlobalState4(r: EosioGlobalState4Interm): EosioGlobalState4 {
return {
continuous_rate: Number.parseFloat(r.continuous_rate),
inflation_pay_factor: r.inflation_pay_factor.toString(),
votepay_factor: r.votepay_factor.toString(),
}
}
export type ExchangeState = {
supply: Asset
base: Connector
quote: Connector
};
export type ExchangeStateInterm = {
supply: string
base: ConnectorInterm
quote: ConnectorInterm
};
export function mapExchangeState(r: ExchangeStateInterm): ExchangeState {
return {
supply: new Asset(r.supply),
base: mapConnector(r.base),
quote: mapConnector(r.quote),
}
}
export type Fundcpuloan = {
from: string
loan_num: string
payment: Asset
};
export type FundcpuloanInterm = {
from: string
loan_num: number
payment: string
};
export function mapFundcpuloan(r: FundcpuloanInterm): Fundcpuloan {
return {
from: r.from,
loan_num: r.loan_num.toString(),
payment: new Asset(r.payment),
}
}
export type Fundnetloan = {
from: string
loan_num: string
payment: Asset
};
export type FundnetloanInterm = {
from: string
loan_num: number
payment: string
};
export function mapFundnetloan(r: FundnetloanInterm): Fundnetloan {
return {
from: r.from,
loan_num: r.loan_num.toString(),
payment: new Asset(r.payment),
}
}
export type Init = {
version: number
core: Symbol
};
export type InitInterm = {
version: number
core: string
};
export function mapInit(r: InitInterm): Init {
return {
version: r.version,
core: new Symbol(r.core),
}
}
export type KeyWeight = {
key: string
weight: number
};
export type KeyWeightInterm = {
key: string
weight: number
};
export function mapKeyWeight(r: KeyWeightInterm): KeyWeight {
return {
key: r.key,
weight: r.weight,
}
}
export type Linkauth = {
account: string
code: string
type: string
requirement: string
};
export type LinkauthInterm = {
account: string
code: string
type: string
requirement: string
};
export function mapLinkauth(r: LinkauthInterm): Linkauth {
return {
account: r.account,
code: r.code,
type: r.type,
requirement: r.requirement,
}
}
export type Mvfrsavings = {
owner: string
rex: Asset
};
export type MvfrsavingsInterm = {
owner: string
rex: string
};
export function mapMvfrsavings(r: MvfrsavingsInterm): Mvfrsavings {
return {
owner: r.owner,
rex: new Asset(r.rex),
}
}
export type Mvtosavings = {
owner: string
rex: Asset
};
export type MvtosavingsInterm = {
owner: string
rex: string
};
export function mapMvtosavings(r: MvtosavingsInterm): Mvtosavings {
return {
owner: r.owner,
rex: new Asset(r.rex),
}
}
export type NameBid = {
newname: string
high_bidder: string
high_bid: string
last_bid_time: string
};
export type NameBidInterm = {
newname: string
high_bidder: string
high_bid: number
last_bid_time: string
};
export function mapNameBid(r: NameBidInterm): NameBid {
return {
newname: r.newname,
high_bidder: r.high_bidder,
high_bid: r.high_bid.toString(),
last_bid_time: r.last_bid_time,
}
}
export type Newaccount = {
creator: string
name: string
owner: Authority
active: Authority
};
export type NewaccountInterm = {
creator: string
name: string
owner: AuthorityInterm
active: AuthorityInterm
};
export function mapNewaccount(r: NewaccountInterm): Newaccount {
return {
creator: r.creator,
name: r.name,
owner: mapAuthority(r.owner),
active: mapAuthority(r.active),
}
}
export type Onblock = {
header: BlockHeader
};
export type OnblockInterm = {
header: BlockHeaderInterm
};
export function mapOnblock(r: OnblockInterm): Onblock {
return {
header: mapBlockHeader(r.header),
}
}
export type Onerror = {
sender_id: string
sent_trx: string
};
export type OnerrorInterm = {
sender_id: string
sent_trx: string
};
export function mapOnerror(r: OnerrorInterm): Onerror {
return {
sender_id: r.sender_id,
sent_trx: r.sent_trx,
}
}
export type PairTimePointSecInt64 = {
key: string
value: string
};
export type PairTimePointSecInt64Interm = {
key: string
value: number
};
export function mapPairTimePointSecInt64(r: PairTimePointSecInt64Interm): PairTimePointSecInt64 {
return {
key: r.key,
value: r.value.toString(),
}
}
export type PermissionLevel = {
actor: string
permission: string
};
export type PermissionLevelInterm = {
actor: string
permission: string
};
export function mapPermissionLevel(r: PermissionLevelInterm): PermissionLevel {
return {
actor: r.actor,
permission: r.permission,
}
}
export type PermissionLevelWeight = {
permission: PermissionLevel
weight: number
};
export type PermissionLevelWeightInterm = {
permission: PermissionLevelInterm
weight: number
};
export function mapPermissionLevelWeight(r: PermissionLevelWeightInterm): PermissionLevelWeight {
return {
permission: mapPermissionLevel(r.permission),
weight: r.weight,
}
}
export type Powerup = {
payer: string
receiver: string
days: number
net_frac: string
cpu_frac: string
max_payment: Asset
};
export type PowerupInterm = {
payer: string
receiver: string
days: number
net_frac: number
cpu_frac: number
max_payment: string
};
export function mapPowerup(r: PowerupInterm): Powerup {
return {
payer: r.payer,
receiver: r.receiver,
days: r.days,
net_frac: r.net_frac.toString(),
cpu_frac: r.cpu_frac.toString(),
max_payment: new Asset(r.max_payment),
}
}
export type PowerupConfig = {
net: PowerupConfigResource
cpu: PowerupConfigResource
powerup_days: unknown
min_powerup_fee: unknown
};
export type PowerupConfigInterm = {
net: PowerupConfigResourceInterm
cpu: PowerupConfigResourceInterm
powerup_days: unknown
min_powerup_fee: unknown
};
export function mapPowerupConfig(r: PowerupConfigInterm): PowerupConfig {
return {
net: mapPowerupConfigResource(r.net),
cpu: mapPowerupConfigResource(r.cpu),
powerup_days: r.powerup_days,
min_powerup_fee: r.min_powerup_fee,
}
}
export type PowerupConfigResource = {
current_weight_ratio: unknown
target_weight_ratio: unknown
assumed_stake_weight: unknown
target_timestamp: unknown
exponent: unknown
decay_secs: unknown
min_price: unknown
max_price: unknown
};
export type PowerupConfigResourceInterm = {
current_weight_ratio: unknown
target_weight_ratio: unknown
assumed_stake_weight: unknown
target_timestamp: unknown
exponent: unknown
decay_secs: unknown
min_price: unknown
max_price: unknown
};
export function mapPowerupConfigResource(r: PowerupConfigResourceInterm): PowerupConfigResource {
return {
current_weight_ratio: r.current_weight_ratio,
target_weight_ratio: r.target_weight_ratio,
assumed_stake_weight: r.assumed_stake_weight,
target_timestamp: r.target_timestamp,
exponent: r.exponent,
decay_secs: r.decay_secs,
min_price: r.min_price,
max_price: r.max_price,
}
}
export type PowerupOrder = {
version: number
id: string
owner: string
net_weight: string
cpu_weight: string
expires: string
};
export type PowerupOrderInterm = {
version: number
id: number
owner: string
net_weight: number
cpu_weight: number
expires: string
};
export function mapPowerupOrder(r: PowerupOrderInterm): PowerupOrder {
return {
version: r.version,
id: r.id.toString(),
owner: r.owner,
net_weight: r.net_weight.toString(),
cpu_weight: r.cpu_weight.toString(),
expires: r.expires,
}
}
export type PowerupState = {
version: number
net: PowerupStateResource
cpu: PowerupStateResource
powerup_days: number
min_powerup_fee: Asset
};
export type PowerupStateInterm = {
version: number
net: PowerupStateResourceInterm
cpu: PowerupStateResourceInterm
powerup_days: number
min_powerup_fee: string
};
export function mapPowerupState(r: PowerupStateInterm): PowerupState {
return {
version: r.version,
net: mapPowerupStateResource(r.net),
cpu: mapPowerupStateResource(r.cpu),
powerup_days: r.powerup_days,
min_powerup_fee: new Asset(r.min_powerup_fee),
}
}
export type PowerupStateResource = {
version: number
weight: string
weight_ratio: string
assumed_stake_weight: string
initial_weight_ratio: string
target_weight_ratio: string
initial_timestamp: string
target_timestamp: string
exponent: number
decay_secs: number
min_price: Asset
max_price: Asset
utilization: string
adjusted_utilization: string
utilization_timestamp: string
};
export type PowerupStateResourceInterm = {
version: number
weight: number
weight_ratio: number
assumed_stake_weight: number
initial_weight_ratio: number
target_weight_ratio: number
initial_timestamp: string
target_timestamp: string
exponent: string
decay_secs: number
min_price: string
max_price: string
utilization: number
adjusted_utilization: number
utilization_timestamp: string
};
export function mapPowerupStateResource(r: PowerupStateResourceInterm): PowerupStateResource {
return {
version: r.version,
weight: r.weight.toString(),
weight_ratio: r.weight_ratio.toString(),
assumed_stake_weight: r.assumed_stake_weight.toString(),
initial_weight_ratio: r.initial_weight_ratio.toString(),
target_weight_ratio: r.target_weight_ratio.toString(),
initial_timestamp: r.initial_timestamp,
target_timestamp: r.target_timestamp,
exponent: Number.parseFloat(r.exponent),
decay_secs: r.decay_secs,
min_price: new Asset(r.min_price),
max_price: new Asset(r.max_price),
utilization: r.utilization.toString(),
adjusted_utilization: r.adjusted_utilization.toString(),
utilization_timestamp: r.utilization_timestamp,
}
}
export type Powerupexec = {
user: string
max: number
};
export type PowerupexecInterm = {
user: string
max: number
};
export function mapPowerupexec(r: PowerupexecInterm): Powerupexec {
return {
user: r.user,
max: r.max,
}
}
export type ProducerInfo = {
owner: string
total_votes: number
producer_key: string
is_active: boolean
url: string
unpaid_blocks: number
last_claim_time: string
location: number
producer_authority: unknown
};
export type ProducerInfoInterm = {
owner: string
total_votes: string
producer_key: string
is_active: number
url: string
unpaid_blocks: number
last_claim_time: string
location: number
producer_authority: unknown
};
export function mapProducerInfo(r: ProducerInfoInterm): ProducerInfo {
return {
owner: r.owner,
total_votes: Number.parseFloat(r.total_votes),
producer_key: r.producer_key,
is_active: !!(r.is_active),
url: r.url,
unpaid_blocks: r.unpaid_blocks,
last_claim_time: r.last_claim_time,
location: r.location,
producer_authority: r.producer_authority,
}
}
export type ProducerInfo2 = {
owner: string
votepay_share: number
last_votepay_share_update: string
};
export type ProducerInfo2Interm = {
owner: string
votepay_share: string
last_votepay_share_update: string
};
export function mapProducerInfo2(r: ProducerInfo2Interm): ProducerInfo2 {
return {
owner: r.owner,
votepay_share: Number.parseFloat(r.votepay_share),
last_votepay_share_update: r.last_votepay_share_update,
}
}
export type ProducerKey = {
producer_name: string
block_signing_key: string
};
export type ProducerKeyInterm = {
producer_name: string
block_signing_key: string
};
export function mapProducerKey(r: ProducerKeyInterm): ProducerKey {
return {
producer_name: r.producer_name,
block_signing_key: r.block_signing_key,
}
}
export type ProducerSchedule = {
version: number
producers: ProducerKey[]
};
export type ProducerScheduleInterm = {
version: number
producers: ProducerKeyInterm[]
};
export function mapProducerSchedule(r: ProducerScheduleInterm): ProducerSchedule {
return {
version: r.version,
producers: r.producers.map(n => mapProducerKey(n)),
}
}
export type Refund = {
owner: string
};
export type RefundInterm = {
owner: string
};
export function mapRefund(r: RefundInterm): Refund {
return {
owner: r.owner,
}
}
export type RefundRequest = {
owner: string
request_time: string
net_amount: Asset
cpu_amount: Asset
};
export type RefundRequestInterm = {
owner: string
request_time: string
net_amount: string
cpu_amount: string
};
export function mapRefundRequest(r: RefundRequestInterm): RefundRequest {
return {
owner: r.owner,
request_time: r.request_time,
net_amount: new Asset(r.net_amount),
cpu_amount: new Asset(r.cpu_amount),
}
}
export type Regproducer = {
producer: string
producer_key: string
url: string
location: number
};
export type RegproducerInterm = {
producer: string
producer_key: string
url: string
location: number
};
export function mapRegproducer(r: RegproducerInterm): Regproducer {
return {
producer: r.producer,
producer_key: r.producer_key,
url: r.url,
location: r.location,
}
}
export type Regproducer2 = {
producer: string
producer_authority: unknown
url: string
location: number
};
export type Regproducer2Interm = {
producer: string
producer_authority: unknown
url: string
location: number
};
export function mapRegproducer2(r: Regproducer2Interm): Regproducer2 {
return {
producer: r.producer,
producer_authority: r.producer_authority,
url: r.url,
location: r.location,
}
}
export type Regproxy = {
proxy: string
isproxy: boolean
};
export type RegproxyInterm = {
proxy: string
isproxy: number
};
export function mapRegproxy(r: RegproxyInterm): Regproxy {
return {
proxy: r.proxy,
isproxy: !!(r.isproxy),
}
}
export type Rentcpu = {
from: string
receiver: string
loan_payment: Asset
loan_fund: Asset
};
export type RentcpuInterm = {
from: string
receiver: string
loan_payment: string
loan_fund: string
};
export function mapRentcpu(r: RentcpuInterm): Rentcpu {
return {
from: r.from,
receiver: r.receiver,
loan_payment: new Asset(r.loan_payment),
loan_fund: new Asset(r.loan_fund),
}
}
export type Rentnet = {
from: string
receiver: string
loan_payment: Asset
loan_fund: Asset
};
export type RentnetInterm = {
from: string
receiver: string
loan_payment: string
loan_fund: string
};
export function mapRentnet(r: RentnetInterm): Rentnet {
return {
from: r.from,
receiver: r.receiver,
loan_payment: new Asset(r.loan_payment),
loan_fund: new Asset(r.loan_fund),
}
}
export type RexBalance = {
version: number
owner: string
vote_stake: Asset
rex_balance: Asset
matured_rex: string
rex_maturities: PairTimePointSecInt64[]
};
export type RexBalanceInterm = {
version: number
owner: string
vote_stake: string
rex_balance: string
matured_rex: number
rex_maturities: PairTimePointSecInt64Interm[]
};
export function mapRexBalance(r: RexBalanceInterm): RexBalance {
return {
version: r.version,
owner: r.owner,
vote_stake: new Asset(r.vote_stake),
rex_balance: new Asset(r.rex_balance),
matured_rex: r.matured_rex.toString(),
rex_maturities: r.rex_maturities.map(n => mapPairTimePointSecInt64(n)),
}
}
export type RexFund = {
version: number
owner: string
balance: Asset
};
export type RexFundInterm = {
version: number
owner: string
balance: string
};
export function mapRexFund(r: RexFundInterm): RexFund {
return {
version: r.version,
owner: r.owner,
balance: new Asset(r.balance),
}
}
export type RexLoan = {
version: number
from: string
receiver: string
payment: Asset
balance: Asset
total_staked: Asset
loan_num: string
expiration: string
};
export type RexLoanInterm = {
version: number
from: string
receiver: string
payment: string
balance: string
total_staked: string
loan_num: number
expiration: string
};
export function mapRexLoan(r: RexLoanInterm): RexLoan {
return {
version: r.version,
from: r.from,
receiver: r.receiver,
payment: new Asset(r.payment),
balance: new Asset(r.balance),
total_staked: new Asset(r.total_staked),
loan_num: r.loan_num.toString(),
expiration: r.expiration,
}
}
export type RexOrder = {
version: number
owner: string
rex_requested: Asset
proceeds: Asset
stake_change: Asset
order_time: string
is_open: boolean
};
export type RexOrderInterm = {
version: number
owner: string
rex_requested: string
proceeds: string
stake_change: string
order_time: string
is_open: number
};
export function mapRexOrder(r: RexOrderInterm): RexOrder {
return {
version: r.version,
owner: r.owner,
rex_requested: new Asset(r.rex_requested),
proceeds: new Asset(r.proceeds),
stake_change: new Asset(r.stake_change),
order_time: r.order_time,
is_open: !!(r.is_open),
}
}
export type RexPool = {
version: number
total_lent: Asset
total_unlent: Asset
total_rent: Asset
total_lendable: Asset
total_rex: Asset
namebid_proceeds: Asset
loan_num: string
};
export type RexPoolInterm = {
version: number
total_lent: string
total_unlent: string
total_rent: string
total_lendable: string
total_rex: string
namebid_proceeds: string
loan_num: number
};
export function mapRexPool(r: RexPoolInterm): RexPool {
return {
version: r.version,
total_lent: new Asset(r.total_lent),
total_unlent: new Asset(r.total_unlent),
total_rent: new Asset(r.total_rent),
total_lendable: new Asset(r.total_lendable),
total_rex: new Asset(r.total_rex),
namebid_proceeds: new Asset(r.namebid_proceeds),
loan_num: r.loan_num.toString(),
}
}
export type RexReturnBuckets = {
version: number
return_buckets: PairTimePointSecInt64[]
};
export type RexReturnBucketsInterm = {
version: number
return_buckets: PairTimePointSecInt64Interm[]
};
export function mapRexReturnBuckets(r: RexReturnBucketsInterm): RexReturnBuckets {
return {
version: r.version,
return_buckets: r.return_buckets.map(n => mapPairTimePointSecInt64(n)),
}
}
export type RexReturnPool = {
version: number
last_dist_time: string
pending_bucket_time: string
oldest_bucket_time: string
pending_bucket_proceeds: string
current_rate_of_increase: string
proceeds: string
};
export type RexReturnPoolInterm = {
version: number
last_dist_time: string
pending_bucket_time: string
oldest_bucket_time: string
pending_bucket_proceeds: number
current_rate_of_increase: number
proceeds: number
};
export function mapRexReturnPool(r: RexReturnPoolInterm): RexReturnPool {
return {
version: r.version,
last_dist_time: r.last_dist_time,
pending_bucket_time: r.pending_bucket_time,
oldest_bucket_time: r.oldest_bucket_time,
pending_bucket_proceeds: r.pending_bucket_proceeds.toString(),
current_rate_of_increase: r.current_rate_of_increase.toString(),
proceeds: r.proceeds.toString(),
}
}
export type Rexexec = {
user: string
max: number
};
export type RexexecInterm = {
user: string
max: number
};
export function mapRexexec(r: RexexecInterm): Rexexec {
return {
user: r.user,
max: r.max,
}
}
export type Rmvproducer = {
producer: string
};
export type RmvproducerInterm = {
producer: string
};
export function mapRmvproducer(r: RmvproducerInterm): Rmvproducer {
return {
producer: r.producer,
}
}
export type Sellram = {
account: string
bytes: string
};
export type SellramInterm = {
account: string
bytes: number
};
export function mapSellram(r: SellramInterm): Sellram {
return {
account: r.account,
bytes: r.bytes.toString(),
}
}
export type Sellrex = {
from: string
rex: Asset
};
export type SellrexInterm = {
from: string
rex: string
};
export function mapSellrex(r: SellrexInterm): Sellrex {
return {
from: r.from,
rex: new Asset(r.rex),
}
}
export type Setabi = {
account: string
abi: string
};
export type SetabiInterm = {
account: string
abi: string
};
export function mapSetabi(r: SetabiInterm): Setabi {
return {
account: r.account,
abi: r.abi,
}
}
export type Setacctcpu = {
account: string
cpu_weight: unknown
};
export type SetacctcpuInterm = {
account: string
cpu_weight: unknown
};
export function mapSetacctcpu(r: SetacctcpuInterm): Setacctcpu {
return {
account: r.account,
cpu_weight: r.cpu_weight,
}
}
export type Setacctnet = {
account: string
net_weight: unknown
};
export type SetacctnetInterm = {
account: string
net_weight: unknown
};
export function mapSetacctnet(r: SetacctnetInterm): Setacctnet {
return {
account: r.account,
net_weight: r.net_weight,
}
}
export type Setacctram = {
account: string
ram_bytes: unknown
};
export type SetacctramInterm = {
account: string
ram_bytes: unknown
};
export function mapSetacctram(r: SetacctramInterm): Setacctram {
return {
account: r.account,
ram_bytes: r.ram_bytes,
}
}
export type Setalimits = {
account: string
ram_bytes: string
net_weight: string
cpu_weight: string
};
export type SetalimitsInterm = {
account: string
ram_bytes: number
net_weight: number
cpu_weight: number
};
export function mapSetalimits(r: SetalimitsInterm): Setalimits {
return {
account: r.account,
ram_bytes: r.ram_bytes.toString(),
net_weight: r.net_weight.toString(),
cpu_weight: r.cpu_weight.toString(),
}
}
export type Setcode = {
account: string
vmtype: number
vmversion: number
code: string
};
export type SetcodeInterm = {
account: string
vmtype: number
vmversion: number
code: string
};
export function mapSetcode(r: SetcodeInterm): Setcode {
return {
account: r.account,
vmtype: r.vmtype,
vmversion: r.vmversion,
code: r.code,
}
}
export type Setinflation = {
annual_rate: string
inflation_pay_factor: string
votepay_factor: string
};
export type SetinflationInterm = {
annual_rate: number
inflation_pay_factor: number
votepay_factor: number
};
export function mapSetinflation(r: SetinflationInterm): Setinflation {
return {
annual_rate: r.annual_rate.toString(),
inflation_pay_factor: r.inflation_pay_factor.toString(),
votepay_factor: r.votepay_factor.toString(),
}
}
export type Setparams = {
params: BlockchainParameters
};
export type SetparamsInterm = {
params: BlockchainParametersInterm
};
export function mapSetparams(r: SetparamsInterm): Setparams {
return {
params: mapBlockchainParameters(r.params),
}
}
export type Setpriv = {
account: string
is_priv: number
};
export type SetprivInterm = {
account: string
is_priv: number
};
export function mapSetpriv(r: SetprivInterm): Setpriv {
return {
account: r.account,
is_priv: r.is_priv,
}
}
export type Setram = {
max_ram_size: string
};
export type SetramInterm = {
max_ram_size: number
};
export function mapSetram(r: SetramInterm): Setram {
return {
max_ram_size: r.max_ram_size.toString(),
}
}
export type Setramrate = {
bytes_per_block: number
};
export type SetramrateInterm = {
bytes_per_block: number
};
export function mapSetramrate(r: SetramrateInterm): Setramrate {
return {
bytes_per_block: r.bytes_per_block,
}
}
export type Setrex = {
balance: Asset
};
export type SetrexInterm = {
balance: string
};
export function mapSetrex(r: SetrexInterm): Setrex {
return {
balance: new Asset(r.balance),
}
}
export type Undelegatebw = {
from: string
receiver: string
unstake_net_quantity: Asset
unstake_cpu_quantity: Asset
};
export type UndelegatebwInterm = {
from: string
receiver: string
unstake_net_quantity: string
unstake_cpu_quantity: string
};
export function mapUndelegatebw(r: UndelegatebwInterm): Undelegatebw {
return {
from: r.from,
receiver: r.receiver,
unstake_net_quantity: new Asset(r.unstake_net_quantity),
unstake_cpu_quantity: new Asset(r.unstake_cpu_quantity),
}
}
export type Unlinkauth = {
account: string
code: string
type: string
};
export type UnlinkauthInterm = {
account: string
code: string
type: string
};
export function mapUnlinkauth(r: UnlinkauthInterm): Unlinkauth {
return {
account: r.account,
code: r.code,
type: r.type,
}
}
export type Unregprod = {
producer: string
};
export type UnregprodInterm = {
producer: string
};
export function mapUnregprod(r: UnregprodInterm): Unregprod {
return {
producer: r.producer,
}
}
export type Unstaketorex = {
owner: string
receiver: string
from_net: Asset
from_cpu: Asset
};
export type UnstaketorexInterm = {
owner: string
receiver: string
from_net: string
from_cpu: string
};
export function mapUnstaketorex(r: UnstaketorexInterm): Unstaketorex {
return {
owner: r.owner,
receiver: r.receiver,
from_net: new Asset(r.from_net),
from_cpu: new Asset(r.from_cpu),
}
}
export type Updateauth = {
account: string
permission: string
parent: string
auth: Authority
};
export type UpdateauthInterm = {
account: string
permission: string
parent: string
auth: AuthorityInterm
};
export function mapUpdateauth(r: UpdateauthInterm): Updateauth {
return {
account: r.account,
permission: r.permission,
parent: r.parent,
auth: mapAuthority(r.auth),
}
}
export type Updaterex = {
owner: string
};
export type UpdaterexInterm = {
owner: string
};
export function mapUpdaterex(r: UpdaterexInterm): Updaterex {
return {
owner: r.owner,
}
}
export type Updtrevision = {
revision: number
};
export type UpdtrevisionInterm = {
revision: number
};
export function mapUpdtrevision(r: UpdtrevisionInterm): Updtrevision {
return {
revision: r.revision,
}
}
export type UserResources = {
owner: string
net_weight: Asset
cpu_weight: Asset
ram_bytes: string
};
export type UserResourcesInterm = {
owner: string
net_weight: string
cpu_weight: string
ram_bytes: number
};
export function mapUserResources(r: UserResourcesInterm): UserResources {
return {
owner: r.owner,
net_weight: new Asset(r.net_weight),
cpu_weight: new Asset(r.cpu_weight),
ram_bytes: r.ram_bytes.toString(),
}
}
export type Voteproducer = {
voter: string
proxy: string
producers: string[]
};
export type VoteproducerInterm = {
voter: string
proxy: string
producers: string[]
};
export function mapVoteproducer(r: VoteproducerInterm): Voteproducer {
return {
voter: r.voter,
proxy: r.proxy,
producers: r.producers,
}
}
export type VoterInfo = {
owner: string
proxy: string
producers: string[]
staked: string
last_vote_weight: number
proxied_vote_weight: number
is_proxy: boolean
flags1: number
reserved2: number
reserved3: Asset
};
export type VoterInfoInterm = {
owner: string
proxy: string
producers: string[]
staked: number
last_vote_weight: string
proxied_vote_weight: string
is_proxy: number
flags1: number
reserved2: number
reserved3: string
};
export function mapVoterInfo(r: VoterInfoInterm): VoterInfo {
return {
owner: r.owner,
proxy: r.proxy,
producers: r.producers,
staked: r.staked.toString(),
last_vote_weight: Number.parseFloat(r.last_vote_weight),
proxied_vote_weight: Number.parseFloat(r.proxied_vote_weight),
is_proxy: !!(r.is_proxy),
flags1: r.flags1,
reserved2: r.reserved2,
reserved3: new Asset(r.reserved3),
}
}
export type WaitWeight = {
wait_sec: number
weight: number
};
export type WaitWeightInterm = {
wait_sec: number
weight: number
};
export function mapWaitWeight(r: WaitWeightInterm): WaitWeight {
return {
wait_sec: r.wait_sec,
weight: r.weight,
}
}
export type Withdraw = {
owner: string
amount: Asset
};
export type WithdrawInterm = {
owner: string
amount: string
};
export function mapWithdraw(r: WithdrawInterm): Withdraw {
return {
owner: r.owner,
amount: new Asset(r.amount),
}
}
export type AbiHashRows = {
more: boolean;
next_key: string;
rows: AbiHash[];
};
export type AbiHashRowsInterm = {
more: boolean;
next_key: string;
rows: AbiHashInterm[];
};
export type BidRefundRows = {
more: boolean;
next_key: string;
rows: BidRefund[];
};
export type BidRefundRowsInterm = {
more: boolean;
next_key: string;
rows: BidRefundInterm[];
};
export type RexLoanRows = {
more: boolean;
next_key: string;
rows: RexLoan[];
};
export type RexLoanRowsInterm = {
more: boolean;
next_key: string;
rows: RexLoanInterm[];
};
export type DelegatedBandwidthRows = {
more: boolean;
next_key: string;
rows: DelegatedBandwidth[];
};
export type DelegatedBandwidthRowsInterm = {
more: boolean;
next_key: string;
rows: DelegatedBandwidthInterm[];
};
export type EosioGlobalStateRows = {
more: boolean;
next_key: string;
rows: EosioGlobalState[];
};
export type EosioGlobalStateRowsInterm = {
more: boolean;
next_key: string;
rows: EosioGlobalStateInterm[];
};
export type EosioGlobalState2Rows = {
more: boolean;
next_key: string;
rows: EosioGlobalState2[];
};
export type EosioGlobalState2RowsInterm = {
more: boolean;
next_key: string;
rows: EosioGlobalState2Interm[];
};
export type EosioGlobalState3Rows = {
more: boolean;
next_key: string;
rows: EosioGlobalState3[];
};
export type EosioGlobalState3RowsInterm = {
more: boolean;
next_key: string;
rows: EosioGlobalState3Interm[];
};
export type EosioGlobalState4Rows = {
more: boolean;
next_key: string;
rows: EosioGlobalState4[];
};
export type EosioGlobalState4RowsInterm = {
more: boolean;
next_key: string;
rows: EosioGlobalState4Interm[];
};
export type NameBidRows = {
more: boolean;
next_key: string;
rows: NameBid[];
};
export type NameBidRowsInterm = {
more: boolean;
next_key: string;
rows: NameBidInterm[];
};
export type PowerupOrderRows = {
more: boolean;
next_key: string;
rows: PowerupOrder[];
};
export type PowerupOrderRowsInterm = {
more: boolean;
next_key: string;
rows: PowerupOrderInterm[];
};
export type PowerupStateRows = {
more: boolean;
next_key: string;
rows: PowerupState[];
};
export type PowerupStateRowsInterm = {
more: boolean;
next_key: string;
rows: PowerupStateInterm[];
};
export type ProducerInfoRows = {
more: boolean;
next_key: string;
rows: ProducerInfo[];
};
export type ProducerInfoRowsInterm = {
more: boolean;
next_key: string;
rows: ProducerInfoInterm[];
};
export type ProducerInfo2Rows = {
more: boolean;
next_key: string;
rows: ProducerInfo2[];
};
export type ProducerInfo2RowsInterm = {
more: boolean;
next_key: string;
rows: ProducerInfo2Interm[];
};
export type ExchangeStateRows = {
more: boolean;
next_key: string;
rows: ExchangeState[];
};
export type ExchangeStateRowsInterm = {
more: boolean;
next_key: string;
rows: ExchangeStateInterm[];
};
export type RefundRequestRows = {
more: boolean;
next_key: string;
rows: RefundRequest[];
};
export type RefundRequestRowsInterm = {
more: boolean;
next_key: string;
rows: RefundRequestInterm[];
};
export type RexReturnBucketsRows = {
more: boolean;
next_key: string;
rows: RexReturnBuckets[];
};
export type RexReturnBucketsRowsInterm = {
more: boolean;
next_key: string;
rows: RexReturnBucketsInterm[];
};
export type RexBalanceRows = {
more: boolean;
next_key: string;
rows: RexBalance[];
};
export type RexBalanceRowsInterm = {
more: boolean;
next_key: string;
rows: RexBalanceInterm[];
};
export type RexFundRows = {
more: boolean;
next_key: string;
rows: RexFund[];
};
export type RexFundRowsInterm = {
more: boolean;
next_key: string;
rows: RexFundInterm[];
};
export type RexPoolRows = {
more: boolean;
next_key: string;
rows: RexPool[];
};
export type RexPoolRowsInterm = {
more: boolean;
next_key: string;
rows: RexPoolInterm[];
};
export type RexOrderRows = {
more: boolean;
next_key: string;
rows: RexOrder[];
};
export type RexOrderRowsInterm = {
more: boolean;
next_key: string;
rows: RexOrderInterm[];
};
export type RexReturnPoolRows = {
more: boolean;
next_key: string;
rows: RexReturnPool[];
};
export type RexReturnPoolRowsInterm = {
more: boolean;
next_key: string;
rows: RexReturnPoolInterm[];
};
export type UserResourcesRows = {
more: boolean;
next_key: string;
rows: UserResources[];
};
export type UserResourcesRowsInterm = {
more: boolean;
next_key: string;
rows: UserResourcesInterm[];
};
export type VoterInfoRows = {
more: boolean;
next_key: string;
rows: VoterInfo[];
};
export type VoterInfoRowsInterm = {
more: boolean;
next_key: string;
rows: VoterInfoInterm[];
};
| 19.404158 | 103 | 0.74693 | 2,076 | 107 | 0 | 107 | 4 | 826 | 13 | 0 | 695 | 247 | 0 | 5.158879 | 16,028 | 0.013352 | 0.00025 | 0.051535 | 0.015411 | 0 | 0 | 0.665709 | 0.229411 | // Generated by eos-abigen version master
export const CONTRACT_NAME = "eosio";
export type Authorization = {
actor;
permission;
}
export type Action = {
account;
name;
authorization;
data;
}
export type GetTableRowsParams = Partial<{
code
scope
bounds
lower_bound
upper_bound
index_position
key_type
limit
reverse
show_payer
}>
export class Symbol {
readonly raw;
readonly precision;
readonly symbol_code;
public constructor(raw) {
this.raw = raw;
const [precision, symbol_code] = raw.split(",", 2)
this.precision = Number.parseInt(precision);
this.symbol_code = symbol_code;
}
}
export class Asset {
readonly raw;
readonly raw_quantity;
readonly quantity;
readonly precision;
readonly symbol_code;
public constructor(raw) {
this.raw = raw;
const [quantity, symbol_code] = raw.split(" ", 2);
this.raw_quantity = quantity;
this.precision = 0;
const splitted = quantity.split(".");
if (splitted.length > 1) {
this.precision = splitted[1].length;
}
this.quantity = Number.parseFloat(quantity);
this.symbol_code = symbol_code;
}
}
export type ExtendedAssetType = {
quantity
contract
}
export class ExtendedAsset {
readonly asset;
readonly contract;
public constructor(raw) {
this.asset = new Asset(raw.quantity);
this.contract = raw.contract;
}
}
export type AbiHash = {
owner
hash
};
export type AbiHashInterm = {
owner
hash
};
export function mapAbiHash(r) {
return {
owner: r.owner,
hash: r.hash,
}
}
export type Activate = {
feature_digest
};
export type ActivateInterm = {
feature_digest
};
export function mapActivate(r) {
return {
feature_digest: r.feature_digest,
}
}
export type Authority = {
threshold
keys
accounts
waits
};
export type AuthorityInterm = {
threshold
keys
accounts
waits
};
export /* Example usages of 'mapAuthority' are shown below:
mapAuthority(r.owner);
mapAuthority(r.active);
mapAuthority(r.auth);
*/
function mapAuthority(r) {
return {
threshold: r.threshold,
keys: r.keys.map(n => mapKeyWeight(n)),
accounts: r.accounts.map(n => mapPermissionLevelWeight(n)),
waits: r.waits.map(n => mapWaitWeight(n)),
}
}
export type BidRefund = {
bidder
amount
};
export type BidRefundInterm = {
bidder
amount
};
export function mapBidRefund(r) {
return {
bidder: r.bidder,
amount: new Asset(r.amount),
}
}
export type Bidname = {
bidder
newname
bid
};
export type BidnameInterm = {
bidder
newname
bid
};
export function mapBidname(r) {
return {
bidder: r.bidder,
newname: r.newname,
bid: new Asset(r.bid),
}
}
export type Bidrefund = {
bidder
newname
};
export type BidrefundInterm = {
bidder
newname
};
export function mapBidrefund(r) {
return {
bidder: r.bidder,
newname: r.newname,
}
}
export type BlockHeader = {
timestamp
producer
confirmed
previous
transaction_mroot
action_mroot
schedule_version
new_producers
};
export type BlockHeaderInterm = {
timestamp
producer
confirmed
previous
transaction_mroot
action_mroot
schedule_version
new_producers
};
export /* Example usages of 'mapBlockHeader' are shown below:
mapBlockHeader(r.header);
*/
function mapBlockHeader(r) {
return {
timestamp: r.timestamp,
producer: r.producer,
confirmed: r.confirmed,
previous: r.previous,
transaction_mroot: r.transaction_mroot,
action_mroot: r.action_mroot,
schedule_version: r.schedule_version,
new_producers: r.new_producers,
}
}
export type BlockSigningAuthorityV0 = {
threshold
keys
};
export type BlockSigningAuthorityV0Interm = {
threshold
keys
};
export function mapBlockSigningAuthorityV0(r) {
return {
threshold: r.threshold,
keys: r.keys.map(n => mapKeyWeight(n)),
}
}
export type BlockchainParameters = {
max_block_net_usage
target_block_net_usage_pct
max_transaction_net_usage
base_per_transaction_net_usage
net_usage_leeway
context_free_discount_net_usage_num
context_free_discount_net_usage_den
max_block_cpu_usage
target_block_cpu_usage_pct
max_transaction_cpu_usage
min_transaction_cpu_usage
max_transaction_lifetime
deferred_trx_expiration_window
max_transaction_delay
max_inline_action_size
max_inline_action_depth
max_authority_depth
};
export type BlockchainParametersInterm = {
max_block_net_usage
target_block_net_usage_pct
max_transaction_net_usage
base_per_transaction_net_usage
net_usage_leeway
context_free_discount_net_usage_num
context_free_discount_net_usage_den
max_block_cpu_usage
target_block_cpu_usage_pct
max_transaction_cpu_usage
min_transaction_cpu_usage
max_transaction_lifetime
deferred_trx_expiration_window
max_transaction_delay
max_inline_action_size
max_inline_action_depth
max_authority_depth
};
export /* Example usages of 'mapBlockchainParameters' are shown below:
mapBlockchainParameters(r.params);
*/
function mapBlockchainParameters(r) {
return {
max_block_net_usage: r.max_block_net_usage.toString(),
target_block_net_usage_pct: r.target_block_net_usage_pct,
max_transaction_net_usage: r.max_transaction_net_usage,
base_per_transaction_net_usage: r.base_per_transaction_net_usage,
net_usage_leeway: r.net_usage_leeway,
context_free_discount_net_usage_num: r.context_free_discount_net_usage_num,
context_free_discount_net_usage_den: r.context_free_discount_net_usage_den,
max_block_cpu_usage: r.max_block_cpu_usage,
target_block_cpu_usage_pct: r.target_block_cpu_usage_pct,
max_transaction_cpu_usage: r.max_transaction_cpu_usage,
min_transaction_cpu_usage: r.min_transaction_cpu_usage,
max_transaction_lifetime: r.max_transaction_lifetime,
deferred_trx_expiration_window: r.deferred_trx_expiration_window,
max_transaction_delay: r.max_transaction_delay,
max_inline_action_size: r.max_inline_action_size,
max_inline_action_depth: r.max_inline_action_depth,
max_authority_depth: r.max_authority_depth,
}
}
export type Buyram = {
payer
receiver
quant
};
export type BuyramInterm = {
payer
receiver
quant
};
export function mapBuyram(r) {
return {
payer: r.payer,
receiver: r.receiver,
quant: new Asset(r.quant),
}
}
export type Buyrambytes = {
payer
receiver
bytes
};
export type BuyrambytesInterm = {
payer
receiver
bytes
};
export function mapBuyrambytes(r) {
return {
payer: r.payer,
receiver: r.receiver,
bytes: r.bytes,
}
}
export type Buyrex = {
from
amount
};
export type BuyrexInterm = {
from
amount
};
export function mapBuyrex(r) {
return {
from: r.from,
amount: new Asset(r.amount),
}
}
export type Canceldelay = {
canceling_auth
trx_id
};
export type CanceldelayInterm = {
canceling_auth
trx_id
};
export function mapCanceldelay(r) {
return {
canceling_auth: mapPermissionLevel(r.canceling_auth),
trx_id: r.trx_id,
}
}
export type Cfgpowerup = {
args
};
export type CfgpowerupInterm = {
args
};
export function mapCfgpowerup(r) {
return {
args: mapPowerupConfig(r.args),
}
}
export type Claimrewards = {
owner
};
export type ClaimrewardsInterm = {
owner
};
export function mapClaimrewards(r) {
return {
owner: r.owner,
}
}
export type Closerex = {
owner
};
export type CloserexInterm = {
owner
};
export function mapCloserex(r) {
return {
owner: r.owner,
}
}
export type Cnclrexorder = {
owner
};
export type CnclrexorderInterm = {
owner
};
export function mapCnclrexorder(r) {
return {
owner: r.owner,
}
}
export type Connector = {
balance
weight
};
export type ConnectorInterm = {
balance
weight
};
export /* Example usages of 'mapConnector' are shown below:
mapConnector(r.base);
mapConnector(r.quote);
*/
function mapConnector(r) {
return {
balance: new Asset(r.balance),
weight: Number.parseFloat(r.weight),
}
}
export type Consolidate = {
owner
};
export type ConsolidateInterm = {
owner
};
export function mapConsolidate(r) {
return {
owner: r.owner,
}
}
export type Defcpuloan = {
from
loan_num
amount
};
export type DefcpuloanInterm = {
from
loan_num
amount
};
export function mapDefcpuloan(r) {
return {
from: r.from,
loan_num: r.loan_num.toString(),
amount: new Asset(r.amount),
}
}
export type Defnetloan = {
from
loan_num
amount
};
export type DefnetloanInterm = {
from
loan_num
amount
};
export function mapDefnetloan(r) {
return {
from: r.from,
loan_num: r.loan_num.toString(),
amount: new Asset(r.amount),
}
}
export type Delegatebw = {
from
receiver
stake_net_quantity
stake_cpu_quantity
transfer
};
export type DelegatebwInterm = {
from
receiver
stake_net_quantity
stake_cpu_quantity
transfer
};
export function mapDelegatebw(r) {
return {
from: r.from,
receiver: r.receiver,
stake_net_quantity: new Asset(r.stake_net_quantity),
stake_cpu_quantity: new Asset(r.stake_cpu_quantity),
transfer: !!(r.transfer),
}
}
export type DelegatedBandwidth = {
from
to
net_weight
cpu_weight
};
export type DelegatedBandwidthInterm = {
from
to
net_weight
cpu_weight
};
export function mapDelegatedBandwidth(r) {
return {
from: r.from,
to: r.to,
net_weight: new Asset(r.net_weight),
cpu_weight: new Asset(r.cpu_weight),
}
}
export type Deleteauth = {
account
permission
};
export type DeleteauthInterm = {
account
permission
};
export function mapDeleteauth(r) {
return {
account: r.account,
permission: r.permission,
}
}
export type Deposit = {
owner
amount
};
export type DepositInterm = {
owner
amount
};
export function mapDeposit(r) {
return {
owner: r.owner,
amount: new Asset(r.amount),
}
}
export type EosioGlobalState = {
max_ram_size
total_ram_bytes_reserved
total_ram_stake
last_producer_schedule_update
last_pervote_bucket_fill
pervote_bucket
perblock_bucket
total_unpaid_blocks
total_activated_stake
thresh_activated_stake_time
last_producer_schedule_size
total_producer_vote_weight
last_name_close
};
export type EosioGlobalStateInterm = {
max_ram_size
total_ram_bytes_reserved
total_ram_stake
last_producer_schedule_update
last_pervote_bucket_fill
pervote_bucket
perblock_bucket
total_unpaid_blocks
total_activated_stake
thresh_activated_stake_time
last_producer_schedule_size
total_producer_vote_weight
last_name_close
};
export function mapEosioGlobalState(r) {
return {
max_ram_size: r.max_ram_size.toString(),
total_ram_bytes_reserved: r.total_ram_bytes_reserved.toString(),
total_ram_stake: r.total_ram_stake.toString(),
last_producer_schedule_update: r.last_producer_schedule_update,
last_pervote_bucket_fill: r.last_pervote_bucket_fill,
pervote_bucket: r.pervote_bucket.toString(),
perblock_bucket: r.perblock_bucket.toString(),
total_unpaid_blocks: r.total_unpaid_blocks,
total_activated_stake: r.total_activated_stake.toString(),
thresh_activated_stake_time: r.thresh_activated_stake_time,
last_producer_schedule_size: r.last_producer_schedule_size,
total_producer_vote_weight: Number.parseFloat(r.total_producer_vote_weight),
last_name_close: r.last_name_close,
}
}
export type EosioGlobalState2 = {
new_ram_per_block
last_ram_increase
last_block_num
total_producer_votepay_share
revision
};
export type EosioGlobalState2Interm = {
new_ram_per_block
last_ram_increase
last_block_num
total_producer_votepay_share
revision
};
export function mapEosioGlobalState2(r) {
return {
new_ram_per_block: r.new_ram_per_block,
last_ram_increase: r.last_ram_increase,
last_block_num: r.last_block_num,
total_producer_votepay_share: Number.parseFloat(r.total_producer_votepay_share),
revision: r.revision,
}
}
export type EosioGlobalState3 = {
last_vpay_state_update
total_vpay_share_change_rate
};
export type EosioGlobalState3Interm = {
last_vpay_state_update
total_vpay_share_change_rate
};
export function mapEosioGlobalState3(r) {
return {
last_vpay_state_update: r.last_vpay_state_update,
total_vpay_share_change_rate: Number.parseFloat(r.total_vpay_share_change_rate),
}
}
export type EosioGlobalState4 = {
continuous_rate
inflation_pay_factor
votepay_factor
};
export type EosioGlobalState4Interm = {
continuous_rate
inflation_pay_factor
votepay_factor
};
export function mapEosioGlobalState4(r) {
return {
continuous_rate: Number.parseFloat(r.continuous_rate),
inflation_pay_factor: r.inflation_pay_factor.toString(),
votepay_factor: r.votepay_factor.toString(),
}
}
export type ExchangeState = {
supply
base
quote
};
export type ExchangeStateInterm = {
supply
base
quote
};
export function mapExchangeState(r) {
return {
supply: new Asset(r.supply),
base: mapConnector(r.base),
quote: mapConnector(r.quote),
}
}
export type Fundcpuloan = {
from
loan_num
payment
};
export type FundcpuloanInterm = {
from
loan_num
payment
};
export function mapFundcpuloan(r) {
return {
from: r.from,
loan_num: r.loan_num.toString(),
payment: new Asset(r.payment),
}
}
export type Fundnetloan = {
from
loan_num
payment
};
export type FundnetloanInterm = {
from
loan_num
payment
};
export function mapFundnetloan(r) {
return {
from: r.from,
loan_num: r.loan_num.toString(),
payment: new Asset(r.payment),
}
}
export type Init = {
version
core
};
export type InitInterm = {
version
core
};
export function mapInit(r) {
return {
version: r.version,
core: new Symbol(r.core),
}
}
export type KeyWeight = {
key
weight
};
export type KeyWeightInterm = {
key
weight
};
export /* Example usages of 'mapKeyWeight' are shown below:
mapKeyWeight(n);
*/
function mapKeyWeight(r) {
return {
key: r.key,
weight: r.weight,
}
}
export type Linkauth = {
account
code
type
requirement
};
export type LinkauthInterm = {
account
code
type
requirement
};
export function mapLinkauth(r) {
return {
account: r.account,
code: r.code,
type: r.type,
requirement: r.requirement,
}
}
export type Mvfrsavings = {
owner
rex
};
export type MvfrsavingsInterm = {
owner
rex
};
export function mapMvfrsavings(r) {
return {
owner: r.owner,
rex: new Asset(r.rex),
}
}
export type Mvtosavings = {
owner
rex
};
export type MvtosavingsInterm = {
owner
rex
};
export function mapMvtosavings(r) {
return {
owner: r.owner,
rex: new Asset(r.rex),
}
}
export type NameBid = {
newname
high_bidder
high_bid
last_bid_time
};
export type NameBidInterm = {
newname
high_bidder
high_bid
last_bid_time
};
export function mapNameBid(r) {
return {
newname: r.newname,
high_bidder: r.high_bidder,
high_bid: r.high_bid.toString(),
last_bid_time: r.last_bid_time,
}
}
export type Newaccount = {
creator
name
owner
active
};
export type NewaccountInterm = {
creator
name
owner
active
};
export function mapNewaccount(r) {
return {
creator: r.creator,
name: r.name,
owner: mapAuthority(r.owner),
active: mapAuthority(r.active),
}
}
export type Onblock = {
header
};
export type OnblockInterm = {
header
};
export function mapOnblock(r) {
return {
header: mapBlockHeader(r.header),
}
}
export type Onerror = {
sender_id
sent_trx
};
export type OnerrorInterm = {
sender_id
sent_trx
};
export function mapOnerror(r) {
return {
sender_id: r.sender_id,
sent_trx: r.sent_trx,
}
}
export type PairTimePointSecInt64 = {
key
value
};
export type PairTimePointSecInt64Interm = {
key
value
};
export /* Example usages of 'mapPairTimePointSecInt64' are shown below:
mapPairTimePointSecInt64(n);
*/
function mapPairTimePointSecInt64(r) {
return {
key: r.key,
value: r.value.toString(),
}
}
export type PermissionLevel = {
actor
permission
};
export type PermissionLevelInterm = {
actor
permission
};
export /* Example usages of 'mapPermissionLevel' are shown below:
mapPermissionLevel(r.canceling_auth);
mapPermissionLevel(r.permission);
*/
function mapPermissionLevel(r) {
return {
actor: r.actor,
permission: r.permission,
}
}
export type PermissionLevelWeight = {
permission
weight
};
export type PermissionLevelWeightInterm = {
permission
weight
};
export /* Example usages of 'mapPermissionLevelWeight' are shown below:
mapPermissionLevelWeight(n);
*/
function mapPermissionLevelWeight(r) {
return {
permission: mapPermissionLevel(r.permission),
weight: r.weight,
}
}
export type Powerup = {
payer
receiver
days
net_frac
cpu_frac
max_payment
};
export type PowerupInterm = {
payer
receiver
days
net_frac
cpu_frac
max_payment
};
export function mapPowerup(r) {
return {
payer: r.payer,
receiver: r.receiver,
days: r.days,
net_frac: r.net_frac.toString(),
cpu_frac: r.cpu_frac.toString(),
max_payment: new Asset(r.max_payment),
}
}
export type PowerupConfig = {
net
cpu
powerup_days
min_powerup_fee
};
export type PowerupConfigInterm = {
net
cpu
powerup_days
min_powerup_fee
};
export /* Example usages of 'mapPowerupConfig' are shown below:
mapPowerupConfig(r.args);
*/
function mapPowerupConfig(r) {
return {
net: mapPowerupConfigResource(r.net),
cpu: mapPowerupConfigResource(r.cpu),
powerup_days: r.powerup_days,
min_powerup_fee: r.min_powerup_fee,
}
}
export type PowerupConfigResource = {
current_weight_ratio
target_weight_ratio
assumed_stake_weight
target_timestamp
exponent
decay_secs
min_price
max_price
};
export type PowerupConfigResourceInterm = {
current_weight_ratio
target_weight_ratio
assumed_stake_weight
target_timestamp
exponent
decay_secs
min_price
max_price
};
export /* Example usages of 'mapPowerupConfigResource' are shown below:
mapPowerupConfigResource(r.net);
mapPowerupConfigResource(r.cpu);
*/
function mapPowerupConfigResource(r) {
return {
current_weight_ratio: r.current_weight_ratio,
target_weight_ratio: r.target_weight_ratio,
assumed_stake_weight: r.assumed_stake_weight,
target_timestamp: r.target_timestamp,
exponent: r.exponent,
decay_secs: r.decay_secs,
min_price: r.min_price,
max_price: r.max_price,
}
}
export type PowerupOrder = {
version
id
owner
net_weight
cpu_weight
expires
};
export type PowerupOrderInterm = {
version
id
owner
net_weight
cpu_weight
expires
};
export function mapPowerupOrder(r) {
return {
version: r.version,
id: r.id.toString(),
owner: r.owner,
net_weight: r.net_weight.toString(),
cpu_weight: r.cpu_weight.toString(),
expires: r.expires,
}
}
export type PowerupState = {
version
net
cpu
powerup_days
min_powerup_fee
};
export type PowerupStateInterm = {
version
net
cpu
powerup_days
min_powerup_fee
};
export function mapPowerupState(r) {
return {
version: r.version,
net: mapPowerupStateResource(r.net),
cpu: mapPowerupStateResource(r.cpu),
powerup_days: r.powerup_days,
min_powerup_fee: new Asset(r.min_powerup_fee),
}
}
export type PowerupStateResource = {
version
weight
weight_ratio
assumed_stake_weight
initial_weight_ratio
target_weight_ratio
initial_timestamp
target_timestamp
exponent
decay_secs
min_price
max_price
utilization
adjusted_utilization
utilization_timestamp
};
export type PowerupStateResourceInterm = {
version
weight
weight_ratio
assumed_stake_weight
initial_weight_ratio
target_weight_ratio
initial_timestamp
target_timestamp
exponent
decay_secs
min_price
max_price
utilization
adjusted_utilization
utilization_timestamp
};
export /* Example usages of 'mapPowerupStateResource' are shown below:
mapPowerupStateResource(r.net);
mapPowerupStateResource(r.cpu);
*/
function mapPowerupStateResource(r) {
return {
version: r.version,
weight: r.weight.toString(),
weight_ratio: r.weight_ratio.toString(),
assumed_stake_weight: r.assumed_stake_weight.toString(),
initial_weight_ratio: r.initial_weight_ratio.toString(),
target_weight_ratio: r.target_weight_ratio.toString(),
initial_timestamp: r.initial_timestamp,
target_timestamp: r.target_timestamp,
exponent: Number.parseFloat(r.exponent),
decay_secs: r.decay_secs,
min_price: new Asset(r.min_price),
max_price: new Asset(r.max_price),
utilization: r.utilization.toString(),
adjusted_utilization: r.adjusted_utilization.toString(),
utilization_timestamp: r.utilization_timestamp,
}
}
export type Powerupexec = {
user
max
};
export type PowerupexecInterm = {
user
max
};
export function mapPowerupexec(r) {
return {
user: r.user,
max: r.max,
}
}
export type ProducerInfo = {
owner
total_votes
producer_key
is_active
url
unpaid_blocks
last_claim_time
location
producer_authority
};
export type ProducerInfoInterm = {
owner
total_votes
producer_key
is_active
url
unpaid_blocks
last_claim_time
location
producer_authority
};
export function mapProducerInfo(r) {
return {
owner: r.owner,
total_votes: Number.parseFloat(r.total_votes),
producer_key: r.producer_key,
is_active: !!(r.is_active),
url: r.url,
unpaid_blocks: r.unpaid_blocks,
last_claim_time: r.last_claim_time,
location: r.location,
producer_authority: r.producer_authority,
}
}
export type ProducerInfo2 = {
owner
votepay_share
last_votepay_share_update
};
export type ProducerInfo2Interm = {
owner
votepay_share
last_votepay_share_update
};
export function mapProducerInfo2(r) {
return {
owner: r.owner,
votepay_share: Number.parseFloat(r.votepay_share),
last_votepay_share_update: r.last_votepay_share_update,
}
}
export type ProducerKey = {
producer_name
block_signing_key
};
export type ProducerKeyInterm = {
producer_name
block_signing_key
};
export /* Example usages of 'mapProducerKey' are shown below:
mapProducerKey(n);
*/
function mapProducerKey(r) {
return {
producer_name: r.producer_name,
block_signing_key: r.block_signing_key,
}
}
export type ProducerSchedule = {
version
producers
};
export type ProducerScheduleInterm = {
version
producers
};
export function mapProducerSchedule(r) {
return {
version: r.version,
producers: r.producers.map(n => mapProducerKey(n)),
}
}
export type Refund = {
owner
};
export type RefundInterm = {
owner
};
export function mapRefund(r) {
return {
owner: r.owner,
}
}
export type RefundRequest = {
owner
request_time
net_amount
cpu_amount
};
export type RefundRequestInterm = {
owner
request_time
net_amount
cpu_amount
};
export function mapRefundRequest(r) {
return {
owner: r.owner,
request_time: r.request_time,
net_amount: new Asset(r.net_amount),
cpu_amount: new Asset(r.cpu_amount),
}
}
export type Regproducer = {
producer
producer_key
url
location
};
export type RegproducerInterm = {
producer
producer_key
url
location
};
export function mapRegproducer(r) {
return {
producer: r.producer,
producer_key: r.producer_key,
url: r.url,
location: r.location,
}
}
export type Regproducer2 = {
producer
producer_authority
url
location
};
export type Regproducer2Interm = {
producer
producer_authority
url
location
};
export function mapRegproducer2(r) {
return {
producer: r.producer,
producer_authority: r.producer_authority,
url: r.url,
location: r.location,
}
}
export type Regproxy = {
proxy
isproxy
};
export type RegproxyInterm = {
proxy
isproxy
};
export function mapRegproxy(r) {
return {
proxy: r.proxy,
isproxy: !!(r.isproxy),
}
}
export type Rentcpu = {
from
receiver
loan_payment
loan_fund
};
export type RentcpuInterm = {
from
receiver
loan_payment
loan_fund
};
export function mapRentcpu(r) {
return {
from: r.from,
receiver: r.receiver,
loan_payment: new Asset(r.loan_payment),
loan_fund: new Asset(r.loan_fund),
}
}
export type Rentnet = {
from
receiver
loan_payment
loan_fund
};
export type RentnetInterm = {
from
receiver
loan_payment
loan_fund
};
export function mapRentnet(r) {
return {
from: r.from,
receiver: r.receiver,
loan_payment: new Asset(r.loan_payment),
loan_fund: new Asset(r.loan_fund),
}
}
export type RexBalance = {
version
owner
vote_stake
rex_balance
matured_rex
rex_maturities
};
export type RexBalanceInterm = {
version
owner
vote_stake
rex_balance
matured_rex
rex_maturities
};
export function mapRexBalance(r) {
return {
version: r.version,
owner: r.owner,
vote_stake: new Asset(r.vote_stake),
rex_balance: new Asset(r.rex_balance),
matured_rex: r.matured_rex.toString(),
rex_maturities: r.rex_maturities.map(n => mapPairTimePointSecInt64(n)),
}
}
export type RexFund = {
version
owner
balance
};
export type RexFundInterm = {
version
owner
balance
};
export function mapRexFund(r) {
return {
version: r.version,
owner: r.owner,
balance: new Asset(r.balance),
}
}
export type RexLoan = {
version
from
receiver
payment
balance
total_staked
loan_num
expiration
};
export type RexLoanInterm = {
version
from
receiver
payment
balance
total_staked
loan_num
expiration
};
export function mapRexLoan(r) {
return {
version: r.version,
from: r.from,
receiver: r.receiver,
payment: new Asset(r.payment),
balance: new Asset(r.balance),
total_staked: new Asset(r.total_staked),
loan_num: r.loan_num.toString(),
expiration: r.expiration,
}
}
export type RexOrder = {
version
owner
rex_requested
proceeds
stake_change
order_time
is_open
};
export type RexOrderInterm = {
version
owner
rex_requested
proceeds
stake_change
order_time
is_open
};
export function mapRexOrder(r) {
return {
version: r.version,
owner: r.owner,
rex_requested: new Asset(r.rex_requested),
proceeds: new Asset(r.proceeds),
stake_change: new Asset(r.stake_change),
order_time: r.order_time,
is_open: !!(r.is_open),
}
}
export type RexPool = {
version
total_lent
total_unlent
total_rent
total_lendable
total_rex
namebid_proceeds
loan_num
};
export type RexPoolInterm = {
version
total_lent
total_unlent
total_rent
total_lendable
total_rex
namebid_proceeds
loan_num
};
export function mapRexPool(r) {
return {
version: r.version,
total_lent: new Asset(r.total_lent),
total_unlent: new Asset(r.total_unlent),
total_rent: new Asset(r.total_rent),
total_lendable: new Asset(r.total_lendable),
total_rex: new Asset(r.total_rex),
namebid_proceeds: new Asset(r.namebid_proceeds),
loan_num: r.loan_num.toString(),
}
}
export type RexReturnBuckets = {
version
return_buckets
};
export type RexReturnBucketsInterm = {
version
return_buckets
};
export function mapRexReturnBuckets(r) {
return {
version: r.version,
return_buckets: r.return_buckets.map(n => mapPairTimePointSecInt64(n)),
}
}
export type RexReturnPool = {
version
last_dist_time
pending_bucket_time
oldest_bucket_time
pending_bucket_proceeds
current_rate_of_increase
proceeds
};
export type RexReturnPoolInterm = {
version
last_dist_time
pending_bucket_time
oldest_bucket_time
pending_bucket_proceeds
current_rate_of_increase
proceeds
};
export function mapRexReturnPool(r) {
return {
version: r.version,
last_dist_time: r.last_dist_time,
pending_bucket_time: r.pending_bucket_time,
oldest_bucket_time: r.oldest_bucket_time,
pending_bucket_proceeds: r.pending_bucket_proceeds.toString(),
current_rate_of_increase: r.current_rate_of_increase.toString(),
proceeds: r.proceeds.toString(),
}
}
export type Rexexec = {
user
max
};
export type RexexecInterm = {
user
max
};
export function mapRexexec(r) {
return {
user: r.user,
max: r.max,
}
}
export type Rmvproducer = {
producer
};
export type RmvproducerInterm = {
producer
};
export function mapRmvproducer(r) {
return {
producer: r.producer,
}
}
export type Sellram = {
account
bytes
};
export type SellramInterm = {
account
bytes
};
export function mapSellram(r) {
return {
account: r.account,
bytes: r.bytes.toString(),
}
}
export type Sellrex = {
from
rex
};
export type SellrexInterm = {
from
rex
};
export function mapSellrex(r) {
return {
from: r.from,
rex: new Asset(r.rex),
}
}
export type Setabi = {
account
abi
};
export type SetabiInterm = {
account
abi
};
export function mapSetabi(r) {
return {
account: r.account,
abi: r.abi,
}
}
export type Setacctcpu = {
account
cpu_weight
};
export type SetacctcpuInterm = {
account
cpu_weight
};
export function mapSetacctcpu(r) {
return {
account: r.account,
cpu_weight: r.cpu_weight,
}
}
export type Setacctnet = {
account
net_weight
};
export type SetacctnetInterm = {
account
net_weight
};
export function mapSetacctnet(r) {
return {
account: r.account,
net_weight: r.net_weight,
}
}
export type Setacctram = {
account
ram_bytes
};
export type SetacctramInterm = {
account
ram_bytes
};
export function mapSetacctram(r) {
return {
account: r.account,
ram_bytes: r.ram_bytes,
}
}
export type Setalimits = {
account
ram_bytes
net_weight
cpu_weight
};
export type SetalimitsInterm = {
account
ram_bytes
net_weight
cpu_weight
};
export function mapSetalimits(r) {
return {
account: r.account,
ram_bytes: r.ram_bytes.toString(),
net_weight: r.net_weight.toString(),
cpu_weight: r.cpu_weight.toString(),
}
}
export type Setcode = {
account
vmtype
vmversion
code
};
export type SetcodeInterm = {
account
vmtype
vmversion
code
};
export function mapSetcode(r) {
return {
account: r.account,
vmtype: r.vmtype,
vmversion: r.vmversion,
code: r.code,
}
}
export type Setinflation = {
annual_rate
inflation_pay_factor
votepay_factor
};
export type SetinflationInterm = {
annual_rate
inflation_pay_factor
votepay_factor
};
export function mapSetinflation(r) {
return {
annual_rate: r.annual_rate.toString(),
inflation_pay_factor: r.inflation_pay_factor.toString(),
votepay_factor: r.votepay_factor.toString(),
}
}
export type Setparams = {
params
};
export type SetparamsInterm = {
params
};
export function mapSetparams(r) {
return {
params: mapBlockchainParameters(r.params),
}
}
export type Setpriv = {
account
is_priv
};
export type SetprivInterm = {
account
is_priv
};
export function mapSetpriv(r) {
return {
account: r.account,
is_priv: r.is_priv,
}
}
export type Setram = {
max_ram_size
};
export type SetramInterm = {
max_ram_size
};
export function mapSetram(r) {
return {
max_ram_size: r.max_ram_size.toString(),
}
}
export type Setramrate = {
bytes_per_block
};
export type SetramrateInterm = {
bytes_per_block
};
export function mapSetramrate(r) {
return {
bytes_per_block: r.bytes_per_block,
}
}
export type Setrex = {
balance
};
export type SetrexInterm = {
balance
};
export function mapSetrex(r) {
return {
balance: new Asset(r.balance),
}
}
export type Undelegatebw = {
from
receiver
unstake_net_quantity
unstake_cpu_quantity
};
export type UndelegatebwInterm = {
from
receiver
unstake_net_quantity
unstake_cpu_quantity
};
export function mapUndelegatebw(r) {
return {
from: r.from,
receiver: r.receiver,
unstake_net_quantity: new Asset(r.unstake_net_quantity),
unstake_cpu_quantity: new Asset(r.unstake_cpu_quantity),
}
}
export type Unlinkauth = {
account
code
type
};
export type UnlinkauthInterm = {
account
code
type
};
export function mapUnlinkauth(r) {
return {
account: r.account,
code: r.code,
type: r.type,
}
}
export type Unregprod = {
producer
};
export type UnregprodInterm = {
producer
};
export function mapUnregprod(r) {
return {
producer: r.producer,
}
}
export type Unstaketorex = {
owner
receiver
from_net
from_cpu
};
export type UnstaketorexInterm = {
owner
receiver
from_net
from_cpu
};
export function mapUnstaketorex(r) {
return {
owner: r.owner,
receiver: r.receiver,
from_net: new Asset(r.from_net),
from_cpu: new Asset(r.from_cpu),
}
}
export type Updateauth = {
account
permission
parent
auth
};
export type UpdateauthInterm = {
account
permission
parent
auth
};
export function mapUpdateauth(r) {
return {
account: r.account,
permission: r.permission,
parent: r.parent,
auth: mapAuthority(r.auth),
}
}
export type Updaterex = {
owner
};
export type UpdaterexInterm = {
owner
};
export function mapUpdaterex(r) {
return {
owner: r.owner,
}
}
export type Updtrevision = {
revision
};
export type UpdtrevisionInterm = {
revision
};
export function mapUpdtrevision(r) {
return {
revision: r.revision,
}
}
export type UserResources = {
owner
net_weight
cpu_weight
ram_bytes
};
export type UserResourcesInterm = {
owner
net_weight
cpu_weight
ram_bytes
};
export function mapUserResources(r) {
return {
owner: r.owner,
net_weight: new Asset(r.net_weight),
cpu_weight: new Asset(r.cpu_weight),
ram_bytes: r.ram_bytes.toString(),
}
}
export type Voteproducer = {
voter
proxy
producers
};
export type VoteproducerInterm = {
voter
proxy
producers
};
export function mapVoteproducer(r) {
return {
voter: r.voter,
proxy: r.proxy,
producers: r.producers,
}
}
export type VoterInfo = {
owner
proxy
producers
staked
last_vote_weight
proxied_vote_weight
is_proxy
flags1
reserved2
reserved3
};
export type VoterInfoInterm = {
owner
proxy
producers
staked
last_vote_weight
proxied_vote_weight
is_proxy
flags1
reserved2
reserved3
};
export function mapVoterInfo(r) {
return {
owner: r.owner,
proxy: r.proxy,
producers: r.producers,
staked: r.staked.toString(),
last_vote_weight: Number.parseFloat(r.last_vote_weight),
proxied_vote_weight: Number.parseFloat(r.proxied_vote_weight),
is_proxy: !!(r.is_proxy),
flags1: r.flags1,
reserved2: r.reserved2,
reserved3: new Asset(r.reserved3),
}
}
export type WaitWeight = {
wait_sec
weight
};
export type WaitWeightInterm = {
wait_sec
weight
};
export /* Example usages of 'mapWaitWeight' are shown below:
mapWaitWeight(n);
*/
function mapWaitWeight(r) {
return {
wait_sec: r.wait_sec,
weight: r.weight,
}
}
export type Withdraw = {
owner
amount
};
export type WithdrawInterm = {
owner
amount
};
export function mapWithdraw(r) {
return {
owner: r.owner,
amount: new Asset(r.amount),
}
}
export type AbiHashRows = {
more;
next_key;
rows;
};
export type AbiHashRowsInterm = {
more;
next_key;
rows;
};
export type BidRefundRows = {
more;
next_key;
rows;
};
export type BidRefundRowsInterm = {
more;
next_key;
rows;
};
export type RexLoanRows = {
more;
next_key;
rows;
};
export type RexLoanRowsInterm = {
more;
next_key;
rows;
};
export type DelegatedBandwidthRows = {
more;
next_key;
rows;
};
export type DelegatedBandwidthRowsInterm = {
more;
next_key;
rows;
};
export type EosioGlobalStateRows = {
more;
next_key;
rows;
};
export type EosioGlobalStateRowsInterm = {
more;
next_key;
rows;
};
export type EosioGlobalState2Rows = {
more;
next_key;
rows;
};
export type EosioGlobalState2RowsInterm = {
more;
next_key;
rows;
};
export type EosioGlobalState3Rows = {
more;
next_key;
rows;
};
export type EosioGlobalState3RowsInterm = {
more;
next_key;
rows;
};
export type EosioGlobalState4Rows = {
more;
next_key;
rows;
};
export type EosioGlobalState4RowsInterm = {
more;
next_key;
rows;
};
export type NameBidRows = {
more;
next_key;
rows;
};
export type NameBidRowsInterm = {
more;
next_key;
rows;
};
export type PowerupOrderRows = {
more;
next_key;
rows;
};
export type PowerupOrderRowsInterm = {
more;
next_key;
rows;
};
export type PowerupStateRows = {
more;
next_key;
rows;
};
export type PowerupStateRowsInterm = {
more;
next_key;
rows;
};
export type ProducerInfoRows = {
more;
next_key;
rows;
};
export type ProducerInfoRowsInterm = {
more;
next_key;
rows;
};
export type ProducerInfo2Rows = {
more;
next_key;
rows;
};
export type ProducerInfo2RowsInterm = {
more;
next_key;
rows;
};
export type ExchangeStateRows = {
more;
next_key;
rows;
};
export type ExchangeStateRowsInterm = {
more;
next_key;
rows;
};
export type RefundRequestRows = {
more;
next_key;
rows;
};
export type RefundRequestRowsInterm = {
more;
next_key;
rows;
};
export type RexReturnBucketsRows = {
more;
next_key;
rows;
};
export type RexReturnBucketsRowsInterm = {
more;
next_key;
rows;
};
export type RexBalanceRows = {
more;
next_key;
rows;
};
export type RexBalanceRowsInterm = {
more;
next_key;
rows;
};
export type RexFundRows = {
more;
next_key;
rows;
};
export type RexFundRowsInterm = {
more;
next_key;
rows;
};
export type RexPoolRows = {
more;
next_key;
rows;
};
export type RexPoolRowsInterm = {
more;
next_key;
rows;
};
export type RexOrderRows = {
more;
next_key;
rows;
};
export type RexOrderRowsInterm = {
more;
next_key;
rows;
};
export type RexReturnPoolRows = {
more;
next_key;
rows;
};
export type RexReturnPoolRowsInterm = {
more;
next_key;
rows;
};
export type UserResourcesRows = {
more;
next_key;
rows;
};
export type UserResourcesRowsInterm = {
more;
next_key;
rows;
};
export type VoterInfoRows = {
more;
next_key;
rows;
};
export type VoterInfoRowsInterm = {
more;
next_key;
rows;
};
|
df5014f90779ceb7e77829f2ba6f8409bb7a9d6f | 1,757 | ts | TypeScript | src/app/shared/helpers/functions.ts | ythouma/Toolbox | 2b8ffd667616cbfbdae39bde198cd342a7091767 | [
"Apache-2.0"
] | null | null | null | src/app/shared/helpers/functions.ts | ythouma/Toolbox | 2b8ffd667616cbfbdae39bde198cd342a7091767 | [
"Apache-2.0"
] | 1 | 2022-03-02T07:44:53.000Z | 2022-03-02T07:44:53.000Z | src/app/shared/helpers/functions.ts | ythouma/Toolbox | 2b8ffd667616cbfbdae39bde198cd342a7091767 | [
"Apache-2.0"
] | null | null | null | export function fromArray(data: [any] | any[]): any | undefined {
for (let json of data) {
if (json === undefined) {
return undefined;
}
}
return data;
}
export function containsObject(obj: any, list: [any] | any[]): boolean {
for (let i = 0; i < list.length; i++) {
if (list[i] === obj) {
return true;
}
}
return false;
}
export function containsSlashBeg(myUrl){
if (myUrl.substr(0, 1) === '/')
{
myUrl = myUrl.substr(1, myUrl.length);
}
return myUrl;
}
export function getRandomInt(min, max) {
// public random = Math.floor(Math.random() * (999999 - 100000)) + 100000;
return Math.floor(Math.random() * (max - min + 1)) + min;
}
export function parseJSON(str) {
try {
return JSON.parse(str);
} catch (e) {
return str;
}
}
export function Utf8Encode(data) {
data = data.replace(/\r\n/g, '\n');
let utftext = '';
for (let n = 0; n < data.length; n++) {
let c = data.charCodeAt(n);
if (c < 128) {
utftext += String.fromCharCode(c);
} else if ((c > 127) && (c < 2048)) {
utftext += String.fromCharCode((c >> 6) | 192);
utftext += String.fromCharCode((c & 63) | 128);
} else {
utftext += String.fromCharCode((c >> 12) | 224);
utftext += String.fromCharCode(((c >> 6) & 63) | 128);
utftext += String.fromCharCode((c & 63) | 128);
}
}
return utftext;
};
export function hexToRgbA(hex, opacity = 1){
let c;
if (/^#([A-Fa-f0-9]{3}){1,2}$/.test(hex)){
c = hex.substring(1).split('');
if (c.length === 3){
c = [c[0], c[0], c[1], c[1], c[2], c[2]];
}
c = '0x' + c.join('');
return 'rgba(' + [(c >> 16) & 255, (c >> 8) & 255, c & 255].join(',') + ',' + opacity + ')';
}
throw new Error('Bad Hex');
}
| 24.746479 | 98 | 0.538418 | 63 | 7 | 0 | 10 | 5 | 0 | 0 | 6 | 1 | 0 | 0 | 7 | 668 | 0.025449 | 0.007485 | 0 | 0 | 0 | 0.272727 | 0.045455 | 0.249645 | export function fromArray(data) {
for (let json of data) {
if (json === undefined) {
return undefined;
}
}
return data;
}
export function containsObject(obj, list) {
for (let i = 0; i < list.length; i++) {
if (list[i] === obj) {
return true;
}
}
return false;
}
export function containsSlashBeg(myUrl){
if (myUrl.substr(0, 1) === '/')
{
myUrl = myUrl.substr(1, myUrl.length);
}
return myUrl;
}
export function getRandomInt(min, max) {
// public random = Math.floor(Math.random() * (999999 - 100000)) + 100000;
return Math.floor(Math.random() * (max - min + 1)) + min;
}
export function parseJSON(str) {
try {
return JSON.parse(str);
} catch (e) {
return str;
}
}
export function Utf8Encode(data) {
data = data.replace(/\r\n/g, '\n');
let utftext = '';
for (let n = 0; n < data.length; n++) {
let c = data.charCodeAt(n);
if (c < 128) {
utftext += String.fromCharCode(c);
} else if ((c > 127) && (c < 2048)) {
utftext += String.fromCharCode((c >> 6) | 192);
utftext += String.fromCharCode((c & 63) | 128);
} else {
utftext += String.fromCharCode((c >> 12) | 224);
utftext += String.fromCharCode(((c >> 6) & 63) | 128);
utftext += String.fromCharCode((c & 63) | 128);
}
}
return utftext;
};
export function hexToRgbA(hex, opacity = 1){
let c;
if (/^#([A-Fa-f0-9]{3}){1,2}$/.test(hex)){
c = hex.substring(1).split('');
if (c.length === 3){
c = [c[0], c[0], c[1], c[1], c[2], c[2]];
}
c = '0x' + c.join('');
return 'rgba(' + [(c >> 16) & 255, (c >> 8) & 255, c & 255].join(',') + ',' + opacity + ')';
}
throw new Error('Bad Hex');
}
|
df56be00c3038a2e59ef67f17b495704517624d3 | 22,145 | ts | TypeScript | synth/filtering.ts | gridsol/jummbox | e3dad13baff54214e7b2ac7e3bd5eb612cc4b5ff | [
"MIT"
] | 2 | 2022-02-07T17:22:14.000Z | 2022-02-07T19:14:36.000Z | synth/filtering.ts | gridsol/jummbox | e3dad13baff54214e7b2ac7e3bd5eb612cc4b5ff | [
"MIT"
] | 2 | 2022-02-07T17:27:38.000Z | 2022-02-08T15:48:21.000Z | synth/filtering.ts | gridsol/jummbox | e3dad13baff54214e7b2ac7e3bd5eb612cc4b5ff | [
"MIT"
] | null | null | null | /*
This file contains code to compute digital audio filter coefficients based on
the desired type, cutoff frequency, and other parameters. You can use these
coefficients to apply the filter to audio samples. It also contains code to
analyze these filters, which is useful for graphically displaying their effects.
All of the filters in this file are known as "Infinite Impulse Response" or IIR
filters, because older output samples contribute feedback to newer output
samples and thus contribute to all future samples, although typically filters
are design to reduce the contribution of older samples over time.
Low-pass filters aka high-cut filters preserve audio signals below the cutoff
frequency, and attenuate audio signals above the cutoff frequency. High-pass
filters aka low-cut filters are the reverse. All-pass filters do not affect the
volume of the signal at all but induce phase changes above the cutoff frequency.
Peak/Notch filters maintain the volume on either side of the cutoff frequency,
but raise or lower the volume at that frequency.
The number of old samples used in the filter determines the "order" of the
filter. First-order filters generally have shallower slopes, and second-order
filters generally have steeper slopes and can be configured to "resonate",
meaning they have a louder peak at the cutoff frequency. This file contains
first-order filters and second-order filters, meaning one or two older samples
are involved, as well as the current input sample.
The class FilterCoefficients is defined lower in this file. You can use it to
set up a first order filter like this:
const cutoffRadiansPerSample: number = 2 * Math.PI * cutoffHz / sampleRate;
const filter: FilterCoefficients = new FilterCoefficients();
filter.lowPass1stOrderButterworth(cutoffRadiansPerSample);
// output sample coefficients are conventionally called a0, a1, etc. Note
// that a[0] is typically normalized to 1.0 and need not be used directly.
const a: number[] = filter.a;
// input sample coefficients are conventionally called b0, b1, etc
const b: number[] = filter.b;
// filter input samples, x[0] is the most recent, x[1] is the previous one, etc.
const x: number[] = [0, 0, 0];
// filter output samples, y[0] will be computed by the filter based on input
// samples and older output samples.
const y: number[] = [0, 0, 0];
Then to apply the first-order filter to samples inside a loop, using the current
input sample (x[0]) as well as previous input and output samples, do this:
// Compute the next output sample y[0]:
y[0] = b[0] * x[0] + b[1] * x[1] - a[1] * y[1];
// Remember the input and output samples for next time:
x[1] = x[0];
y[1] = y[0];
2nd order filters are similar, but have more parameters and require more old
samples:
// Compute the next output sample y[0]:
y[0] = b[0] * x[0] + b[1] * x[1] + b[2] * x[2] - a[1] * y[1] - a[2] * y[2];
// Remember the input and output samples for next time:
x[2] = x[1];
x[1] = x[0];
y[2] = y[1];
y[1] = y[0];
You can compose multiple filters into a higher order filter, although doing so
reduces the numerical stability of the filter:
filter3.combination(filter1, filter2);
// filter3.order will equal: filter1.order + filter2.order
// The number of coefficients in filter3.a and filter3.b will be: order + 1
This file also contains a class called FrequencyResponse. You can use it to
determine how much gain or attenuation a filter would apply to sounds at a
specific input frequency, as well as the phase offset:
const inputRadians: number = 2 * Math.PI * cutoffHz / sampleRate;
const response: FrequencyResponse = new FrequencyResponse();
response.analyze(filter, inputRadians);
const gainResponse = response.magnitude();
const phaseResponse = response.angle();
That's basically all you need to know to use this code, but I'll also explain
how the analysis works.
A first-order digital IIR filter is ordinarily implemented in a form like this:
output = inputCoeff * input + prevInputCoeff * prevInput - prevOutputCoeff * prevOutput;
If we adopt standard naming conventions for audio filters, this same code would
instead look like:
// x0 = current input, x1 = prevInput, y0 = current output, y1 = prevOutput
y0 = b0*x0 + b1*x1 - a1*y1;
Leaving behind the world of code for a moment and entering the world of algebra,
we can rewrite this equation by moving all the output terms to the left side,
and we can add a coefficient to the y0 term called a0 (which is typically
normalized to 1.0, which is why I didn't bother including it until now):
a0*y0 + a1*y1 = b0*x0 + b1*x1
This is known as the symmetrical form of the filter, and it will help us analyze
the impact of the filter on an input audio signal. Here's a lesson that helped
me understand the symmetrical form:
https://web.archive.org/web/20200626183458/http://123.physics.ucdavis.edu/week_5_files/filters/digital_filter.pdf
The end of that lesson introduces a concept called the "delay operator" which
looks like "z^-1", which (magically) turns a sample into the previous sample
when you multiply them. For example:
x0 * z^-1 = x1
The lesson doesn't explain how it actually works. Audio signals aren't always
predictable, which means that you generally can't do math on a single sample to
compute what the previous sample was. However, some audio signals ARE
predictable, such as pure sine waves. Fortunately, all audio signals can be
broken down into a sum of independent sine waves. We can pick one sine wave at a
time, and use it to analyze the filter's impact on waves at that frequency. In
practice, this tells us what the filter will do to unpredictable input samples
that contain a partial sine wave at that frequency.
Technically, you can't just use a single sine wave sample to determine the
previous sine wave sample, because each possible value is passed going upwards
and downwards once per period and the direction is ambigous. This is where we
need to move into the complex number domain, where the real and imaginary
components can provide enough information to compute the previous position on
the input signal. So now instead of talking about sine waves, we're talking
about waves where the imaginary component is a sine wave and the real component
is a cosine wave at the same frequency. Together, they trace around a unit
circle in the complex domain, and each sample is just a consistent rotation
applied to the previous sample. The "delay operator" described above, z^-1, is
this same rotation applied in reverse, and it can be computed as:
z^-1 = cos(radiansPerSample) - i * sin(radiansPerSample)
Math nerds may be interested to know that "Euler's formula" was used here, but
explaining what that means is probably beyond the scope of this documentation
aside from noting that a complex number on the unit circle represents a 2D
rotation that you can apply via multiplication.
Now we can rewrite the symmetrical form using the delay operator and algebra:
a0*y0 + a1*y0*z^-1 = b0*x0 + b1*x0*z^-1
y0 * (a0 + a1*z^-1) = x0 * (b0 + b1*z^-1)
y0 = x0 * (b0 + b1*z^-1) / (a0 + a1*z^-1)
y0 / x0 = (b0 + b1*z^-1) / (a0 + a1*z^-1)
That last equation expresses the relationship between the input and output
signals (y0/x0) in terms of the filter coefficients and delay operator. At this
point, the specific values of the input and output samples don't even matter!
This is called the "transfer function", and it's conventionally named "H(z)":
H(z) = (b0 + b1*z^-1) / (a0 + a1*z^-1)
If you plug in actual filter coefficients and express the delay operators as
complex numbers with the appropriate trigonometry functions, the transfer
function can be computed and produces a complex number that represents the
relationship between the input and output signals, whose magnitude represents
the volume gain (or attenuation) of signals at that frequency, and whose angle
represents how much phase shift is applied by the filter to signals at that
frequency.
(Note that in order to compute the transfer function, you'll need to do
something about the complex number in the denominator. It turns out you can turn
the denominator into a real number by multiplying both the numerator and
denominator by the complex conjugate of the denominator, which is just the
denominator with the imaginary component negated.)
Finally, I'll list some of the links that helped me understand filters and
provided some of the algorithms I that use here.
Here's where I found accurate 2nd order low-pass and high-pass digital filters:
https://web.archive.org/web/20120531011328/http://www.musicdsp.org/files/Audio-EQ-Cookbook.txt
This page is how I found a link to the cookbook article above. It claims these
filters are Butterworth filters:
http://web.archive.org/web/20191213120120/https://crypto.stanford.edu/~blynn/sound/analog.html
I found the first-order digital Butterworth filter coefficients at:
https://www.researchgate.net/publication/338022014_Digital_Implementation_of_Butterworth_First-Order_Filter_Type_IIR
This meta-paper helped me understand how to make 2nd order peak/notch filters:
https://web.archive.org/web/20170706085655/https://www.thesounddesign.com/MIO/EQ-Coefficients.pdf
BeepBox originally used simpler low-pass filters that I adapted from SFXR:
https://www.drpetter.se/project_sfxr.html
For low cutoff frequencies, the simpler filters and the Butterworth filters are
nearly identical, but when closer to the nyquist frequency the simpler filters
create extra resonance.
*/
export class FilterCoefficients {
public readonly a: number[] = [1.0]; // output coefficients (negated, keep a[0]=1)
public readonly b: number[] = [1.0]; // input coefficients
public order: number = 0;
public linearGain0thOrder(linearGain: number): void {
//a[0] = 1.0; // a0 should always be normalized to 1.0, no need to assign it directly.
this.b[0] = linearGain;
this.order = 0;
}
public lowPass1stOrderButterworth(cornerRadiansPerSample: number): void {
// First-order Butterworth low-pass filter according to:
// https://www.researchgate.net/publication/338022014_Digital_Implementation_of_Butterworth_First-Order_Filter_Type_IIR
// A butterworth filter is one where the amplitude response is equal to:
// 1 / √(1 + (freq / cutoffFreq)^(2 * order))
const g: number = 1.0 / Math.tan(cornerRadiansPerSample * 0.5);
const a0: number = 1.0 + g;
this.a[1] = (1.0 - g) / a0;
this.b[1] = this.b[0] = 1 / a0;
this.order = 1;
}
public lowPass1stOrderSimplified(cornerRadiansPerSample: number): void {
// The output of this filter is nearly identical to the 1st order
// Butterworth low-pass above, except if the cutoff is set to nyquist/3,
// then the output is the same as the input, and if the cutoff is higher
// than that, then the output actually resonates at high frequencies
// instead of attenuating.
// I'm guessing this filter was converted from analog to digital using
// the "matched z-transform" method instead of the "bilinear transform"
// method. The difference is that the bilinear transform warps
// frequencies so that the lowpass response of zero at analogue ∞hz maps
// to the digital nyquist frequency, whereas the matched z-transform
// preserves the frequency of the filter response but also adds the
// reflected response from above the nyquist frequency.
const g: number = 2.0 * Math.sin(cornerRadiansPerSample * 0.5);
this.a[1] = g - 1.0;
this.b[0] = g;
this.b[1] = 0.0;
/*
// Alternatively:
const g: number = 1.0 / (2.0 * Math.sin(cornerRadiansPerSample / 2));
const a0: number = g;
this.a[1] = (1.0 - g) / a0;
this.b[0] = 1.0 / a0;
this.b[1] = 0.0 / a0;
*/
this.order = 1;
}
public highPass1stOrderButterworth(cornerRadiansPerSample: number): void {
// First-order Butterworth high-pass filter according to:
// https://www.researchgate.net/publication/338022014_Digital_Implementation_of_Butterworth_First-Order_Filter_Type_IIR
const g: number = 1.0 / Math.tan(cornerRadiansPerSample * 0.5);
const a0: number = 1.0 + g;
this.a[1] = (1.0 - g) / a0;
this.b[0] = g / a0;
this.b[1] = -g / a0;
this.order = 1;
}
/*
public highPass1stOrderSimplified(cornerRadiansPerSample: number): void {
// The output of this filter is nearly identical to the 1st order
// Butterworth high-pass above, except it resonates when the cutoff
// appoaches the nyquist.
const g: number = 2.0 * Math.sin(cornerRadiansPerSample * 0.5);
this.a[1] = g - 1.0;
this.b[0] = 1.0;
this.b[1] = -1.0;
this.order = 1;
}
*/
public highShelf1stOrder(cornerRadiansPerSample: number, shelfLinearGain: number): void {
// I had trouble figuring this one out because I couldn't find any
// online algorithms that I understood. There are 3 degrees of freedom
// and I could narrow down a couple of them based on the desired gain at
// DC and nyquist, but getting the cutoff frequency correct took a
// little bit of trial and error in my attempts to interpret page 53 of
// this chapter: http://www.music.mcgill.ca/~ich/classes/FiltersChap2.pdf
// Obviously I don't fully understand the bilinear transform yet!
const tan: number = Math.tan(cornerRadiansPerSample * 0.5);
const sqrtGain: number = Math.sqrt(shelfLinearGain);
const g: number = (tan * sqrtGain - 1) / (tan * sqrtGain + 1.0);
const a0: number = 1.0;
this.a[1] = g / a0;
this.b[0] = (1.0 + g + shelfLinearGain * (1.0 - g)) / (2.0 * a0);
this.b[1] = (1.0 + g - shelfLinearGain * (1.0 - g)) / (2.0 * a0);
this.order = 1;
}
public allPass1stOrderInvertPhaseAbove(cornerRadiansPerSample: number): void {
const g: number = (Math.sin(cornerRadiansPerSample) - 1.0) / Math.cos(cornerRadiansPerSample);
this.a[1] = g;
this.b[0] = g;
this.b[1] = 1.0;
this.order = 1;
}
/*
// I haven't found a practical use for this version of the all pass filter.
// It seems to create a weird subharmonic when used in a delay feedback loop.
public allPass1stOrderInvertPhaseBelow(cornerRadiansPerSample: number): void {
const g: number = (Math.sin(cornerRadiansPerSample) - 1.0) / Math.cos(cornerRadiansPerSample);
this.a[1] = g;
this.b[0] = -g;
this.b[1] = -1.0;
this.order = 1;
}
*/
public allPass1stOrderFractionalDelay(delay: number) {
// Very similar to allPass1stOrderInvertPhaseAbove, but configured
// differently and for a different purpose! Useful for interpolating
// between samples in a delay line.
const g: number = (1.0 - delay) / (1.0 + delay);
this.a[1] = g;
this.b[0] = g;
this.b[1] = 1.0;
this.order = 1;
}
public lowPass2ndOrderButterworth(cornerRadiansPerSample: number, peakLinearGain: number): void {
// This is Butterworth if peakLinearGain=1/√2 according to:
// http://web.archive.org/web/20191213120120/https://crypto.stanford.edu/~blynn/sound/analog.html
// An interesting property is that if peakLinearGain=1/16 then the
// output resembles a first-order lowpass at a cutoff 4 octaves lower,
// although it gets distorted near the nyquist.
const alpha: number = Math.sin(cornerRadiansPerSample) / (2.0 * peakLinearGain);
const cos: number = Math.cos(cornerRadiansPerSample);
const a0: number = 1.0 + alpha;
this.a[1] = -2.0*cos / a0;
this.a[2] = (1 - alpha) / a0;
this.b[2] = this.b[0] = (1 - cos) / (2.0*a0);
this.b[1] = (1 - cos) / a0;
this.order = 2;
}
public lowPass2ndOrderSimplified(cornerRadiansPerSample: number, peakLinearGain: number): void {
// This filter is adapted from the one in the SFXR source code:
// https://www.drpetter.se/project_sfxr.html
// The output is nearly identical to the resonant Butterworth low-pass
// above, except it resonates too much when the cutoff appoaches the
// nyquist. If the resonance is set to zero and the cutoff is set to
// nyquist/3, then the output is the same as the input.
const g: number = 2.0 * Math.sin(cornerRadiansPerSample / 2.0);
const filterResonance: number = 1.0 - 1.0 / (2.0 * peakLinearGain);
const feedback: number = filterResonance + filterResonance / (1.0 - g);
this.a[1] = 2.0*g + (g - 1.0) * g*feedback - 2.0;
this.a[2] = (g - 1.0) * (g - g*feedback - 1.0);
this.b[0] = g*g;
this.b[1] = 0;
this.b[2] = 0;
this.order = 2;
}
public highPass2ndOrderButterworth(cornerRadiansPerSample: number, peakLinearGain: number): void {
const alpha: number = Math.sin(cornerRadiansPerSample) / (2 * peakLinearGain);
const cos: number = Math.cos(cornerRadiansPerSample);
const a0: number = 1.0 + alpha;
this.a[1] = -2.0*cos / a0;
this.a[2] = (1.0 - alpha) / a0;
this.b[2] = this.b[0] = (1.0 + cos) / (2.0*a0);
this.b[1] = -(1.0 + cos) / a0;
this.order = 2;
}
/*
public highPass2ndOrderSimplified(cornerRadiansPerSample: number, peakLinearGain: number): void {
const g: number = 2.0 * Math.sin(cornerRadiansPerSample * 0.5);
const filterResonance: number = 1.0 - 1.0 / (2.0 * peakLinearGain);
const feedback: number = filterResonance + filterResonance / (1.0 - g);
this.a[1] = 2.0*g + (g - 1.0) * g*feedback - 2.0;
this.a[2] = (g - 1.0) * (g - g*feedback - 1.0);
this.b[0] = 1.0;
this.b[1] = -2.0;
this.b[2] = 1.0;
this.order = 2;
}
*/
public peak2ndOrder(cornerRadiansPerSample: number, peakLinearGain: number, bandWidthScale: number): void {
const sqrtGain: number = Math.sqrt(peakLinearGain);
const bandWidth: number = bandWidthScale * cornerRadiansPerSample / (sqrtGain >= 1 ? sqrtGain : 1/sqrtGain);
//const bandWidth: number = bandWidthScale * cornerRadiansPerSample / Math.max(sqrtGain, 1.0);
const alpha: number = Math.tan(bandWidth * 0.5);
const a0: number = 1.0 + alpha / sqrtGain;
this.b[0] = (1.0 + alpha * sqrtGain) / a0;
this.b[1] = this.a[1] = -2.0 * Math.cos(cornerRadiansPerSample) / a0;
this.b[2] = (1.0 - alpha * sqrtGain) / a0;
this.a[2] = (1.0 - alpha / sqrtGain) / a0;
this.order = 2;
}
/*
// Create a higher order filter by combining two lower order filters.
// However, making high order filters in this manner results in instability.
// It is recommended to apply the 2nd order filters (biquads) in sequence instead.
public combination(filter1: FilterCoefficients, filter2: FilterCoefficients): void {
this.order = filter1.order + filter2.order;
for (let i: number = 0; i <= this.order; i++) {
this.a[i] = 0.0;
this.b[i] = 0.0;
}
for (let i: number = 0; i <= filter1.order; i++) {
for (let j: number = 0; j <= filter2.order; j++) {
this.a[i + j] += filter1.a[i] * filter2.a[j];
this.b[i + j] += filter1.b[i] * filter2.b[j];
}
}
}
public scaledDifference(other: FilterCoefficients, scale: number): void {
if (other.order != this.order) throw new Error();
for (let i: number = 0; i <= this.order; i++) {
this.a[i] = (this.a[i] - other.a[i]) * scale;
this.b[i] = (this.b[i] - other.b[i]) * scale;
}
}
public copy(other: FilterCoefficients): void {
this.order = other.order;
for (let i: number = 0; i <= this.order; i++) {
this.a[i] = other.a[i];
this.b[i] = other.b[i];
}
}
*/
}
export class FrequencyResponse {
public real: number = 0.0;
public imag: number = 0.0;
public denom: number = 1.0;
public analyze(filter: FilterCoefficients, radiansPerSample: number): void {
this.analyzeComplex(filter, Math.cos(radiansPerSample), Math.sin(radiansPerSample));
}
public analyzeComplex(filter: FilterCoefficients, real: number, imag: number): void {
const a: number[] = filter.a;
const b: number[] = filter.b;
const realZ1: number = real;
const imagZ1: number = -imag;
let realNum: number = b[0] + b[1] * realZ1;
let imagNum: number = b[1] * imagZ1;
let realDenom: number = 1.0 + a[1] * realZ1;
let imagDenom: number = a[1] * imagZ1;
let realZ: number = realZ1;
let imagZ: number = imagZ1;
for (let i: number = 2; i <= filter.order; i++) {
const realTemp: number = realZ * realZ1 - imagZ * imagZ1;
const imagTemp: number = realZ * imagZ1 + imagZ * realZ1;
realZ = realTemp;
imagZ = imagTemp;
realNum += b[i] * realZ;
imagNum += b[i] * imagZ;
realDenom += a[i] * realZ;
imagDenom += a[i] * imagZ;
}
this.denom = realDenom * realDenom + imagDenom * imagDenom;
this.real = realNum * realDenom + imagNum * imagDenom;
this.imag = imagNum * realDenom - realNum * imagDenom;
}
public magnitude(): number {
return Math.sqrt(this.real * this.real + this.imag * this.imag) / this.denom;
}
public angle(): number {
return Math.atan2(this.imag, this.real);
}
}
export class DynamicBiquadFilter {
public a1: number = 0.0;
public a2: number = 0.0;
public b0: number = 1.0;
public b1: number = 0.0;
public b2: number = 0.0;
public a1Delta: number = 0.0;
public a2Delta: number = 0.0;
public b0Delta: number = 0.0;
public b1Delta: number = 0.0;
public b2Delta: number = 0.0;
public output1: number = 0.0;
public output2: number = 0.0;
// Some filter types are more stable when interpolating between coefficients
// if the "b" coefficient interpolation is multiplicative. Don't enable this
// for filter types where the "b" coefficients might change sign!
public useMultiplicativeInputCoefficients: boolean = false;
public resetOutput(): void {
this.output1 = 0.0;
this.output2 = 0.0;
}
public loadCoefficientsWithGradient(start: FilterCoefficients, end: FilterCoefficients, deltaRate: number, useMultiplicativeInputCoefficients: boolean): void {
if (start.order != 2 || end.order != 2) throw new Error();
this.a1 = start.a[1];
this.a2 = start.a[2];
this.b0 = start.b[0];
this.b1 = start.b[1];
this.b2 = start.b[2];
this.a1Delta = (end.a[1] - start.a[1]) * deltaRate;
this.a2Delta = (end.a[2] - start.a[2]) * deltaRate;
if (useMultiplicativeInputCoefficients) {
this.b0Delta = Math.pow(end.b[0] / start.b[0], deltaRate);
this.b1Delta = Math.pow(end.b[1] / start.b[1], deltaRate);
this.b2Delta = Math.pow(end.b[2] / start.b[2], deltaRate);
} else {
this.b0Delta = (end.b[0] - start.b[0]) * deltaRate;
this.b1Delta = (end.b[1] - start.b[1]) * deltaRate;
this.b2Delta = (end.b[2] - start.b[2]) * deltaRate;
}
this.useMultiplicativeInputCoefficients = useMultiplicativeInputCoefficients;
}
}
| 43.764822 | 160 | 0.713705 | 175 | 17 | 0 | 26 | 37 | 19 | 1 | 0 | 94 | 3 | 0 | 6.823529 | 7,367 | 0.005837 | 0.005022 | 0.002579 | 0.000407 | 0 | 0 | 0.949495 | 0.199776 | /*
This file contains code to compute digital audio filter coefficients based on
the desired type, cutoff frequency, and other parameters. You can use these
coefficients to apply the filter to audio samples. It also contains code to
analyze these filters, which is useful for graphically displaying their effects.
All of the filters in this file are known as "Infinite Impulse Response" or IIR
filters, because older output samples contribute feedback to newer output
samples and thus contribute to all future samples, although typically filters
are design to reduce the contribution of older samples over time.
Low-pass filters aka high-cut filters preserve audio signals below the cutoff
frequency, and attenuate audio signals above the cutoff frequency. High-pass
filters aka low-cut filters are the reverse. All-pass filters do not affect the
volume of the signal at all but induce phase changes above the cutoff frequency.
Peak/Notch filters maintain the volume on either side of the cutoff frequency,
but raise or lower the volume at that frequency.
The number of old samples used in the filter determines the "order" of the
filter. First-order filters generally have shallower slopes, and second-order
filters generally have steeper slopes and can be configured to "resonate",
meaning they have a louder peak at the cutoff frequency. This file contains
first-order filters and second-order filters, meaning one or two older samples
are involved, as well as the current input sample.
The class FilterCoefficients is defined lower in this file. You can use it to
set up a first order filter like this:
const cutoffRadiansPerSample: number = 2 * Math.PI * cutoffHz / sampleRate;
const filter: FilterCoefficients = new FilterCoefficients();
filter.lowPass1stOrderButterworth(cutoffRadiansPerSample);
// output sample coefficients are conventionally called a0, a1, etc. Note
// that a[0] is typically normalized to 1.0 and need not be used directly.
const a: number[] = filter.a;
// input sample coefficients are conventionally called b0, b1, etc
const b: number[] = filter.b;
// filter input samples, x[0] is the most recent, x[1] is the previous one, etc.
const x: number[] = [0, 0, 0];
// filter output samples, y[0] will be computed by the filter based on input
// samples and older output samples.
const y: number[] = [0, 0, 0];
Then to apply the first-order filter to samples inside a loop, using the current
input sample (x[0]) as well as previous input and output samples, do this:
// Compute the next output sample y[0]:
y[0] = b[0] * x[0] + b[1] * x[1] - a[1] * y[1];
// Remember the input and output samples for next time:
x[1] = x[0];
y[1] = y[0];
2nd order filters are similar, but have more parameters and require more old
samples:
// Compute the next output sample y[0]:
y[0] = b[0] * x[0] + b[1] * x[1] + b[2] * x[2] - a[1] * y[1] - a[2] * y[2];
// Remember the input and output samples for next time:
x[2] = x[1];
x[1] = x[0];
y[2] = y[1];
y[1] = y[0];
You can compose multiple filters into a higher order filter, although doing so
reduces the numerical stability of the filter:
filter3.combination(filter1, filter2);
// filter3.order will equal: filter1.order + filter2.order
// The number of coefficients in filter3.a and filter3.b will be: order + 1
This file also contains a class called FrequencyResponse. You can use it to
determine how much gain or attenuation a filter would apply to sounds at a
specific input frequency, as well as the phase offset:
const inputRadians: number = 2 * Math.PI * cutoffHz / sampleRate;
const response: FrequencyResponse = new FrequencyResponse();
response.analyze(filter, inputRadians);
const gainResponse = response.magnitude();
const phaseResponse = response.angle();
That's basically all you need to know to use this code, but I'll also explain
how the analysis works.
A first-order digital IIR filter is ordinarily implemented in a form like this:
output = inputCoeff * input + prevInputCoeff * prevInput - prevOutputCoeff * prevOutput;
If we adopt standard naming conventions for audio filters, this same code would
instead look like:
// x0 = current input, x1 = prevInput, y0 = current output, y1 = prevOutput
y0 = b0*x0 + b1*x1 - a1*y1;
Leaving behind the world of code for a moment and entering the world of algebra,
we can rewrite this equation by moving all the output terms to the left side,
and we can add a coefficient to the y0 term called a0 (which is typically
normalized to 1.0, which is why I didn't bother including it until now):
a0*y0 + a1*y1 = b0*x0 + b1*x1
This is known as the symmetrical form of the filter, and it will help us analyze
the impact of the filter on an input audio signal. Here's a lesson that helped
me understand the symmetrical form:
https://web.archive.org/web/20200626183458/http://123.physics.ucdavis.edu/week_5_files/filters/digital_filter.pdf
The end of that lesson introduces a concept called the "delay operator" which
looks like "z^-1", which (magically) turns a sample into the previous sample
when you multiply them. For example:
x0 * z^-1 = x1
The lesson doesn't explain how it actually works. Audio signals aren't always
predictable, which means that you generally can't do math on a single sample to
compute what the previous sample was. However, some audio signals ARE
predictable, such as pure sine waves. Fortunately, all audio signals can be
broken down into a sum of independent sine waves. We can pick one sine wave at a
time, and use it to analyze the filter's impact on waves at that frequency. In
practice, this tells us what the filter will do to unpredictable input samples
that contain a partial sine wave at that frequency.
Technically, you can't just use a single sine wave sample to determine the
previous sine wave sample, because each possible value is passed going upwards
and downwards once per period and the direction is ambigous. This is where we
need to move into the complex number domain, where the real and imaginary
components can provide enough information to compute the previous position on
the input signal. So now instead of talking about sine waves, we're talking
about waves where the imaginary component is a sine wave and the real component
is a cosine wave at the same frequency. Together, they trace around a unit
circle in the complex domain, and each sample is just a consistent rotation
applied to the previous sample. The "delay operator" described above, z^-1, is
this same rotation applied in reverse, and it can be computed as:
z^-1 = cos(radiansPerSample) - i * sin(radiansPerSample)
Math nerds may be interested to know that "Euler's formula" was used here, but
explaining what that means is probably beyond the scope of this documentation
aside from noting that a complex number on the unit circle represents a 2D
rotation that you can apply via multiplication.
Now we can rewrite the symmetrical form using the delay operator and algebra:
a0*y0 + a1*y0*z^-1 = b0*x0 + b1*x0*z^-1
y0 * (a0 + a1*z^-1) = x0 * (b0 + b1*z^-1)
y0 = x0 * (b0 + b1*z^-1) / (a0 + a1*z^-1)
y0 / x0 = (b0 + b1*z^-1) / (a0 + a1*z^-1)
That last equation expresses the relationship between the input and output
signals (y0/x0) in terms of the filter coefficients and delay operator. At this
point, the specific values of the input and output samples don't even matter!
This is called the "transfer function", and it's conventionally named "H(z)":
H(z) = (b0 + b1*z^-1) / (a0 + a1*z^-1)
If you plug in actual filter coefficients and express the delay operators as
complex numbers with the appropriate trigonometry functions, the transfer
function can be computed and produces a complex number that represents the
relationship between the input and output signals, whose magnitude represents
the volume gain (or attenuation) of signals at that frequency, and whose angle
represents how much phase shift is applied by the filter to signals at that
frequency.
(Note that in order to compute the transfer function, you'll need to do
something about the complex number in the denominator. It turns out you can turn
the denominator into a real number by multiplying both the numerator and
denominator by the complex conjugate of the denominator, which is just the
denominator with the imaginary component negated.)
Finally, I'll list some of the links that helped me understand filters and
provided some of the algorithms I that use here.
Here's where I found accurate 2nd order low-pass and high-pass digital filters:
https://web.archive.org/web/20120531011328/http://www.musicdsp.org/files/Audio-EQ-Cookbook.txt
This page is how I found a link to the cookbook article above. It claims these
filters are Butterworth filters:
http://web.archive.org/web/20191213120120/https://crypto.stanford.edu/~blynn/sound/analog.html
I found the first-order digital Butterworth filter coefficients at:
https://www.researchgate.net/publication/338022014_Digital_Implementation_of_Butterworth_First-Order_Filter_Type_IIR
This meta-paper helped me understand how to make 2nd order peak/notch filters:
https://web.archive.org/web/20170706085655/https://www.thesounddesign.com/MIO/EQ-Coefficients.pdf
BeepBox originally used simpler low-pass filters that I adapted from SFXR:
https://www.drpetter.se/project_sfxr.html
For low cutoff frequencies, the simpler filters and the Butterworth filters are
nearly identical, but when closer to the nyquist frequency the simpler filters
create extra resonance.
*/
export class FilterCoefficients {
public readonly a = [1.0]; // output coefficients (negated, keep a[0]=1)
public readonly b = [1.0]; // input coefficients
public order = 0;
public linearGain0thOrder(linearGain) {
//a[0] = 1.0; // a0 should always be normalized to 1.0, no need to assign it directly.
this.b[0] = linearGain;
this.order = 0;
}
public lowPass1stOrderButterworth(cornerRadiansPerSample) {
// First-order Butterworth low-pass filter according to:
// https://www.researchgate.net/publication/338022014_Digital_Implementation_of_Butterworth_First-Order_Filter_Type_IIR
// A butterworth filter is one where the amplitude response is equal to:
// 1 / √(1 + (freq / cutoffFreq)^(2 * order))
const g = 1.0 / Math.tan(cornerRadiansPerSample * 0.5);
const a0 = 1.0 + g;
this.a[1] = (1.0 - g) / a0;
this.b[1] = this.b[0] = 1 / a0;
this.order = 1;
}
public lowPass1stOrderSimplified(cornerRadiansPerSample) {
// The output of this filter is nearly identical to the 1st order
// Butterworth low-pass above, except if the cutoff is set to nyquist/3,
// then the output is the same as the input, and if the cutoff is higher
// than that, then the output actually resonates at high frequencies
// instead of attenuating.
// I'm guessing this filter was converted from analog to digital using
// the "matched z-transform" method instead of the "bilinear transform"
// method. The difference is that the bilinear transform warps
// frequencies so that the lowpass response of zero at analogue ∞hz maps
// to the digital nyquist frequency, whereas the matched z-transform
// preserves the frequency of the filter response but also adds the
// reflected response from above the nyquist frequency.
const g = 2.0 * Math.sin(cornerRadiansPerSample * 0.5);
this.a[1] = g - 1.0;
this.b[0] = g;
this.b[1] = 0.0;
/*
// Alternatively:
const g: number = 1.0 / (2.0 * Math.sin(cornerRadiansPerSample / 2));
const a0: number = g;
this.a[1] = (1.0 - g) / a0;
this.b[0] = 1.0 / a0;
this.b[1] = 0.0 / a0;
*/
this.order = 1;
}
public highPass1stOrderButterworth(cornerRadiansPerSample) {
// First-order Butterworth high-pass filter according to:
// https://www.researchgate.net/publication/338022014_Digital_Implementation_of_Butterworth_First-Order_Filter_Type_IIR
const g = 1.0 / Math.tan(cornerRadiansPerSample * 0.5);
const a0 = 1.0 + g;
this.a[1] = (1.0 - g) / a0;
this.b[0] = g / a0;
this.b[1] = -g / a0;
this.order = 1;
}
/*
public highPass1stOrderSimplified(cornerRadiansPerSample: number): void {
// The output of this filter is nearly identical to the 1st order
// Butterworth high-pass above, except it resonates when the cutoff
// appoaches the nyquist.
const g: number = 2.0 * Math.sin(cornerRadiansPerSample * 0.5);
this.a[1] = g - 1.0;
this.b[0] = 1.0;
this.b[1] = -1.0;
this.order = 1;
}
*/
public highShelf1stOrder(cornerRadiansPerSample, shelfLinearGain) {
// I had trouble figuring this one out because I couldn't find any
// online algorithms that I understood. There are 3 degrees of freedom
// and I could narrow down a couple of them based on the desired gain at
// DC and nyquist, but getting the cutoff frequency correct took a
// little bit of trial and error in my attempts to interpret page 53 of
// this chapter: http://www.music.mcgill.ca/~ich/classes/FiltersChap2.pdf
// Obviously I don't fully understand the bilinear transform yet!
const tan = Math.tan(cornerRadiansPerSample * 0.5);
const sqrtGain = Math.sqrt(shelfLinearGain);
const g = (tan * sqrtGain - 1) / (tan * sqrtGain + 1.0);
const a0 = 1.0;
this.a[1] = g / a0;
this.b[0] = (1.0 + g + shelfLinearGain * (1.0 - g)) / (2.0 * a0);
this.b[1] = (1.0 + g - shelfLinearGain * (1.0 - g)) / (2.0 * a0);
this.order = 1;
}
public allPass1stOrderInvertPhaseAbove(cornerRadiansPerSample) {
const g = (Math.sin(cornerRadiansPerSample) - 1.0) / Math.cos(cornerRadiansPerSample);
this.a[1] = g;
this.b[0] = g;
this.b[1] = 1.0;
this.order = 1;
}
/*
// I haven't found a practical use for this version of the all pass filter.
// It seems to create a weird subharmonic when used in a delay feedback loop.
public allPass1stOrderInvertPhaseBelow(cornerRadiansPerSample: number): void {
const g: number = (Math.sin(cornerRadiansPerSample) - 1.0) / Math.cos(cornerRadiansPerSample);
this.a[1] = g;
this.b[0] = -g;
this.b[1] = -1.0;
this.order = 1;
}
*/
public allPass1stOrderFractionalDelay(delay) {
// Very similar to allPass1stOrderInvertPhaseAbove, but configured
// differently and for a different purpose! Useful for interpolating
// between samples in a delay line.
const g = (1.0 - delay) / (1.0 + delay);
this.a[1] = g;
this.b[0] = g;
this.b[1] = 1.0;
this.order = 1;
}
public lowPass2ndOrderButterworth(cornerRadiansPerSample, peakLinearGain) {
// This is Butterworth if peakLinearGain=1/√2 according to:
// http://web.archive.org/web/20191213120120/https://crypto.stanford.edu/~blynn/sound/analog.html
// An interesting property is that if peakLinearGain=1/16 then the
// output resembles a first-order lowpass at a cutoff 4 octaves lower,
// although it gets distorted near the nyquist.
const alpha = Math.sin(cornerRadiansPerSample) / (2.0 * peakLinearGain);
const cos = Math.cos(cornerRadiansPerSample);
const a0 = 1.0 + alpha;
this.a[1] = -2.0*cos / a0;
this.a[2] = (1 - alpha) / a0;
this.b[2] = this.b[0] = (1 - cos) / (2.0*a0);
this.b[1] = (1 - cos) / a0;
this.order = 2;
}
public lowPass2ndOrderSimplified(cornerRadiansPerSample, peakLinearGain) {
// This filter is adapted from the one in the SFXR source code:
// https://www.drpetter.se/project_sfxr.html
// The output is nearly identical to the resonant Butterworth low-pass
// above, except it resonates too much when the cutoff appoaches the
// nyquist. If the resonance is set to zero and the cutoff is set to
// nyquist/3, then the output is the same as the input.
const g = 2.0 * Math.sin(cornerRadiansPerSample / 2.0);
const filterResonance = 1.0 - 1.0 / (2.0 * peakLinearGain);
const feedback = filterResonance + filterResonance / (1.0 - g);
this.a[1] = 2.0*g + (g - 1.0) * g*feedback - 2.0;
this.a[2] = (g - 1.0) * (g - g*feedback - 1.0);
this.b[0] = g*g;
this.b[1] = 0;
this.b[2] = 0;
this.order = 2;
}
public highPass2ndOrderButterworth(cornerRadiansPerSample, peakLinearGain) {
const alpha = Math.sin(cornerRadiansPerSample) / (2 * peakLinearGain);
const cos = Math.cos(cornerRadiansPerSample);
const a0 = 1.0 + alpha;
this.a[1] = -2.0*cos / a0;
this.a[2] = (1.0 - alpha) / a0;
this.b[2] = this.b[0] = (1.0 + cos) / (2.0*a0);
this.b[1] = -(1.0 + cos) / a0;
this.order = 2;
}
/*
public highPass2ndOrderSimplified(cornerRadiansPerSample: number, peakLinearGain: number): void {
const g: number = 2.0 * Math.sin(cornerRadiansPerSample * 0.5);
const filterResonance: number = 1.0 - 1.0 / (2.0 * peakLinearGain);
const feedback: number = filterResonance + filterResonance / (1.0 - g);
this.a[1] = 2.0*g + (g - 1.0) * g*feedback - 2.0;
this.a[2] = (g - 1.0) * (g - g*feedback - 1.0);
this.b[0] = 1.0;
this.b[1] = -2.0;
this.b[2] = 1.0;
this.order = 2;
}
*/
public peak2ndOrder(cornerRadiansPerSample, peakLinearGain, bandWidthScale) {
const sqrtGain = Math.sqrt(peakLinearGain);
const bandWidth = bandWidthScale * cornerRadiansPerSample / (sqrtGain >= 1 ? sqrtGain : 1/sqrtGain);
//const bandWidth: number = bandWidthScale * cornerRadiansPerSample / Math.max(sqrtGain, 1.0);
const alpha = Math.tan(bandWidth * 0.5);
const a0 = 1.0 + alpha / sqrtGain;
this.b[0] = (1.0 + alpha * sqrtGain) / a0;
this.b[1] = this.a[1] = -2.0 * Math.cos(cornerRadiansPerSample) / a0;
this.b[2] = (1.0 - alpha * sqrtGain) / a0;
this.a[2] = (1.0 - alpha / sqrtGain) / a0;
this.order = 2;
}
/*
// Create a higher order filter by combining two lower order filters.
// However, making high order filters in this manner results in instability.
// It is recommended to apply the 2nd order filters (biquads) in sequence instead.
public combination(filter1: FilterCoefficients, filter2: FilterCoefficients): void {
this.order = filter1.order + filter2.order;
for (let i: number = 0; i <= this.order; i++) {
this.a[i] = 0.0;
this.b[i] = 0.0;
}
for (let i: number = 0; i <= filter1.order; i++) {
for (let j: number = 0; j <= filter2.order; j++) {
this.a[i + j] += filter1.a[i] * filter2.a[j];
this.b[i + j] += filter1.b[i] * filter2.b[j];
}
}
}
public scaledDifference(other: FilterCoefficients, scale: number): void {
if (other.order != this.order) throw new Error();
for (let i: number = 0; i <= this.order; i++) {
this.a[i] = (this.a[i] - other.a[i]) * scale;
this.b[i] = (this.b[i] - other.b[i]) * scale;
}
}
public copy(other: FilterCoefficients): void {
this.order = other.order;
for (let i: number = 0; i <= this.order; i++) {
this.a[i] = other.a[i];
this.b[i] = other.b[i];
}
}
*/
}
export class FrequencyResponse {
public real = 0.0;
public imag = 0.0;
public denom = 1.0;
public analyze(filter, radiansPerSample) {
this.analyzeComplex(filter, Math.cos(radiansPerSample), Math.sin(radiansPerSample));
}
public analyzeComplex(filter, real, imag) {
const a = filter.a;
const b = filter.b;
const realZ1 = real;
const imagZ1 = -imag;
let realNum = b[0] + b[1] * realZ1;
let imagNum = b[1] * imagZ1;
let realDenom = 1.0 + a[1] * realZ1;
let imagDenom = a[1] * imagZ1;
let realZ = realZ1;
let imagZ = imagZ1;
for (let i = 2; i <= filter.order; i++) {
const realTemp = realZ * realZ1 - imagZ * imagZ1;
const imagTemp = realZ * imagZ1 + imagZ * realZ1;
realZ = realTemp;
imagZ = imagTemp;
realNum += b[i] * realZ;
imagNum += b[i] * imagZ;
realDenom += a[i] * realZ;
imagDenom += a[i] * imagZ;
}
this.denom = realDenom * realDenom + imagDenom * imagDenom;
this.real = realNum * realDenom + imagNum * imagDenom;
this.imag = imagNum * realDenom - realNum * imagDenom;
}
public magnitude() {
return Math.sqrt(this.real * this.real + this.imag * this.imag) / this.denom;
}
public angle() {
return Math.atan2(this.imag, this.real);
}
}
export class DynamicBiquadFilter {
public a1 = 0.0;
public a2 = 0.0;
public b0 = 1.0;
public b1 = 0.0;
public b2 = 0.0;
public a1Delta = 0.0;
public a2Delta = 0.0;
public b0Delta = 0.0;
public b1Delta = 0.0;
public b2Delta = 0.0;
public output1 = 0.0;
public output2 = 0.0;
// Some filter types are more stable when interpolating between coefficients
// if the "b" coefficient interpolation is multiplicative. Don't enable this
// for filter types where the "b" coefficients might change sign!
public useMultiplicativeInputCoefficients = false;
public resetOutput() {
this.output1 = 0.0;
this.output2 = 0.0;
}
public loadCoefficientsWithGradient(start, end, deltaRate, useMultiplicativeInputCoefficients) {
if (start.order != 2 || end.order != 2) throw new Error();
this.a1 = start.a[1];
this.a2 = start.a[2];
this.b0 = start.b[0];
this.b1 = start.b[1];
this.b2 = start.b[2];
this.a1Delta = (end.a[1] - start.a[1]) * deltaRate;
this.a2Delta = (end.a[2] - start.a[2]) * deltaRate;
if (useMultiplicativeInputCoefficients) {
this.b0Delta = Math.pow(end.b[0] / start.b[0], deltaRate);
this.b1Delta = Math.pow(end.b[1] / start.b[1], deltaRate);
this.b2Delta = Math.pow(end.b[2] / start.b[2], deltaRate);
} else {
this.b0Delta = (end.b[0] - start.b[0]) * deltaRate;
this.b1Delta = (end.b[1] - start.b[1]) * deltaRate;
this.b2Delta = (end.b[2] - start.b[2]) * deltaRate;
}
this.useMultiplicativeInputCoefficients = useMultiplicativeInputCoefficients;
}
}
|
df65c376614800d5166e8224dfe9c10d61752ed0 | 2,410 | ts | TypeScript | .history/src/common/util/util_20220130202625.ts | lzijia/recordPlan | 94ec73ee7c6a42fc2547065af26ad1258e7a7ff2 | [
"Apache-2.0"
] | 1 | 2022-01-21T14:42:28.000Z | 2022-01-21T14:42:28.000Z | .history/src/common/util/util_20220130202625.ts | lzijia/recordPlan | 94ec73ee7c6a42fc2547065af26ad1258e7a7ff2 | [
"Apache-2.0"
] | null | null | null | .history/src/common/util/util_20220130202625.ts | lzijia/recordPlan | 94ec73ee7c6a42fc2547065af26ad1258e7a7ff2 | [
"Apache-2.0"
] | null | null | null | //要解码的base64
export function base64ToString(data: string) {
/** Convert Base64 data to a string */
var toBinaryTable = [-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 62, -1, -1, -1, 63,
52, 53, 54, 55, 56, 57, 58, 59, 60, 61, -1, -1, -1, 0, -1, -1, -1, 0, 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, -1, -1, -1, -1, -1, -1, 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, -1, -1, -1, -1, -1
];
var result = '';
var leftbits = 0;
var leftdata = 0;
for (var i = 0; i < data.length; i++) {
var c = toBinaryTable[data.charCodeAt(i) & 0x7f];
var padding = (data.charCodeAt(i) == '='.charCodeAt(0));
if (c == -1) continue;
leftdata = (leftdata << 6) | c;
leftbits += 6;
if (leftbits >= 8) {
leftbits -= 8;
if (!padding)
result += String.fromCharCode((leftdata >> leftbits) & 0xff);
leftdata &= (1 << leftbits) - 1;
}
}
return result;
}
//字符串转换为base64
export function toBase64(data: string) {
var toBase64Table = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/';
var base64Pad = '=';
var result = '';
var length = data.length;
var i;
// Convert every three bytes to 4 ascii characters.
for (i = 0; i < (length - 2); i += 3) {
result += toBase64Table[data.charCodeAt(i) >> 2];
result += toBase64Table[((data.charCodeAt(i) & 0x03) << 4) + (data.charCodeAt(i + 1) >> 4)];
result += toBase64Table[((data.charCodeAt(i + 1) & 0x0f) << 2) + (data.charCodeAt(i + 2) >> 6)];
result += toBase64Table[data.charCodeAt(i + 2) & 0x3f];
}
// Convert the remaining 1 or 2 bytes, pad out to 4 characters.
if (length % 3) {
i = length - (length % 3);
result += toBase64Table[data.charCodeAt(i) >> 2];
if ((length % 3) == 2) {
result += toBase64Table[((data.charCodeAt(i) & 0x03) << 4) + (data.charCodeAt(i + 1) >> 4)];
result += toBase64Table[(data.charCodeAt(i + 1) & 0x0f) << 2];
result += base64Pad;
} else {
result += toBase64Table[(data.charCodeAt(i) & 0x03) << 4];
result += base64Pad + base64Pad;
}
}
return result;
}
| 40.847458 | 214 | 0.519502 | 50 | 2 | 0 | 2 | 12 | 0 | 0 | 0 | 2 | 0 | 0 | 23 | 1,091 | 0.003666 | 0.010999 | 0 | 0 | 0 | 0 | 0.125 | 0.214447 | //要解码的base64
export function base64ToString(data) {
/** Convert Base64 data to a string */
var toBinaryTable = [-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 62, -1, -1, -1, 63,
52, 53, 54, 55, 56, 57, 58, 59, 60, 61, -1, -1, -1, 0, -1, -1, -1, 0, 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, -1, -1, -1, -1, -1, -1, 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, -1, -1, -1, -1, -1
];
var result = '';
var leftbits = 0;
var leftdata = 0;
for (var i = 0; i < data.length; i++) {
var c = toBinaryTable[data.charCodeAt(i) & 0x7f];
var padding = (data.charCodeAt(i) == '='.charCodeAt(0));
if (c == -1) continue;
leftdata = (leftdata << 6) | c;
leftbits += 6;
if (leftbits >= 8) {
leftbits -= 8;
if (!padding)
result += String.fromCharCode((leftdata >> leftbits) & 0xff);
leftdata &= (1 << leftbits) - 1;
}
}
return result;
}
//字符串转换为base64
export function toBase64(data) {
var toBase64Table = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/';
var base64Pad = '=';
var result = '';
var length = data.length;
var i;
// Convert every three bytes to 4 ascii characters.
for (i = 0; i < (length - 2); i += 3) {
result += toBase64Table[data.charCodeAt(i) >> 2];
result += toBase64Table[((data.charCodeAt(i) & 0x03) << 4) + (data.charCodeAt(i + 1) >> 4)];
result += toBase64Table[((data.charCodeAt(i + 1) & 0x0f) << 2) + (data.charCodeAt(i + 2) >> 6)];
result += toBase64Table[data.charCodeAt(i + 2) & 0x3f];
}
// Convert the remaining 1 or 2 bytes, pad out to 4 characters.
if (length % 3) {
i = length - (length % 3);
result += toBase64Table[data.charCodeAt(i) >> 2];
if ((length % 3) == 2) {
result += toBase64Table[((data.charCodeAt(i) & 0x03) << 4) + (data.charCodeAt(i + 1) >> 4)];
result += toBase64Table[(data.charCodeAt(i + 1) & 0x0f) << 2];
result += base64Pad;
} else {
result += toBase64Table[(data.charCodeAt(i) & 0x03) << 4];
result += base64Pad + base64Pad;
}
}
return result;
}
|
dff56085aa8c60f51846792e37f02b9735834ba8 | 2,594 | ts | TypeScript | src/app/shared/share-func.ts | luca-98/cma-client-angular | 1a2124ef5b1932ba2a2b478c1742e51bbfb6db6c | [
"MIT"
] | 1 | 2021-12-31T07:21:45.000Z | 2021-12-31T07:21:45.000Z | src/app/shared/share-func.ts | luca-98/cma-client-angular | 1a2124ef5b1932ba2a2b478c1742e51bbfb6db6c | [
"MIT"
] | null | null | null | src/app/shared/share-func.ts | luca-98/cma-client-angular | 1a2124ef5b1932ba2a2b478c1742e51bbfb6db6c | [
"MIT"
] | null | null | null | export function removeSignAndLowerCase(str: string): string {
str = str.trim();
str = str.toLowerCase();
str = str.replace(/à|á|ạ|ả|ã|â|ầ|ấ|ậ|ẩ|ẫ|ă|ằ|ắ|ặ|ẳ|ẵ/g, 'a');
str = str.replace(/è|é|ẹ|ẻ|ẽ|ê|ề|ế|ệ|ể|ễ/g, 'e');
str = str.replace(/ì|í|ị|ỉ|ĩ/g, 'i');
str = str.replace(/ò|ó|ọ|ỏ|õ|ô|ồ|ố|ộ|ổ|ỗ|ơ|ờ|ớ|ợ|ở|ỡ/g, 'o');
str = str.replace(/ù|ú|ụ|ủ|ũ|ư|ừ|ứ|ự|ử|ữ/g, 'u');
str = str.replace(/ỳ|ý|ỵ|ỷ|ỹ/g, 'y');
str = str.replace(/đ/g, 'd');
str = str.replace(/À|Á|Ạ|Ả|Ã|Â|Ầ|Ấ|Ậ|Ẩ|Ẫ|Ă|Ằ|Ắ|Ặ|Ẳ|Ẵ/g, 'a');
str = str.replace(/È|É|Ẹ|Ẻ|Ẽ|Ê|Ề|Ế|Ệ|Ể|Ễ/g, 'e');
str = str.replace(/Ì|Í|Ị|Ỉ|Ĩ/g, 'i');
str = str.replace(/Ò|Ó|Ọ|Ỏ|Õ|Ô|Ồ|Ố|Ộ|Ổ|Ỗ|Ơ|Ờ|Ớ|Ợ|Ở|Ỡ/g, 'o');
str = str.replace(/Ù|Ú|Ụ|Ủ|Ũ|Ư|Ừ|Ứ|Ự|Ử|Ữ/g, 'u');
str = str.replace(/Ỳ|Ý|Ỵ|Ỷ|Ỹ/g, 'y');
str = str.replace(/Đ/g, 'd');
str = str.toLowerCase();
return str;
}
export function propValToString(obj: any): any {
for (const property in obj) {
if (typeof obj[property] === 'object' && obj[property] !== null) {
obj[property] = propValToString(obj[property]);
break;
}
if (!(typeof obj[property] === 'string' || obj[property] instanceof String) && obj[property] !== null) {
obj[property] = obj[property].toString();
}
}
return obj;
}
export function clearNullOfObject(obj: any): any {
for (const property in obj) {
if (typeof obj[property] === 'object' && obj[property] !== null) {
obj[property] = clearNullOfObject(obj[property]);
break;
}
if (obj[property] === null || obj[property] === undefined) {
obj[property] = '';
}
}
return obj;
}
// convert dateTime object to dd/MM/yyyy
export function convertDateToNormal(d: any): string {
if (!d) {
return d;
}
const date = d._d.getDate();
const month = d._d.getMonth() + 1;
const year = d._d.getFullYear();
return date + '/' + month + '/' + year;
}
// highlight text matching in autocomplate
// rawString: string send to server to search
// resultString: string result server sent to client
export function buildHighlightString(rawString: string, resultString: string) {
const rawParse = removeSignAndLowerCase(rawString);
const resultParse = removeSignAndLowerCase(resultString);
const indexStart = resultParse.indexOf(rawParse);
const indexEnd = indexStart + rawParse.length;
return '<p>' + resultString.substring(0, indexStart) + '<strong>'
+ resultString.substring(indexStart, indexEnd) + '</strong>'
+ resultString.substring(indexEnd) + '</p>';
}
export function oneDot(input) {
return input.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ',');
}
| 33.25641 | 108 | 0.613338 | 65 | 6 | 0 | 7 | 7 | 0 | 3 | 5 | 5 | 0 | 4 | 8.833333 | 1,077 | 0.012071 | 0.0065 | 0 | 0 | 0.003714 | 0.25 | 0.25 | 0.215421 | export /* Example usages of 'removeSignAndLowerCase' are shown below:
removeSignAndLowerCase(rawString);
removeSignAndLowerCase(resultString);
*/
function removeSignAndLowerCase(str) {
str = str.trim();
str = str.toLowerCase();
str = str.replace(/à|á|ạ|ả|ã|â|ầ|ấ|ậ|ẩ|ẫ|ă|ằ|ắ|ặ|ẳ|ẵ/g, 'a');
str = str.replace(/è|é|ẹ|ẻ|ẽ|ê|ề|ế|ệ|ể|ễ/g, 'e');
str = str.replace(/ì|í|ị|ỉ|ĩ/g, 'i');
str = str.replace(/ò|ó|ọ|ỏ|õ|ô|ồ|ố|ộ|ổ|ỗ|ơ|ờ|ớ|ợ|ở|ỡ/g, 'o');
str = str.replace(/ù|ú|ụ|ủ|ũ|ư|ừ|ứ|ự|ử|ữ/g, 'u');
str = str.replace(/ỳ|ý|ỵ|ỷ|ỹ/g, 'y');
str = str.replace(/đ/g, 'd');
str = str.replace(/À|Á|Ạ|Ả|Ã|Â|Ầ|Ấ|Ậ|Ẩ|Ẫ|Ă|Ằ|Ắ|Ặ|Ẳ|Ẵ/g, 'a');
str = str.replace(/È|É|Ẹ|Ẻ|Ẽ|Ê|Ề|Ế|Ệ|Ể|Ễ/g, 'e');
str = str.replace(/Ì|Í|Ị|Ỉ|Ĩ/g, 'i');
str = str.replace(/Ò|Ó|Ọ|Ỏ|Õ|Ô|Ồ|Ố|Ộ|Ổ|Ỗ|Ơ|Ờ|Ớ|Ợ|Ở|Ỡ/g, 'o');
str = str.replace(/Ù|Ú|Ụ|Ủ|Ũ|Ư|Ừ|Ứ|Ự|Ử|Ữ/g, 'u');
str = str.replace(/Ỳ|Ý|Ỵ|Ỷ|Ỹ/g, 'y');
str = str.replace(/Đ/g, 'd');
str = str.toLowerCase();
return str;
}
export /* Example usages of 'propValToString' are shown below:
obj[property] = propValToString(obj[property]);
*/
function propValToString(obj) {
for (const property in obj) {
if (typeof obj[property] === 'object' && obj[property] !== null) {
obj[property] = propValToString(obj[property]);
break;
}
if (!(typeof obj[property] === 'string' || obj[property] instanceof String) && obj[property] !== null) {
obj[property] = obj[property].toString();
}
}
return obj;
}
export /* Example usages of 'clearNullOfObject' are shown below:
obj[property] = clearNullOfObject(obj[property]);
*/
function clearNullOfObject(obj) {
for (const property in obj) {
if (typeof obj[property] === 'object' && obj[property] !== null) {
obj[property] = clearNullOfObject(obj[property]);
break;
}
if (obj[property] === null || obj[property] === undefined) {
obj[property] = '';
}
}
return obj;
}
// convert dateTime object to dd/MM/yyyy
export function convertDateToNormal(d) {
if (!d) {
return d;
}
const date = d._d.getDate();
const month = d._d.getMonth() + 1;
const year = d._d.getFullYear();
return date + '/' + month + '/' + year;
}
// highlight text matching in autocomplate
// rawString: string send to server to search
// resultString: string result server sent to client
export function buildHighlightString(rawString, resultString) {
const rawParse = removeSignAndLowerCase(rawString);
const resultParse = removeSignAndLowerCase(resultString);
const indexStart = resultParse.indexOf(rawParse);
const indexEnd = indexStart + rawParse.length;
return '<p>' + resultString.substring(0, indexStart) + '<strong>'
+ resultString.substring(indexStart, indexEnd) + '</strong>'
+ resultString.substring(indexEnd) + '</p>';
}
export function oneDot(input) {
return input.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ',');
}
|
782540af99146e3e07fdd0219b9a1b8603c98c86 | 4,968 | ts | TypeScript | src/utils/spring.ts | devzeebo/react-charts | e00162f9f548be27f69f42b4b1f1795433d95fa7 | [
"MIT"
] | 63 | 2022-02-07T18:27:58.000Z | 2022-03-30T21:15:28.000Z | src/utils/spring.ts | devzeebo/react-charts | e00162f9f548be27f69f42b4b1f1795433d95fa7 | [
"MIT"
] | 9 | 2022-02-08T15:59:21.000Z | 2022-03-22T18:24:45.000Z | src/utils/spring.ts | devzeebo/react-charts | e00162f9f548be27f69f42b4b1f1795433d95fa7 | [
"MIT"
] | 10 | 2022-02-13T19:23:41.000Z | 2022-03-28T21:08:06.000Z | // Super fast physics simulations for JavaScript
// Copyright 2014 Ralph Thomas
// Licensed under the Apache License, Version 2.0
// https://github.com/iamralpht/gravitas.js
// Adapted to TypeScript and customized by Tanner Linsley (@tannerlinsley)
type Solution = {
x: (num: number) => number
dx: (num: number) => number
}
const epsilon = 0.001
function almostEqual(a: number, b: number) {
if (Number.isNaN(a) && Number.isNaN(b)) {
return true
}
return a > b - epsilon && a < b + epsilon
}
function almostZero(a: number) {
return almostEqual(a, 0)
}
export class Spring {
private _m: number
private _k: number
private _c: number
private _solution: null | Solution
private _startTime: number
endPosition: number
constructor(
init: number,
mass: number,
springConstant: number,
damping: number
) {
this._m = mass
this._k = springConstant
this._c = damping
this._solution = null
this.endPosition = init
this._startTime = 0
}
x(dt?: number) {
if (dt === undefined) {
dt = (new Date().getTime() - this._startTime) / 1000.0
}
return this._solution
? this.endPosition + this._solution.x(dt)
: this.endPosition
}
private dx(dt?: number) {
if (dt === undefined) {
dt = (new Date().getTime() - this._startTime) / 1000.0
}
return this._solution ? this._solution.dx(dt) : 0
}
setEnd(x: number) {
const t = new Date().getTime()
let velocity = 0
let position = this.endPosition
if (this._solution) {
// Don't whack incoming velocity.
if (almostZero(velocity))
velocity = this._solution.dx((t - this._startTime) / 1000.0)
position = this._solution.x((t - this._startTime) / 1000.0)
if (almostZero(velocity)) velocity = 0
if (almostZero(position)) position = 0
position += this.endPosition
}
if (this._solution && almostZero(position - x) && almostZero(velocity)) {
return
}
this.endPosition = x
this._solution = this._solve(position - this.endPosition, velocity)
this._startTime = t
}
snap(x: number) {
this._startTime = new Date().getTime()
this.endPosition = x
this._solution = {
x() {
return 0
},
dx() {
return 0
},
}
}
done() {
return almostEqual(this.x(), this.endPosition) && almostZero(this.dx())
}
// reconfigure(mass: number, springConstant: number, damping: number) {
// this._m = mass
// this._k = springConstant
// this._c = damping
// if (this.done()) {
// return
// }
// this._solution = this._solve(this.x() - this.endPosition, this.dx())
// this._startTime = new Date().getTime()
// }
// springConstant() {
// return this._k
// }
// damping() {
// return this._c
// }
private _solve(initial: number, velocity: number): Solution {
const c = this._c
const m = this._m
const k = this._k
// Solve the quadratic equation; root = (-c +/- sqrt(c^2 - 4mk)) / 2m.
const cmk = c * c - 4 * m * k
if (cmk === 0) {
// The spring is critically damped.
// x = (c1 + c2*t) * e ^(-c/2m)*t
const r = -c / (2 * m)
const c1 = initial
const c2 = velocity / (r * initial)
return {
x(t) {
return (c1 + c2 * t) * Math.pow(Math.E, r * t)
},
dx(t) {
const pow = Math.pow(Math.E, r * t)
return r * (c1 + c2 * t) * pow + c2 * pow
},
}
} else if (cmk > 0) {
// The spring is overdamped; no bounces.
// x = c1*e^(r1*t) + c2*e^(r2t)
// Need to find r1 and r2, the roots, then solve c1 and c2.
const r1 = (-c - Math.sqrt(cmk)) / (2 * m)
const r2 = (-c + Math.sqrt(cmk)) / (2 * m)
const c2 = (velocity - r1 * initial) / (r2 - r1)
const c1 = initial - c2
return {
x(t) {
return c1 * Math.pow(Math.E, r1 * t) + c2 * Math.pow(Math.E, r2 * t)
},
dx(t) {
return (
c1 * r1 * Math.pow(Math.E, r1 * t) +
c2 * r2 * Math.pow(Math.E, r2 * t)
)
},
}
} else {
// The spring is underdamped, it has imaginary roots.
// r = -(c / 2*m) +- w*i
// w = sqrt(4mk - c^2) / 2m
// x = (e^-(c/2m)t) * (c1 * cos(wt) + c2 * sin(wt))
const w = Math.sqrt(4 * m * k - c * c) / (2 * m)
const r = -((c / 2) * m)
const c1 = initial
const c2 = (velocity - r * initial) / w
return {
x(t) {
return (
Math.pow(Math.E, r * t) *
(c1 * Math.cos(w * t) + c2 * Math.sin(w * t))
)
},
dx(t) {
const power = Math.pow(Math.E, r * t)
const cos = Math.cos(w * t)
const sin = Math.sin(w * t)
return (
power * (c2 * w * cos - c1 * w * sin) +
r * power * (c2 * sin + c1 * cos)
)
},
}
}
}
}
| 25.608247 | 78 | 0.524155 | 141 | 17 | 0 | 19 | 23 | 8 | 5 | 0 | 22 | 2 | 0 | 7.411765 | 1,616 | 0.022277 | 0.014233 | 0.00495 | 0.001238 | 0 | 0 | 0.328358 | 0.271524 | // Super fast physics simulations for JavaScript
// Copyright 2014 Ralph Thomas
// Licensed under the Apache License, Version 2.0
// https://github.com/iamralpht/gravitas.js
// Adapted to TypeScript and customized by Tanner Linsley (@tannerlinsley)
type Solution = {
x
dx
}
const epsilon = 0.001
/* Example usages of 'almostEqual' are shown below:
almostEqual(a, 0);
almostEqual(this.x(), this.endPosition) && almostZero(this.dx());
*/
function almostEqual(a, b) {
if (Number.isNaN(a) && Number.isNaN(b)) {
return true
}
return a > b - epsilon && a < b + epsilon
}
/* Example usages of 'almostZero' are shown below:
almostZero(velocity);
almostZero(position);
this._solution && almostZero(position - x) && almostZero(velocity);
almostEqual(this.x(), this.endPosition) && almostZero(this.dx());
*/
function almostZero(a) {
return almostEqual(a, 0)
}
export class Spring {
private _m
private _k
private _c
private _solution
private _startTime
endPosition
constructor(
init,
mass,
springConstant,
damping
) {
this._m = mass
this._k = springConstant
this._c = damping
this._solution = null
this.endPosition = init
this._startTime = 0
}
x(dt?) {
if (dt === undefined) {
dt = (new Date().getTime() - this._startTime) / 1000.0
}
return this._solution
? this.endPosition + this._solution.x(dt)
: this.endPosition
}
private dx(dt?) {
if (dt === undefined) {
dt = (new Date().getTime() - this._startTime) / 1000.0
}
return this._solution ? this._solution.dx(dt) : 0
}
setEnd(x) {
const t = new Date().getTime()
let velocity = 0
let position = this.endPosition
if (this._solution) {
// Don't whack incoming velocity.
if (almostZero(velocity))
velocity = this._solution.dx((t - this._startTime) / 1000.0)
position = this._solution.x((t - this._startTime) / 1000.0)
if (almostZero(velocity)) velocity = 0
if (almostZero(position)) position = 0
position += this.endPosition
}
if (this._solution && almostZero(position - x) && almostZero(velocity)) {
return
}
this.endPosition = x
this._solution = this._solve(position - this.endPosition, velocity)
this._startTime = t
}
snap(x) {
this._startTime = new Date().getTime()
this.endPosition = x
this._solution = {
x() {
return 0
},
dx() {
return 0
},
}
}
done() {
return almostEqual(this.x(), this.endPosition) && almostZero(this.dx())
}
// reconfigure(mass: number, springConstant: number, damping: number) {
// this._m = mass
// this._k = springConstant
// this._c = damping
// if (this.done()) {
// return
// }
// this._solution = this._solve(this.x() - this.endPosition, this.dx())
// this._startTime = new Date().getTime()
// }
// springConstant() {
// return this._k
// }
// damping() {
// return this._c
// }
private _solve(initial, velocity) {
const c = this._c
const m = this._m
const k = this._k
// Solve the quadratic equation; root = (-c +/- sqrt(c^2 - 4mk)) / 2m.
const cmk = c * c - 4 * m * k
if (cmk === 0) {
// The spring is critically damped.
// x = (c1 + c2*t) * e ^(-c/2m)*t
const r = -c / (2 * m)
const c1 = initial
const c2 = velocity / (r * initial)
return {
x(t) {
return (c1 + c2 * t) * Math.pow(Math.E, r * t)
},
dx(t) {
const pow = Math.pow(Math.E, r * t)
return r * (c1 + c2 * t) * pow + c2 * pow
},
}
} else if (cmk > 0) {
// The spring is overdamped; no bounces.
// x = c1*e^(r1*t) + c2*e^(r2t)
// Need to find r1 and r2, the roots, then solve c1 and c2.
const r1 = (-c - Math.sqrt(cmk)) / (2 * m)
const r2 = (-c + Math.sqrt(cmk)) / (2 * m)
const c2 = (velocity - r1 * initial) / (r2 - r1)
const c1 = initial - c2
return {
x(t) {
return c1 * Math.pow(Math.E, r1 * t) + c2 * Math.pow(Math.E, r2 * t)
},
dx(t) {
return (
c1 * r1 * Math.pow(Math.E, r1 * t) +
c2 * r2 * Math.pow(Math.E, r2 * t)
)
},
}
} else {
// The spring is underdamped, it has imaginary roots.
// r = -(c / 2*m) +- w*i
// w = sqrt(4mk - c^2) / 2m
// x = (e^-(c/2m)t) * (c1 * cos(wt) + c2 * sin(wt))
const w = Math.sqrt(4 * m * k - c * c) / (2 * m)
const r = -((c / 2) * m)
const c1 = initial
const c2 = (velocity - r * initial) / w
return {
x(t) {
return (
Math.pow(Math.E, r * t) *
(c1 * Math.cos(w * t) + c2 * Math.sin(w * t))
)
},
dx(t) {
const power = Math.pow(Math.E, r * t)
const cos = Math.cos(w * t)
const sin = Math.sin(w * t)
return (
power * (c2 * w * cos - c1 * w * sin) +
r * power * (c2 * sin + c1 * cos)
)
},
}
}
}
}
|
78e2b4a588f064a38ff2faa84f782f389ccd537c | 3,324 | ts | TypeScript | RecommenederSystem/api/controllers/AdminController.ts | JonathanPachacama/AplicacionFer | 3a606e22b7c6a8d777e251f695e8dd6d12a54352 | [
"MIT"
] | null | null | null | RecommenederSystem/api/controllers/AdminController.ts | JonathanPachacama/AplicacionFer | 3a606e22b7c6a8d777e251f695e8dd6d12a54352 | [
"MIT"
] | 1 | 2022-02-10T19:23:59.000Z | 2022-02-10T19:23:59.000Z | RecommenederSystem/api/controllers/AdminController.ts | JonathanPachacama/recommendation-system-scientific-articles-linked-data | 3a606e22b7c6a8d777e251f695e8dd6d12a54352 | [
"MIT"
] | null | null | null | declare var module;
declare var sails;
declare var Rol_users;
declare var User;
declare var require;
module.exports = {
index:function(req,res){
return res.view('Admin/newRol',{
layout: 'Auth/loginLayout'
})
},
view:function(req,res){
let parametros = req.allParams();
sails.log.info("Parametros",parametros);
Rol_users
.find()
.exec((err,rols)=>{
if(err) return res.negotiate(err);
sails.log.info("roles",rols);
return res.view('Admin/rols',{
rol:rols,
layout: 'Auth/loginLayout'
})
})
},
edit:function(req,res){
let parametros = req.allParams();
if(parametros.rol_id){
Rol_users.findOne({
rol_id:parametros.rol_id
})
.exec((err,rolFound)=>{
if(err) return res.serverError(err);
if(rolFound){
//Si encontro
return res.view('Admin/editRol',{
rol:rolFound,
layout: 'Auth/loginLayout'
})
}else{
//No encontro
return res.notFound()
}
})
}else{
return res.badRequest()
}
},
create_rol:(req, res)=>{
let parametros = req.allParams();
let newRol = {
rol_name :parametros.rol_name ,
rol_description :parametros.rol_description ,
rol_active :parametros.rol_active
};
Rol_users.create(newRol)
.exec(
(error,rolCreated)=> {
if (error) {return res.negotiate(error);}
return res.ok(rolCreated)
})
},
update_role:(req,res)=>{
let parametros = req.allParams();
if(parametros.rol_name&&
parametros.rol_description&&
parametros.rol_active&&
parametros.rol_id){
Rol_users.update({
rol_id:parametros.rol_id
},{
rol_name:parametros.rol_name,
rol_description:parametros.rol_description,
rol_active:parametros.rol_active
})
.exec((err,rolEdit)=>{
if(err) return res.serverError(err);
if(rolEdit){
//Si encontro
return res.ok(rolEdit)
}else{
//No encontro
return res.notFound()
}
})
}else{
return res.badRequest()
}
},
delete_rol: (req, res) => {
let params = req.allParams();
sails.log.info("Parametros", params);
if (req.method == "POST" && params.rol_id) {
Rol_users.destroy({
rol_id: params.rol_id
}).exec((err, rolDeleted) => {
if (err) return res.serverError(err);
return res.ok(rolDeleted)
})
} else {
return res.badRequest();
}
},
update_password:(req,res)=>{
let parametros = req.allParams();
if(parametros.user_password&&
parametros.user_username&&
parametros.user_id){
User.update({
user_id:parametros.user_id
},{
user_password:parametros.user_password,
user_username:parametros.user_username
})
.exec((err,passEdit)=>{
if(err) return res.serverError(err);
if(passEdit){
//Si Edito
return res.ok(passEdit)
}else{
//No Edito
return res.notFound()
}
})
}else{
return res.badRequest()
}
},
};
| 22.924138 | 51 | 0.546029 | 123 | 13 | 0 | 26 | 12 | 0 | 0 | 0 | 0 | 0 | 0 | 10.230769 | 900 | 0.043333 | 0.013333 | 0 | 0 | 0 | 0 | 0 | 0.315035 | declare var module;
declare var sails;
declare var Rol_users;
declare var User;
declare var require;
module.exports = {
index:function(req,res){
return res.view('Admin/newRol',{
layout: 'Auth/loginLayout'
})
},
view:function(req,res){
let parametros = req.allParams();
sails.log.info("Parametros",parametros);
Rol_users
.find()
.exec((err,rols)=>{
if(err) return res.negotiate(err);
sails.log.info("roles",rols);
return res.view('Admin/rols',{
rol:rols,
layout: 'Auth/loginLayout'
})
})
},
edit:function(req,res){
let parametros = req.allParams();
if(parametros.rol_id){
Rol_users.findOne({
rol_id:parametros.rol_id
})
.exec((err,rolFound)=>{
if(err) return res.serverError(err);
if(rolFound){
//Si encontro
return res.view('Admin/editRol',{
rol:rolFound,
layout: 'Auth/loginLayout'
})
}else{
//No encontro
return res.notFound()
}
})
}else{
return res.badRequest()
}
},
create_rol:(req, res)=>{
let parametros = req.allParams();
let newRol = {
rol_name :parametros.rol_name ,
rol_description :parametros.rol_description ,
rol_active :parametros.rol_active
};
Rol_users.create(newRol)
.exec(
(error,rolCreated)=> {
if (error) {return res.negotiate(error);}
return res.ok(rolCreated)
})
},
update_role:(req,res)=>{
let parametros = req.allParams();
if(parametros.rol_name&&
parametros.rol_description&&
parametros.rol_active&&
parametros.rol_id){
Rol_users.update({
rol_id:parametros.rol_id
},{
rol_name:parametros.rol_name,
rol_description:parametros.rol_description,
rol_active:parametros.rol_active
})
.exec((err,rolEdit)=>{
if(err) return res.serverError(err);
if(rolEdit){
//Si encontro
return res.ok(rolEdit)
}else{
//No encontro
return res.notFound()
}
})
}else{
return res.badRequest()
}
},
delete_rol: (req, res) => {
let params = req.allParams();
sails.log.info("Parametros", params);
if (req.method == "POST" && params.rol_id) {
Rol_users.destroy({
rol_id: params.rol_id
}).exec((err, rolDeleted) => {
if (err) return res.serverError(err);
return res.ok(rolDeleted)
})
} else {
return res.badRequest();
}
},
update_password:(req,res)=>{
let parametros = req.allParams();
if(parametros.user_password&&
parametros.user_username&&
parametros.user_id){
User.update({
user_id:parametros.user_id
},{
user_password:parametros.user_password,
user_username:parametros.user_username
})
.exec((err,passEdit)=>{
if(err) return res.serverError(err);
if(passEdit){
//Si Edito
return res.ok(passEdit)
}else{
//No Edito
return res.notFound()
}
})
}else{
return res.badRequest()
}
},
};
|
592c51fd9164222f5c17f89c1f7d4ef189e7e84d | 1,415 | ts | TypeScript | angular/src/shared/service-proxies/dto/contact-list/create-contact-dto.ts | fabianorangel26/unisolution-fabianorangel26 | 2d6030e5bcc14a56ebeffb24377040d40e508b22 | [
"MIT"
] | 2 | 2022-02-03T13:22:50.000Z | 2022-02-04T17:53:02.000Z | angular/src/shared/service-proxies/dto/contact-list/create-contact-dto.ts | fabianorangel26/unisolution-fabianorangel26 | 2d6030e5bcc14a56ebeffb24377040d40e508b22 | [
"MIT"
] | null | null | null | angular/src/shared/service-proxies/dto/contact-list/create-contact-dto.ts | fabianorangel26/unisolution-fabianorangel26 | 2d6030e5bcc14a56ebeffb24377040d40e508b22 | [
"MIT"
] | null | null | null | export interface ICreateContactDto {
id: number;
personId: number;
name: string;
telephone: string;
email: string;
isActive: boolean;
}
export class CreateContactDto implements ICreateContactDto {
id: number;
personId: number;
name: string;
telephone: string;
email: string;
isActive: boolean;
constructor(data?: ICreateContactDto) {
if (data) {
for (var property in data) {
if (data.hasOwnProperty(property))
(<any>this)[property] = (<any>data)[property];
}
}
}
init(data?: any) {
if (data) {
this.id = data.id;
this.personId = data.personId;
this.name = data.name;
this.telephone = data.telephone;
this.email = data.email;
this.isActive = data.isActive;
}
}
static fromJS(data: any): CreateContactDto {
data = typeof data === "object" ? data : {};
let result = new CreateContactDto();
result.init(data);
return result;
}
toJSON(data?: any) {
data = typeof data === "object" ? data : {};
data.id = this.id;
data.personId = this.personId;
data.name = this.name;
data.telephone = this.telephone;
data.email = this.email;
data.isActive = this.isActive;
return data;
}
}
| 24.396552 | 66 | 0.540636 | 50 | 4 | 0 | 4 | 1 | 12 | 1 | 5 | 12 | 2 | 2 | 6.5 | 351 | 0.022792 | 0.002849 | 0.034188 | 0.005698 | 0.005698 | 0.238095 | 0.571429 | 0.236741 | export interface ICreateContactDto {
id;
personId;
name;
telephone;
email;
isActive;
}
export class CreateContactDto implements ICreateContactDto {
id;
personId;
name;
telephone;
email;
isActive;
constructor(data?) {
if (data) {
for (var property in data) {
if (data.hasOwnProperty(property))
(<any>this)[property] = (<any>data)[property];
}
}
}
init(data?) {
if (data) {
this.id = data.id;
this.personId = data.personId;
this.name = data.name;
this.telephone = data.telephone;
this.email = data.email;
this.isActive = data.isActive;
}
}
static fromJS(data) {
data = typeof data === "object" ? data : {};
let result = new CreateContactDto();
result.init(data);
return result;
}
toJSON(data?) {
data = typeof data === "object" ? data : {};
data.id = this.id;
data.personId = this.personId;
data.name = this.name;
data.telephone = this.telephone;
data.email = this.email;
data.isActive = this.isActive;
return data;
}
}
|
595681bb13aee410a4c20056b48f731d78418652 | 1,918 | ts | TypeScript | src/utils/heap.ts | ayushnirwal/react-photo-album | 31c89817526e24dba6f3d3213e9429637bdbda34 | [
"MIT"
] | 23 | 2022-01-26T14:42:41.000Z | 2022-03-30T20:38:08.000Z | src/utils/heap.ts | ayushnirwal/react-photo-album | 31c89817526e24dba6f3d3213e9429637bdbda34 | [
"MIT"
] | 57 | 2022-01-10T21:10:50.000Z | 2022-03-24T21:55:33.000Z | src/utils/heap.ts | ayushnirwal/react-photo-album | 31c89817526e24dba6f3d3213e9429637bdbda34 | [
"MIT"
] | 2 | 2022-02-21T10:07:12.000Z | 2022-03-31T12:09:17.000Z | type Comparator<T> = (a: T, b: T) => number;
export const RankingFunctionComparator =
<T>(rank: (element: T) => number) =>
(a: T, b: T) =>
rank(b) - rank(a);
export const NumericComparator = RankingFunctionComparator<number>((x: number) => x);
/**
* Min heap implementation.
* Comparator function is expected to return a positive number, zero or a negative number if a > b, a === b or a < b.
*/
const MinHeap = <T>(comparator: Comparator<T>) => {
// heap-ordered complete binary tree in heap[1..n] with heap[0] unused
const heap: T[] = [];
const compare = comparator;
let n = 0;
// comparator function
const greater = (i: number, j: number) => compare(heap[i], heap[j]) < 0;
// swap two elements
const swap = (i: number, j: number) => {
const temp = heap[i];
heap[i] = heap[j];
heap[j] = temp;
};
// bubble k-th element up
const swim = (k: number) => {
let k2 = k >> 1;
while (k > 1 && greater(k2, k)) {
swap(k2, k);
k = k2;
k2 = k >> 1;
}
};
// bubble k-th element down
const sink = (k: number) => {
let j = k << 1;
while (j <= n) {
if (j < n && greater(j, j + 1)) j++;
if (!greater(k, j)) break;
swap(k, j);
k = j;
j = k << 1;
}
};
return {
/** add element to the heap */
push: (element: T) => {
n += 1;
heap[n] = element;
swim(n);
},
/** remove the first element from the heap */
pop: (): T | undefined => {
if (n === 0) return undefined;
swap(1, n);
n -= 1;
const max = heap.pop();
sink(1);
return max;
},
/** heap size */
size: (): number => n,
};
};
export default MinHeap;
| 25.236842 | 117 | 0.45829 | 52 | 11 | 0 | 12 | 14 | 0 | 5 | 0 | 11 | 1 | 0 | 6.818182 | 556 | 0.041367 | 0.02518 | 0 | 0.001799 | 0 | 0 | 0.297297 | 0.352931 | type Comparator<T> = (a, b) => number;
export /* Example usages of 'RankingFunctionComparator' are shown below:
RankingFunctionComparator<number>((x) => x);
*/
const RankingFunctionComparator =
<T>(rank) =>
(a, b) =>
rank(b) - rank(a);
export const NumericComparator = RankingFunctionComparator<number>((x) => x);
/**
* Min heap implementation.
* Comparator function is expected to return a positive number, zero or a negative number if a > b, a === b or a < b.
*/
/* Example usages of 'MinHeap' are shown below:
;
*/
const MinHeap = <T>(comparator) => {
// heap-ordered complete binary tree in heap[1..n] with heap[0] unused
const heap = [];
const compare = comparator;
let n = 0;
// comparator function
/* Example usages of 'greater' are shown below:
k > 1 && greater(k2, k);
j < n && greater(j, j + 1);
!greater(k, j);
*/
const greater = (i, j) => compare(heap[i], heap[j]) < 0;
// swap two elements
/* Example usages of 'swap' are shown below:
swap(k2, k);
swap(k, j);
swap(1, n);
*/
const swap = (i, j) => {
const temp = heap[i];
heap[i] = heap[j];
heap[j] = temp;
};
// bubble k-th element up
/* Example usages of 'swim' are shown below:
swim(n);
*/
const swim = (k) => {
let k2 = k >> 1;
while (k > 1 && greater(k2, k)) {
swap(k2, k);
k = k2;
k2 = k >> 1;
}
};
// bubble k-th element down
/* Example usages of 'sink' are shown below:
sink(1);
*/
const sink = (k) => {
let j = k << 1;
while (j <= n) {
if (j < n && greater(j, j + 1)) j++;
if (!greater(k, j)) break;
swap(k, j);
k = j;
j = k << 1;
}
};
return {
/** add element to the heap */
push: (element) => {
n += 1;
heap[n] = element;
swim(n);
},
/** remove the first element from the heap */
pop: () => {
if (n === 0) return undefined;
swap(1, n);
n -= 1;
const max = heap.pop();
sink(1);
return max;
},
/** heap size */
size: () => n,
};
};
export default MinHeap;
|
5967a84ed2e9763f0f798c849269f6a7fc5cece3 | 1,837 | ts | TypeScript | src/utils/temperaturecolorgen.ts | Heyeso/WeatherNow | 939e27a10ae4749b9f3d862681761e1d4c899832 | [
"MIT"
] | 1 | 2022-01-24T21:35:11.000Z | 2022-01-24T21:35:11.000Z | src/utils/temperaturecolorgen.ts | Heyeso/WeatherNow | 939e27a10ae4749b9f3d862681761e1d4c899832 | [
"MIT"
] | null | null | null | src/utils/temperaturecolorgen.ts | Heyeso/WeatherNow | 939e27a10ae4749b9f3d862681761e1d4c899832 | [
"MIT"
] | null | null | null | const TEMP_COLORS = [
[139, 0, 0], //DARK_RED
[255, 0, 0], //RED
[255, 36, 0], //SCARLET
[255, 215, 0], //ORANGE
[255, 255, 0], //YELLOW
[27, 142, 45], //RICH_GREEN
[0, 255, 0], //GREEN
[135, 206, 235], //SKY_BLUE
[0, 0, 255], //BLUE
[128, 0, 128], //PURPLE
[217, 130, 181], //PINKY_PURPLE
[255, 0, 255], //MAGENTA
];
const TEMP = [38, 32, 27, 21, 16, 10, 4, -1, -7, -12, -18, -23];
//colorChannelA and colorChannelB are ints ranging from 0 to 255
const colorChannelMixer = (
colorChannelA: number,
colorChannelB: number,
amountToMix: number
) => {
var channelA = colorChannelA * amountToMix;
var channelB = colorChannelB * (1 - amountToMix);
return channelA + channelB;
};
//rgbA and rgbB are arrays, amountToMix ranges from 0.0 to 1.0
//example (red): rgbA = [255,0,0]
const colorMixer = (
rgbA: Array<number>,
rgbB: Array<number>,
amountToMix: number,
opacity: number
) => {
var r = colorChannelMixer(rgbA[0], rgbB[0], amountToMix);
var g = colorChannelMixer(rgbA[1], rgbB[1], amountToMix);
var b = colorChannelMixer(rgbA[2], rgbB[2], amountToMix);
return "rgba(" + r.toFixed(0) + "," + g.toFixed(0) + "," + b.toFixed(0) + "," + opacity + ")";
};
export const TemperatureColorGenerator = (temp: number, opacity: number = 0.5) => {
if (temp >= TEMP[0]) return `rgb(${TEMP_COLORS[0]}, ${opacity})`;
if (temp <= TEMP[TEMP.length - 1])
return `rgba(${TEMP_COLORS[TEMP.length - 1]}, ${opacity})`;
for (let x = 0; x < TEMP.length - 1; x++) {
if (TEMP[x] === temp) return `rgba(${TEMP_COLORS[x]}, ${opacity})`;
if (temp < TEMP[x] && temp > TEMP[x + 1]) {
let max = TEMP[x],
min = TEMP[x + 1];
let ratio = (temp - min) / (max - min);
return colorMixer(TEMP_COLORS[x], TEMP_COLORS[x + 1], ratio, opacity);
}
}
return `rgb(0,0,0,1)`;
};
| 32.22807 | 96 | 0.593359 | 50 | 3 | 0 | 9 | 14 | 0 | 2 | 0 | 9 | 0 | 0 | 6.666667 | 764 | 0.015707 | 0.018325 | 0 | 0 | 0 | 0 | 0.346154 | 0.266725 | const TEMP_COLORS = [
[139, 0, 0], //DARK_RED
[255, 0, 0], //RED
[255, 36, 0], //SCARLET
[255, 215, 0], //ORANGE
[255, 255, 0], //YELLOW
[27, 142, 45], //RICH_GREEN
[0, 255, 0], //GREEN
[135, 206, 235], //SKY_BLUE
[0, 0, 255], //BLUE
[128, 0, 128], //PURPLE
[217, 130, 181], //PINKY_PURPLE
[255, 0, 255], //MAGENTA
];
const TEMP = [38, 32, 27, 21, 16, 10, 4, -1, -7, -12, -18, -23];
//colorChannelA and colorChannelB are ints ranging from 0 to 255
/* Example usages of 'colorChannelMixer' are shown below:
colorChannelMixer(rgbA[0], rgbB[0], amountToMix);
colorChannelMixer(rgbA[1], rgbB[1], amountToMix);
colorChannelMixer(rgbA[2], rgbB[2], amountToMix);
*/
const colorChannelMixer = (
colorChannelA,
colorChannelB,
amountToMix
) => {
var channelA = colorChannelA * amountToMix;
var channelB = colorChannelB * (1 - amountToMix);
return channelA + channelB;
};
//rgbA and rgbB are arrays, amountToMix ranges from 0.0 to 1.0
//example (red): rgbA = [255,0,0]
/* Example usages of 'colorMixer' are shown below:
colorMixer(TEMP_COLORS[x], TEMP_COLORS[x + 1], ratio, opacity);
*/
const colorMixer = (
rgbA,
rgbB,
amountToMix,
opacity
) => {
var r = colorChannelMixer(rgbA[0], rgbB[0], amountToMix);
var g = colorChannelMixer(rgbA[1], rgbB[1], amountToMix);
var b = colorChannelMixer(rgbA[2], rgbB[2], amountToMix);
return "rgba(" + r.toFixed(0) + "," + g.toFixed(0) + "," + b.toFixed(0) + "," + opacity + ")";
};
export const TemperatureColorGenerator = (temp, opacity = 0.5) => {
if (temp >= TEMP[0]) return `rgb(${TEMP_COLORS[0]}, ${opacity})`;
if (temp <= TEMP[TEMP.length - 1])
return `rgba(${TEMP_COLORS[TEMP.length - 1]}, ${opacity})`;
for (let x = 0; x < TEMP.length - 1; x++) {
if (TEMP[x] === temp) return `rgba(${TEMP_COLORS[x]}, ${opacity})`;
if (temp < TEMP[x] && temp > TEMP[x + 1]) {
let max = TEMP[x],
min = TEMP[x + 1];
let ratio = (temp - min) / (max - min);
return colorMixer(TEMP_COLORS[x], TEMP_COLORS[x + 1], ratio, opacity);
}
}
return `rgb(0,0,0,1)`;
};
|
e69f355e0dde8cc39315088f2549b024fd0d889f | 2,835 | ts | TypeScript | fastcar-core/src/utils/DateUtil.ts | williamDazhangyu/fast-car | c485ab6637e29e8c49b00af6600e2ded2b9a0c57 | [
"MIT"
] | 4 | 2022-03-08T06:02:31.000Z | 2022-03-14T04:33:39.000Z | fastcar-core/src/utils/DateUtil.ts | williamDazhangyu/fast-car | c485ab6637e29e8c49b00af6600e2ded2b9a0c57 | [
"MIT"
] | null | null | null | fastcar-core/src/utils/DateUtil.ts | williamDazhangyu/fast-car | c485ab6637e29e8c49b00af6600e2ded2b9a0c57 | [
"MIT"
] | null | null | null | export default class DateUtil {
static twoDigits(num: number): string {
return num.toString().padStart(2, "0");
}
//返回年月日时分秒
static toDateDesc(datetime: number | string | Date = Date.now()) {
let dataC = new Date(datetime);
return {
YYYY: DateUtil.twoDigits(dataC.getFullYear()),
MM: DateUtil.twoDigits(dataC.getMonth() + 1),
DD: DateUtil.twoDigits(dataC.getDate()),
hh: DateUtil.twoDigits(dataC.getHours()),
mm: DateUtil.twoDigits(dataC.getMinutes()),
ss: DateUtil.twoDigits(dataC.getSeconds()),
ms: DateUtil.twoDigits(dataC.getMilliseconds()),
};
}
static toDay(datetime: number | string | Date = Date.now(), format: string = "YYYY-MM-DD") {
let desc = DateUtil.toDateDesc(datetime);
let ymd = format
.replace(/YYYY/, desc.YYYY)
.replace(/MM/, desc.MM)
.replace(/DD/, desc.DD);
return ymd;
}
static toHms(datetime: number | string | Date = Date.now(), format: string = "hh:mm:ss") {
let desc = DateUtil.toDateDesc(datetime);
let hms = format
.replace(/hh/, desc.hh)
.replace(/mm/, desc.mm)
.replace(/ss/, desc.ss);
return hms;
}
static toDateTime(datetime: number | string | Date = Date.now(), format: string = "YYYY-MM-DD hh:mm:ss") {
let desc = DateUtil.toDateDesc(datetime);
let str = format
.replace(/YYYY/, desc.YYYY)
.replace(/MM/, desc.MM)
.replace(/DD/, desc.DD)
.replace(/hh/, desc.hh)
.replace(/mm/, desc.mm)
.replace(/ss/, desc.ss);
return str;
}
static toDateTimeMS(datetime: number | string | Date = Date.now(), format: string = "YYYY-MM-DD hh:mm:ss.sss") {
let desc = DateUtil.toDateDesc(datetime);
let str = format
.replace(/YYYY/, desc.YYYY)
.replace(/MM/, desc.MM)
.replace(/DD/, desc.DD)
.replace(/hh/, desc.hh)
.replace(/mm/, desc.mm)
.replace(/ss/, desc.ss)
.replace(/sss/, desc.ms);
return str;
}
static toCutDown(datetime: number, format: string = "hh:mm:ss") {
let hours = Math.floor(datetime / 60 / 60);
let minutes = Math.floor((datetime - hours * 60 * 60) / 60);
let seconds = datetime - (hours * 60 + minutes) * 60;
let str = format
.replace(/hh/, hours.toString())
.replace(/mm/, minutes.toString())
.replace(/ss/, seconds.toString());
return str;
}
static getTimeStr(datetime: number) {
let days = datetime / (1000 * 60 * 60 * 24);
if (days >= 1) {
return `${days.toFixed(2)}d`;
}
let hours = datetime / (1000 * 60 * 60);
if (hours >= 1) {
return `${hours.toFixed(2)}h`;
}
let minutes = datetime / (1000 * 60);
if (minutes >= 1) {
return `${minutes.toFixed(2)}m`;
}
let seconds = datetime / 1000;
return `${Math.floor(seconds)}s`;
}
static getDateTime(datetimeStr?: string | number): number {
if (datetimeStr) {
let dataC = new Date(datetimeStr);
return dataC.getTime();
}
return Date.now();
}
}
| 26.25 | 113 | 0.628924 | 89 | 9 | 0 | 14 | 18 | 0 | 2 | 0 | 22 | 1 | 0 | 7.666667 | 1,011 | 0.02275 | 0.017804 | 0 | 0.000989 | 0 | 0 | 0.536585 | 0.282868 | export default class DateUtil {
static twoDigits(num) {
return num.toString().padStart(2, "0");
}
//返回年月日时分秒
static toDateDesc(datetime = Date.now()) {
let dataC = new Date(datetime);
return {
YYYY: DateUtil.twoDigits(dataC.getFullYear()),
MM: DateUtil.twoDigits(dataC.getMonth() + 1),
DD: DateUtil.twoDigits(dataC.getDate()),
hh: DateUtil.twoDigits(dataC.getHours()),
mm: DateUtil.twoDigits(dataC.getMinutes()),
ss: DateUtil.twoDigits(dataC.getSeconds()),
ms: DateUtil.twoDigits(dataC.getMilliseconds()),
};
}
static toDay(datetime = Date.now(), format = "YYYY-MM-DD") {
let desc = DateUtil.toDateDesc(datetime);
let ymd = format
.replace(/YYYY/, desc.YYYY)
.replace(/MM/, desc.MM)
.replace(/DD/, desc.DD);
return ymd;
}
static toHms(datetime = Date.now(), format = "hh:mm:ss") {
let desc = DateUtil.toDateDesc(datetime);
let hms = format
.replace(/hh/, desc.hh)
.replace(/mm/, desc.mm)
.replace(/ss/, desc.ss);
return hms;
}
static toDateTime(datetime = Date.now(), format = "YYYY-MM-DD hh:mm:ss") {
let desc = DateUtil.toDateDesc(datetime);
let str = format
.replace(/YYYY/, desc.YYYY)
.replace(/MM/, desc.MM)
.replace(/DD/, desc.DD)
.replace(/hh/, desc.hh)
.replace(/mm/, desc.mm)
.replace(/ss/, desc.ss);
return str;
}
static toDateTimeMS(datetime = Date.now(), format = "YYYY-MM-DD hh:mm:ss.sss") {
let desc = DateUtil.toDateDesc(datetime);
let str = format
.replace(/YYYY/, desc.YYYY)
.replace(/MM/, desc.MM)
.replace(/DD/, desc.DD)
.replace(/hh/, desc.hh)
.replace(/mm/, desc.mm)
.replace(/ss/, desc.ss)
.replace(/sss/, desc.ms);
return str;
}
static toCutDown(datetime, format = "hh:mm:ss") {
let hours = Math.floor(datetime / 60 / 60);
let minutes = Math.floor((datetime - hours * 60 * 60) / 60);
let seconds = datetime - (hours * 60 + minutes) * 60;
let str = format
.replace(/hh/, hours.toString())
.replace(/mm/, minutes.toString())
.replace(/ss/, seconds.toString());
return str;
}
static getTimeStr(datetime) {
let days = datetime / (1000 * 60 * 60 * 24);
if (days >= 1) {
return `${days.toFixed(2)}d`;
}
let hours = datetime / (1000 * 60 * 60);
if (hours >= 1) {
return `${hours.toFixed(2)}h`;
}
let minutes = datetime / (1000 * 60);
if (minutes >= 1) {
return `${minutes.toFixed(2)}m`;
}
let seconds = datetime / 1000;
return `${Math.floor(seconds)}s`;
}
static getDateTime(datetimeStr?) {
if (datetimeStr) {
let dataC = new Date(datetimeStr);
return dataC.getTime();
}
return Date.now();
}
}
|
e6a6c50f5875f3ac0c808de5ead86b44e54c43c6 | 2,678 | ts | TypeScript | src/helpers/arrayFunctions.ts | luciferreeves/izuku.js | 9297d01ff17ce9d897774ec928eaa0402651ccb2 | [
"MIT"
] | 1 | 2022-01-23T14:51:10.000Z | 2022-01-23T14:51:10.000Z | src/helpers/arrayFunctions.ts | luciferreeves/izuku.js | 9297d01ff17ce9d897774ec928eaa0402651ccb2 | [
"MIT"
] | null | null | null | src/helpers/arrayFunctions.ts | luciferreeves/izuku.js | 9297d01ff17ce9d897774ec928eaa0402651ccb2 | [
"MIT"
] | null | null | null | /**
* isArrayOfType check if the array contains only the specified type
* @param array: the array to be checked
* @param type: the type to be checked
* @returns true if the array contains only the specified type
*/
export function isArrayOfType(array: any[], type: string): boolean {
return array.filter((i) => typeof i === type).length === array.length;
}
/**
* range - returns an array of numbers from start to end
* @param start: the start of the range
* @param end: the end of the range
* @param step: the step of the range
* @returns an array of numbers from start to end
*/
export function range(
start: number,
end: number,
step = 1,
remove?: Array<number>
): Array<number> {
// Check if start, end and step are integers
if (
!Number.isInteger(start) ||
!Number.isInteger(end) ||
!Number.isInteger(step)
) {
throw new Error('range parameters must be integers');
}
const rangeArray: Array<number> = [];
// Start must be less than end
if (start > end) {
throw new Error('starting value must be less than end value');
}
// Step must be greater than 0
if (step <= 0) {
throw new Error('step must be greater than 0');
}
// Generate an array from start to end
for (let i = start; i <= end; i += step) {
if (remove) {
if (!remove.includes(i)) {
rangeArray.push(i);
}
} else {
rangeArray.push(i);
}
}
return rangeArray;
}
/**
* flattenJSON - converts a nested JSON object into a simple JSON object
* @param object: the object to be flattened
* @returns the flattened object
*/
// eslint-disable-next-line @typescript-eslint/no-unused-vars
export function flattenJSON(data: any): any {
const result: any = {};
function recurse(cur: any, prop: string) {
if (Object(cur) !== cur) {
result[prop] = cur;
} else if (Array.isArray(cur)) {
// eslint-disable-next-line no-var
for (var i = 0, l = cur.length; i < l; i++)
recurse(cur[i], prop + '[' + i + ']');
if (l == 0) result[prop] = [];
} else {
let isEmpty = true;
for (const p in cur) {
isEmpty = false;
recurse(cur[p], prop ? prop + '.' + p : p);
}
if (isEmpty && prop) result[prop] = {};
}
}
recurse(data, '');
return result;
}
/**
* isValidJSONObject - checks if the object is a valid JSON object or a valid JSON string
* @param object: the object to be checked
* @returns true if the object is a valid JSON object or a valid JSON string
*/
export function isValidJSONObject(object: any): boolean {
try {
JSON.parse(JSON.stringify(object));
return true;
} catch (e) {
return false;
}
}
| 26.78 | 89 | 0.620239 | 63 | 6 | 0 | 11 | 6 | 0 | 1 | 6 | 9 | 0 | 1 | 10.833333 | 749 | 0.022697 | 0.008011 | 0 | 0 | 0.001335 | 0.26087 | 0.391304 | 0.244738 | /**
* isArrayOfType check if the array contains only the specified type
* @param array: the array to be checked
* @param type: the type to be checked
* @returns true if the array contains only the specified type
*/
export function isArrayOfType(array, type) {
return array.filter((i) => typeof i === type).length === array.length;
}
/**
* range - returns an array of numbers from start to end
* @param start: the start of the range
* @param end: the end of the range
* @param step: the step of the range
* @returns an array of numbers from start to end
*/
export function range(
start,
end,
step = 1,
remove?
) {
// Check if start, end and step are integers
if (
!Number.isInteger(start) ||
!Number.isInteger(end) ||
!Number.isInteger(step)
) {
throw new Error('range parameters must be integers');
}
const rangeArray = [];
// Start must be less than end
if (start > end) {
throw new Error('starting value must be less than end value');
}
// Step must be greater than 0
if (step <= 0) {
throw new Error('step must be greater than 0');
}
// Generate an array from start to end
for (let i = start; i <= end; i += step) {
if (remove) {
if (!remove.includes(i)) {
rangeArray.push(i);
}
} else {
rangeArray.push(i);
}
}
return rangeArray;
}
/**
* flattenJSON - converts a nested JSON object into a simple JSON object
* @param object: the object to be flattened
* @returns the flattened object
*/
// eslint-disable-next-line @typescript-eslint/no-unused-vars
export function flattenJSON(data) {
const result = {};
/* Example usages of 'recurse' are shown below:
recurse(cur[i], prop + '[' + i + ']');
recurse(cur[p], prop ? prop + '.' + p : p);
recurse(data, '');
*/
function recurse(cur, prop) {
if (Object(cur) !== cur) {
result[prop] = cur;
} else if (Array.isArray(cur)) {
// eslint-disable-next-line no-var
for (var i = 0, l = cur.length; i < l; i++)
recurse(cur[i], prop + '[' + i + ']');
if (l == 0) result[prop] = [];
} else {
let isEmpty = true;
for (const p in cur) {
isEmpty = false;
recurse(cur[p], prop ? prop + '.' + p : p);
}
if (isEmpty && prop) result[prop] = {};
}
}
recurse(data, '');
return result;
}
/**
* isValidJSONObject - checks if the object is a valid JSON object or a valid JSON string
* @param object: the object to be checked
* @returns true if the object is a valid JSON object or a valid JSON string
*/
export function isValidJSONObject(object) {
try {
JSON.parse(JSON.stringify(object));
return true;
} catch (e) {
return false;
}
}
|
e6fc9e2bf8ba51a174524542e1ae96dba1e33da4 | 2,904 | ts | TypeScript | src/dapp/utils/supply.ts | JoseRFelix/sunflower-farmers | dde8360c3c3f5620710b7a4cd0af711be65d5735 | [
"MIT"
] | 2 | 2022-02-27T06:06:04.000Z | 2022-03-01T07:14:38.000Z | src/dapp/utils/supply.ts | JoseRFelix/sunflower-farmers | dde8360c3c3f5620710b7a4cd0af711be65d5735 | [
"MIT"
] | null | null | null | src/dapp/utils/supply.ts | JoseRFelix/sunflower-farmers | dde8360c3c3f5620710b7a4cd0af711be65d5735 | [
"MIT"
] | 1 | 2022-01-16T16:43:37.000Z | 2022-01-16T16:43:37.000Z | export function getExchangeRate(supply: number) {
if (supply < 100000) {
return 1;
}
if (supply < 500000) {
return 0.5;
}
if (supply < 1000000) {
return 0.1;
}
if (supply < 5000000) {
return 0.05;
}
if (supply < 10000000) {
return 0.01;
}
if (supply < 50000000) {
return 0.005;
}
if (supply < 100000000) {
return 0.001;
}
if (supply < 500000000) {
return 0.0005;
}
if (supply < 1000000000) {
return 0.0001;
}
// Linear growth
return (1 / supply) * 100000;
}
export function getMarketRate(supply: number) {
if (supply < 100000) {
// 1 Farm Dollar gets you 1 FMC token
return 1;
}
// Less than 500, 000 tokens
if (supply < 500000) {
return 5;
}
// Less than 1, 000, 000 tokens
if (supply < 1000000) {
return 10;
}
// Less than 5, 000, 000 tokens
if (supply < 5000000) {
return 50;
}
// Less than 10, 000, 000 tokens
if (supply < 10000000) {
return 100;
}
// Less than 50, 000, 000 tokens
if (supply < 50000000) {
return 500;
}
// Less than 100, 000, 000 tokens
if (supply < 100000000) {
return 1000;
}
// Less than 500, 000, 000 tokens
if (supply < 500000000) {
return 5000;
}
// Less than 1, 000, 000, 000 tokens
if (supply < 1000000000) {
return 10000;
}
// 1 Farm Dollar gets you a 0.00001 of a token - Linear growth from here
return supply / 10000;
}
interface Threshold {
amount: number;
halveningRate: number;
}
const thresholds: Threshold[] = [
{ amount: 100000, halveningRate: 5 },
{ amount: 500000, halveningRate: 2 },
{ amount: 1000000, halveningRate: 5 },
{ amount: 5000000, halveningRate: 2 },
{ amount: 10000000, halveningRate: 5 },
{ amount: 50000000, halveningRate: 2 },
{ amount: 100000000, halveningRate: 5 },
{ amount: 500000000, halveningRate: 2 },
// Soft supply limit at 1 billion tokens
{ amount: 1000000000, halveningRate: 100000000000000 },
];
export function getHalveningRate(supply: number) {
for (let i = 0; i < thresholds.length; i++) {
if (supply < thresholds[i].amount) {
return thresholds[i].halveningRate;
}
}
return 0;
}
export function getNextHalvingThreshold(supply: number): Threshold {
const currentThresholdIdx = thresholds.findIndex(
(threshold) => supply < threshold.amount
);
if (currentThresholdIdx >= 0) {
return thresholds[currentThresholdIdx];
}
return null;
}
export function getNextMarketRate(supply: number) {
const nextThreshold = getNextHalvingThreshold(supply);
if (nextThreshold) {
return getMarketRate(nextThreshold.amount);
}
}
export function isNearHalvening(supply: number) {
return thresholds.some((threshold) => {
const minWarning = threshold.amount * 0.95;
const maxWarning = threshold.amount * 1.05;
return supply > minWarning && supply < maxWarning;
});
}
| 19.755102 | 74 | 0.634642 | 105 | 8 | 0 | 8 | 6 | 2 | 2 | 0 | 8 | 1 | 0 | 10.25 | 1,200 | 0.013333 | 0.005 | 0.001667 | 0.000833 | 0 | 0 | 0.333333 | 0.219001 | export function getExchangeRate(supply) {
if (supply < 100000) {
return 1;
}
if (supply < 500000) {
return 0.5;
}
if (supply < 1000000) {
return 0.1;
}
if (supply < 5000000) {
return 0.05;
}
if (supply < 10000000) {
return 0.01;
}
if (supply < 50000000) {
return 0.005;
}
if (supply < 100000000) {
return 0.001;
}
if (supply < 500000000) {
return 0.0005;
}
if (supply < 1000000000) {
return 0.0001;
}
// Linear growth
return (1 / supply) * 100000;
}
export /* Example usages of 'getMarketRate' are shown below:
getMarketRate(nextThreshold.amount);
*/
function getMarketRate(supply) {
if (supply < 100000) {
// 1 Farm Dollar gets you 1 FMC token
return 1;
}
// Less than 500, 000 tokens
if (supply < 500000) {
return 5;
}
// Less than 1, 000, 000 tokens
if (supply < 1000000) {
return 10;
}
// Less than 5, 000, 000 tokens
if (supply < 5000000) {
return 50;
}
// Less than 10, 000, 000 tokens
if (supply < 10000000) {
return 100;
}
// Less than 50, 000, 000 tokens
if (supply < 50000000) {
return 500;
}
// Less than 100, 000, 000 tokens
if (supply < 100000000) {
return 1000;
}
// Less than 500, 000, 000 tokens
if (supply < 500000000) {
return 5000;
}
// Less than 1, 000, 000, 000 tokens
if (supply < 1000000000) {
return 10000;
}
// 1 Farm Dollar gets you a 0.00001 of a token - Linear growth from here
return supply / 10000;
}
interface Threshold {
amount;
halveningRate;
}
const thresholds = [
{ amount: 100000, halveningRate: 5 },
{ amount: 500000, halveningRate: 2 },
{ amount: 1000000, halveningRate: 5 },
{ amount: 5000000, halveningRate: 2 },
{ amount: 10000000, halveningRate: 5 },
{ amount: 50000000, halveningRate: 2 },
{ amount: 100000000, halveningRate: 5 },
{ amount: 500000000, halveningRate: 2 },
// Soft supply limit at 1 billion tokens
{ amount: 1000000000, halveningRate: 100000000000000 },
];
export function getHalveningRate(supply) {
for (let i = 0; i < thresholds.length; i++) {
if (supply < thresholds[i].amount) {
return thresholds[i].halveningRate;
}
}
return 0;
}
export /* Example usages of 'getNextHalvingThreshold' are shown below:
getNextHalvingThreshold(supply);
*/
function getNextHalvingThreshold(supply) {
const currentThresholdIdx = thresholds.findIndex(
(threshold) => supply < threshold.amount
);
if (currentThresholdIdx >= 0) {
return thresholds[currentThresholdIdx];
}
return null;
}
export function getNextMarketRate(supply) {
const nextThreshold = getNextHalvingThreshold(supply);
if (nextThreshold) {
return getMarketRate(nextThreshold.amount);
}
}
export function isNearHalvening(supply) {
return thresholds.some((threshold) => {
const minWarning = threshold.amount * 0.95;
const maxWarning = threshold.amount * 1.05;
return supply > minWarning && supply < maxWarning;
});
}
|
5850f70146d2f21fc82cb2955a620b2dbab1cc80 | 2,487 | ts | TypeScript | source/dwi/nodejs-assets/nodejs-project/src/idls/ledger.did.ts | fury02/Difiwallet | 7f4417546b0f51aa76901a720d9d64b392b13452 | [
"MIT"
] | 18 | 2022-01-21T07:50:36.000Z | 2022-01-26T16:33:22.000Z | source/dwi/nodejs-assets/nodejs-project/src/idls/ledger.did.ts | fury02/Difiwallet | 7f4417546b0f51aa76901a720d9d64b392b13452 | [
"MIT"
] | null | null | null | source/dwi/nodejs-assets/nodejs-project/src/idls/ledger.did.ts | fury02/Difiwallet | 7f4417546b0f51aa76901a720d9d64b392b13452 | [
"MIT"
] | null | null | null | /* eslint-disable @typescript-eslint/class-name-casing */
/* eslint-disable camelcase */
/* eslint-disable @typescript-eslint/camelcase */
export default ({ IDL }) => {
const AccountIdentifier = IDL.Text;
const Duration = IDL.Record({ secs: IDL.Nat64, nanos: IDL.Nat32 });
const ArchiveOptions = IDL.Record({
max_message_size_bytes: IDL.Opt(IDL.Nat32),
node_max_memory_size_bytes: IDL.Opt(IDL.Nat32),
controller_id: IDL.Principal,
});
const ICPTs = IDL.Record({ e8s: IDL.Nat64 });
const LedgerCanisterInitPayload = IDL.Record({
send_whitelist: IDL.Vec(IDL.Tuple(IDL.Principal)),
minting_account: AccountIdentifier,
transaction_window: IDL.Opt(Duration),
max_message_size_bytes: IDL.Opt(IDL.Nat32),
archive_options: IDL.Opt(ArchiveOptions),
initial_values: IDL.Vec(IDL.Tuple(AccountIdentifier, ICPTs)),
});
const AccountBalanceArgs = IDL.Record({ account: AccountIdentifier });
const SubAccount = IDL.Vec(IDL.Nat8);
const BlockHeight = IDL.Nat64;
const NotifyCanisterArgs = IDL.Record({
to_subaccount: IDL.Opt(SubAccount),
from_subaccount: IDL.Opt(SubAccount),
to_canister: IDL.Principal,
max_fee: ICPTs,
block_height: BlockHeight,
});
const Memo = IDL.Nat64;
const TimeStamp = IDL.Record({ timestamp_nanos: IDL.Nat64 });
const SendArgs = IDL.Record({
to: AccountIdentifier,
fee: ICPTs,
memo: Memo,
from_subaccount: IDL.Opt(SubAccount),
created_at_time: IDL.Opt(TimeStamp),
amount: ICPTs,
});
return IDL.Service({
account_balance_dfx: IDL.Func([AccountBalanceArgs], [ICPTs], ['query']),
notify_dfx: IDL.Func([NotifyCanisterArgs], [], []),
send_dfx: IDL.Func([SendArgs], [BlockHeight], []),
});
};
export const init = ({ IDL }) => {
const AccountIdentifier = IDL.Text;
const Duration = IDL.Record({ secs: IDL.Nat64, nanos: IDL.Nat32 });
const ArchiveOptions = IDL.Record({
max_message_size_bytes: IDL.Opt(IDL.Nat32),
node_max_memory_size_bytes: IDL.Opt(IDL.Nat32),
controller_id: IDL.Principal,
});
const ICPTs = IDL.Record({ e8s: IDL.Nat64 });
const LedgerCanisterInitPayload = IDL.Record({
send_whitelist: IDL.Vec(IDL.Tuple(IDL.Principal)),
minting_account: AccountIdentifier,
transaction_window: IDL.Opt(Duration),
max_message_size_bytes: IDL.Opt(IDL.Nat32),
archive_options: IDL.Opt(ArchiveOptions),
initial_values: IDL.Vec(IDL.Tuple(AccountIdentifier, ICPTs)),
});
return [LedgerCanisterInitPayload];
};
| 37.681818 | 76 | 0.706072 | 62 | 2 | 0 | 2 | 18 | 0 | 0 | 0 | 0 | 0 | 0 | 29 | 819 | 0.004884 | 0.021978 | 0 | 0 | 0 | 0 | 0 | 0.253366 | /* eslint-disable @typescript-eslint/class-name-casing */
/* eslint-disable camelcase */
/* eslint-disable @typescript-eslint/camelcase */
export default ({ IDL }) => {
const AccountIdentifier = IDL.Text;
const Duration = IDL.Record({ secs: IDL.Nat64, nanos: IDL.Nat32 });
const ArchiveOptions = IDL.Record({
max_message_size_bytes: IDL.Opt(IDL.Nat32),
node_max_memory_size_bytes: IDL.Opt(IDL.Nat32),
controller_id: IDL.Principal,
});
const ICPTs = IDL.Record({ e8s: IDL.Nat64 });
const LedgerCanisterInitPayload = IDL.Record({
send_whitelist: IDL.Vec(IDL.Tuple(IDL.Principal)),
minting_account: AccountIdentifier,
transaction_window: IDL.Opt(Duration),
max_message_size_bytes: IDL.Opt(IDL.Nat32),
archive_options: IDL.Opt(ArchiveOptions),
initial_values: IDL.Vec(IDL.Tuple(AccountIdentifier, ICPTs)),
});
const AccountBalanceArgs = IDL.Record({ account: AccountIdentifier });
const SubAccount = IDL.Vec(IDL.Nat8);
const BlockHeight = IDL.Nat64;
const NotifyCanisterArgs = IDL.Record({
to_subaccount: IDL.Opt(SubAccount),
from_subaccount: IDL.Opt(SubAccount),
to_canister: IDL.Principal,
max_fee: ICPTs,
block_height: BlockHeight,
});
const Memo = IDL.Nat64;
const TimeStamp = IDL.Record({ timestamp_nanos: IDL.Nat64 });
const SendArgs = IDL.Record({
to: AccountIdentifier,
fee: ICPTs,
memo: Memo,
from_subaccount: IDL.Opt(SubAccount),
created_at_time: IDL.Opt(TimeStamp),
amount: ICPTs,
});
return IDL.Service({
account_balance_dfx: IDL.Func([AccountBalanceArgs], [ICPTs], ['query']),
notify_dfx: IDL.Func([NotifyCanisterArgs], [], []),
send_dfx: IDL.Func([SendArgs], [BlockHeight], []),
});
};
export const init = ({ IDL }) => {
const AccountIdentifier = IDL.Text;
const Duration = IDL.Record({ secs: IDL.Nat64, nanos: IDL.Nat32 });
const ArchiveOptions = IDL.Record({
max_message_size_bytes: IDL.Opt(IDL.Nat32),
node_max_memory_size_bytes: IDL.Opt(IDL.Nat32),
controller_id: IDL.Principal,
});
const ICPTs = IDL.Record({ e8s: IDL.Nat64 });
const LedgerCanisterInitPayload = IDL.Record({
send_whitelist: IDL.Vec(IDL.Tuple(IDL.Principal)),
minting_account: AccountIdentifier,
transaction_window: IDL.Opt(Duration),
max_message_size_bytes: IDL.Opt(IDL.Nat32),
archive_options: IDL.Opt(ArchiveOptions),
initial_values: IDL.Vec(IDL.Tuple(AccountIdentifier, ICPTs)),
});
return [LedgerCanisterInitPayload];
};
|
585437ece53451283ff5c57312bb82f4790af54d | 1,837 | ts | TypeScript | libs/ng-esbuild/src/executors/esbuild/lib/create-async-iteratable.ts | Coly010/nx-ng-esbuild | 0fb41aa5c89d3e87f5d916b49321527f1a376bf2 | [
"MIT"
] | 13 | 2022-02-27T08:55:30.000Z | 2022-03-04T13:53:12.000Z | libs/ng-esbuild/src/executors/esbuild/lib/create-async-iteratable.ts | Coly010/nx-ng-esbuild | 0fb41aa5c89d3e87f5d916b49321527f1a376bf2 | [
"MIT"
] | 1 | 2022-03-15T00:39:59.000Z | 2022-03-15T00:39:59.000Z | libs/ng-esbuild/src/executors/esbuild/lib/create-async-iteratable.ts | Coly010/nx-ng-esbuild | 0fb41aa5c89d3e87f5d916b49321527f1a376bf2 | [
"MIT"
] | null | null | null | // FROM https://github.com/nrwl/nx/blob/master/packages/js/src/utils/create-async-iterable/create-async-iteratable.ts
export interface AsyncPushCallbacks<T> {
next: (value: T) => void;
done: () => void;
error: (err: unknown) => void;
}
export function createAsyncIterable<T = unknown>(
listener: (ls: AsyncPushCallbacks<T>) => void
): AsyncIterable<T> {
let done = false;
let error: unknown | null = null;
const pushQueue: T[] = [];
const pullQueue: Array<
[
(x: { value: T | undefined; done: boolean }) => void,
(err: unknown) => void
]
> = [];
return {
[Symbol.asyncIterator]() {
listener({
next: (value) => {
if (done || error) return;
if (pullQueue.length > 0) {
pullQueue.shift()?.[0]({ value, done: false });
} else {
pushQueue.push(value);
}
},
error: (err) => {
if (done || error) return;
if (pullQueue.length > 0) {
pullQueue.shift()?.[1](err);
}
error = err;
},
done: () => {
if (pullQueue.length > 0) {
pullQueue.shift()?.[0]({ value: undefined, done: true });
}
done = true;
},
});
return {
next() {
return new Promise<{ value: T | undefined; done: boolean }>(
(resolve, reject) => {
if (pushQueue.length > 0) {
resolve({ value: pushQueue.shift(), done: false });
} else if (done) {
resolve({ value: undefined, done: true });
} else if (error) {
reject(error);
} else {
pullQueue.push([resolve, reject]);
}
}
);
},
};
},
} as AsyncIterable<T>;
}
| 26.623188 | 117 | 0.468155 | 62 | 7 | 0 | 5 | 4 | 3 | 0 | 0 | 12 | 1 | 1 | 18.571429 | 481 | 0.024948 | 0.008316 | 0.006237 | 0.002079 | 0.002079 | 0 | 0.631579 | 0.25787 | // FROM https://github.com/nrwl/nx/blob/master/packages/js/src/utils/create-async-iterable/create-async-iteratable.ts
export interface AsyncPushCallbacks<T> {
next;
done;
error;
}
export function createAsyncIterable<T = unknown>(
listener
) {
let done = false;
let error = null;
const pushQueue = [];
const pullQueue = [];
return {
[Symbol.asyncIterator]() {
listener({
next: (value) => {
if (done || error) return;
if (pullQueue.length > 0) {
pullQueue.shift()?.[0]({ value, done: false });
} else {
pushQueue.push(value);
}
},
error: (err) => {
if (done || error) return;
if (pullQueue.length > 0) {
pullQueue.shift()?.[1](err);
}
error = err;
},
done: () => {
if (pullQueue.length > 0) {
pullQueue.shift()?.[0]({ value: undefined, done: true });
}
done = true;
},
});
return {
next() {
return new Promise<{ value; done }>(
(resolve, reject) => {
if (pushQueue.length > 0) {
resolve({ value: pushQueue.shift(), done: false });
} else if (done) {
resolve({ value: undefined, done: true });
} else if (error) {
reject(error);
} else {
pullQueue.push([resolve, reject]);
}
}
);
},
};
},
} as AsyncIterable<T>;
}
|
5854bf3dea0d67d8667446aaccf3a64dd1f826ee | 2,654 | ts | TypeScript | src/navability/entities/Factor.ts | NavAbility/NavAbilitySDK.js | e651728b99fa61c564bdb35a4280cb26227f1c51 | [
"Apache-2.0"
] | null | null | null | src/navability/entities/Factor.ts | NavAbility/NavAbilitySDK.js | e651728b99fa61c564bdb35a4280cb26227f1c51 | [
"Apache-2.0"
] | 20 | 2022-01-17T17:30:45.000Z | 2022-03-31T11:52:45.000Z | src/navability/entities/Factor.ts | NavAbility/NavAbilitySDK.js | e651728b99fa61c564bdb35a4280cb26227f1c51 | [
"Apache-2.0"
] | null | null | null | const DFG_VERSION = '0.18.1';
const PI = 3.14159;
export enum FactorType {
PRIORPOSE2 = 'PriorPose2',
POSE2POSE2 = 'Pose2Pose2',
POSE2APRILTAG4CORNERS = 'Pose2AprilTag4Corners',
}
type FactorData = {
eliminated: boolean;
potentialused: boolean;
edgeIDs: string[];
fnc: any;
multihypo: number[];
certainhypo: number[];
nullhypo: number;
solveInProgress: number;
inflation: number;
};
export type Factor = {
label: string;
nstime: string;
fnctype: string;
_variableOrderSymbols: string[];
data: FactorData;
solvable: number;
tags: string[];
timestamp: string;
_version: string;
};
function InitializeFactorData(): FactorData {
return {
eliminated: false,
potentialused: false,
edgeIDs: [],
fnc: {},
multihypo: [],
certainhypo: [],
nullhypo: 0.0,
solveInProgress: 0,
inflation: 3.0,
};
}
export function PriorPose2Data(xythetaPrior = [0.0, 0.0, 0.0], xythetaCovars = [0.01, 0.01, 0.01]): FactorData {
const fnc = {
Z: {
_type: 'IncrementalInference.PackedFullNormal',
mu: xythetaPrior,
cov: [xythetaCovars[0], 0.0, 0.0, 0.0, xythetaCovars[1], 0.0, 0.0, 0.0, xythetaCovars[2]],
},
};
const data = InitializeFactorData();
data.fnc = fnc;
data.certainhypo = [1];
return data;
}
export function Pose2Pose2Data(mus = [1, 0, 0.3333 * PI], sigmas = [0.01, 0.01, 0.01]): FactorData {
const fnc = {
Z: {
_type: 'IncrementalInference.PackedFullNormal',
mu: mus,
cov: [sigmas[0], 0.0, 0.0, 0.0, sigmas[1], 0.0, 0.0, 0.0, sigmas[2]],
},
};
const data = InitializeFactorData();
data.fnc = fnc;
data.certainhypo = [1, 2];
return data;
}
export function Pose2AprilTag4CornersData(
id: number,
corners: number[],
homography: number[],
K: number[] = [300.0, 0.0, 0.0, 0.0, 300.0, 0.0, 180.0, 120.0, 1.0],
taglength: number = 0.25,
): FactorData {
const fnc = {
_type: '/application/JuliaLang/PackedPose2AprilTag4Corners',
corners,
homography,
K,
taglength,
id,
};
const data = InitializeFactorData();
data.fnc = fnc;
data.certainhypo = [1, 2];
return data;
}
export function Factor(
label: string,
fncType: string,
variableOrderSymbols: string[],
data: FactorData,
tags: string[] = ['FACTOR'],
timestamp: string = new Date().toISOString(),
): Factor {
data.certainhypo = variableOrderSymbols.map((x, idx) => idx + 1);
const result: Factor = {
label,
nstime: '0',
fnctype: fncType,
_variableOrderSymbols: variableOrderSymbols,
data,
solvable: 1,
tags,
timestamp,
_version: DFG_VERSION,
};
return result;
}
| 22.116667 | 112 | 0.633384 | 110 | 6 | 0 | 17 | 9 | 18 | 1 | 1 | 26 | 2 | 0 | 9.833333 | 967 | 0.023785 | 0.009307 | 0.018614 | 0.002068 | 0 | 0.02 | 0.52 | 0.258722 | const DFG_VERSION = '0.18.1';
const PI = 3.14159;
export enum FactorType {
PRIORPOSE2 = 'PriorPose2',
POSE2POSE2 = 'Pose2Pose2',
POSE2APRILTAG4CORNERS = 'Pose2AprilTag4Corners',
}
type FactorData = {
eliminated;
potentialused;
edgeIDs;
fnc;
multihypo;
certainhypo;
nullhypo;
solveInProgress;
inflation;
};
export type Factor = {
label;
nstime;
fnctype;
_variableOrderSymbols;
data;
solvable;
tags;
timestamp;
_version;
};
/* Example usages of 'InitializeFactorData' are shown below:
InitializeFactorData();
*/
function InitializeFactorData() {
return {
eliminated: false,
potentialused: false,
edgeIDs: [],
fnc: {},
multihypo: [],
certainhypo: [],
nullhypo: 0.0,
solveInProgress: 0,
inflation: 3.0,
};
}
export function PriorPose2Data(xythetaPrior = [0.0, 0.0, 0.0], xythetaCovars = [0.01, 0.01, 0.01]) {
const fnc = {
Z: {
_type: 'IncrementalInference.PackedFullNormal',
mu: xythetaPrior,
cov: [xythetaCovars[0], 0.0, 0.0, 0.0, xythetaCovars[1], 0.0, 0.0, 0.0, xythetaCovars[2]],
},
};
const data = InitializeFactorData();
data.fnc = fnc;
data.certainhypo = [1];
return data;
}
export function Pose2Pose2Data(mus = [1, 0, 0.3333 * PI], sigmas = [0.01, 0.01, 0.01]) {
const fnc = {
Z: {
_type: 'IncrementalInference.PackedFullNormal',
mu: mus,
cov: [sigmas[0], 0.0, 0.0, 0.0, sigmas[1], 0.0, 0.0, 0.0, sigmas[2]],
},
};
const data = InitializeFactorData();
data.fnc = fnc;
data.certainhypo = [1, 2];
return data;
}
export function Pose2AprilTag4CornersData(
id,
corners,
homography,
K = [300.0, 0.0, 0.0, 0.0, 300.0, 0.0, 180.0, 120.0, 1.0],
taglength = 0.25,
) {
const fnc = {
_type: '/application/JuliaLang/PackedPose2AprilTag4Corners',
corners,
homography,
K,
taglength,
id,
};
const data = InitializeFactorData();
data.fnc = fnc;
data.certainhypo = [1, 2];
return data;
}
export /* Example usages of 'Factor' are shown below:
;
*/
function Factor(
label,
fncType,
variableOrderSymbols,
data,
tags = ['FACTOR'],
timestamp = new Date().toISOString(),
) {
data.certainhypo = variableOrderSymbols.map((x, idx) => idx + 1);
const result = {
label,
nstime: '0',
fnctype: fncType,
_variableOrderSymbols: variableOrderSymbols,
data,
solvable: 1,
tags,
timestamp,
_version: DFG_VERSION,
};
return result;
}
|
5866293cf9bf64693f791c4e69269e74d02b52a1 | 1,274 | ts | TypeScript | src/api/graphql/user.graphql.ts | joker-crypto/PUP-Facuty-Workload | 3840e2833c5f50fbdbf9b13ae6214fbb81e8c157 | [
"MIT"
] | null | null | null | src/api/graphql/user.graphql.ts | joker-crypto/PUP-Facuty-Workload | 3840e2833c5f50fbdbf9b13ae6214fbb81e8c157 | [
"MIT"
] | null | null | null | src/api/graphql/user.graphql.ts | joker-crypto/PUP-Facuty-Workload | 3840e2833c5f50fbdbf9b13ae6214fbb81e8c157 | [
"MIT"
] | 1 | 2022-02-12T02:16:15.000Z | 2022-02-12T02:16:15.000Z | /* eslint-disable @typescript-eslint/no-explicit-any */
/* eslint-disable import/prefer-default-export */
export const listUserGQL = () => {
return `
query {
users {
id
userType
email
created_at
blocked
confirmed
support {
id
fullName
}
customer {
id
personal_info {
fullName
}
}
agent {
id
personalInfo {
fullName
}
}
}
}
`;
};
export const getUserGQL = (id: string) => {
return `
query {
user(id: ${id}) {
id
userType
email
created_at
blocked
confirmed
support {
id
fullName
}
customer {
id
personal_info {
fullName
mobile
}
}
agent {
id
personalInfo{
fullName
mobile
}
}
}
}
`;
};
export const archivedUserGQL = (data: any) => {
return `
mutation {
updateUser(input: { where: { id: ${data.id} }, data: { blocked: true } }) {
user {
id
}
}
}
`;
};
| 16.333333 | 81 | 0.397174 | 73 | 3 | 0 | 2 | 3 | 0 | 0 | 1 | 1 | 0 | 0 | 22.333333 | 272 | 0.018382 | 0.011029 | 0 | 0 | 0 | 0.125 | 0.125 | 0.247005 | /* eslint-disable @typescript-eslint/no-explicit-any */
/* eslint-disable import/prefer-default-export */
export const listUserGQL = () => {
return `
query {
users {
id
userType
email
created_at
blocked
confirmed
support {
id
fullName
}
customer {
id
personal_info {
fullName
}
}
agent {
id
personalInfo {
fullName
}
}
}
}
`;
};
export const getUserGQL = (id) => {
return `
query {
user(id: ${id}) {
id
userType
email
created_at
blocked
confirmed
support {
id
fullName
}
customer {
id
personal_info {
fullName
mobile
}
}
agent {
id
personalInfo{
fullName
mobile
}
}
}
}
`;
};
export const archivedUserGQL = (data) => {
return `
mutation {
updateUser(input: { where: { id: ${data.id} }, data: { blocked: true } }) {
user {
id
}
}
}
`;
};
|
58b8df9791760f314fc7060ea1e190197a2793f1 | 2,291 | ts | TypeScript | src/compiler/jxalib/index.ts | potsbo/jxa-graphql | 0a5be7100babaedaa7297c367fca9b15a930c56e | [
"MIT"
] | 18 | 2022-03-06T14:12:25.000Z | 2022-03-15T11:32:58.000Z | src/compiler/jxalib/index.ts | potsbo/jxa-graphql | 0a5be7100babaedaa7297c367fca9b15a930c56e | [
"MIT"
] | 19 | 2022-02-26T14:31:14.000Z | 2022-03-06T09:22:52.000Z | src/compiler/jxalib/index.ts | potsbo/jxa-graphql | 0a5be7100babaedaa7297c367fca9b15a930c56e | [
"MIT"
] | null | null | null | const AVAILABLES = {
extractClass,
extractId,
paginate,
} as const;
export type AvailableKeys = keyof typeof AVAILABLES;
export const buildLibrary = (dependencies: Set<AvailableKeys>) => {
const keys = Array.from(dependencies.values()).sort();
return keys.map((k) => AVAILABLES[k].toString()).join("\n");
};
export const library = `
${extractClass.toString()}
${extractId.toString()}
${paginate.toString()}
`;
export const FUNCS = {
extractClass: {
kind: "FunctionDependency",
name: "extractClass",
},
extractId: {
kind: "FunctionDependency",
name: "extractId",
},
paginate: {
kind: "FunctionDependency",
name: "paginate",
},
} as const;
declare const Automation: {
getDisplayString: (obj: unknown) => string | undefined;
};
declare const ObjectSpecifier: {
classOf: (obj: unknown) => string | undefined;
};
/* eslint-disable @typescript-eslint/no-non-null-assertion */
function extractClass(obj: unknown) {
const s = ObjectSpecifier.classOf(eval(Automation.getDisplayString(obj)!))!;
return (s.match(/[a-zA-Z0-9]+/g) || []).map((w) => `${w[0].toUpperCase()}${w.slice(1)}`).join("");
}
/* eslint-enable @typescript-eslint/no-non-null-assertion */
function extractId(obj: unknown) {
const spec = Automation.getDisplayString(obj);
if (spec === undefined) {
return null;
}
let inStr = false;
let ret = "";
let nextEscape = null;
for (let i = 0; i < spec.length; i++) {
const c = spec[i];
const inEscape = nextEscape === i;
if (c === "\\") {
nextEscape = i + 1;
continue;
}
if (!inEscape && c === '"') {
inStr = !inStr;
continue;
}
if (!inStr) {
if (c === "(") {
ret = "";
continue;
}
if (c === ")") {
continue;
}
}
ret = `${ret}${c}`;
}
return ret !== "" ? ret : null;
}
function paginate<T>(nodes: T[], { first, after }: { first?: number; after?: string }, getId: (elm: T) => string): T[] {
const afterIndex = after === undefined ? undefined : nodes.findIndex((n) => getId(n) === after);
if (afterIndex === -1) {
return [];
}
const start = afterIndex === undefined ? 0 : afterIndex + 1;
const end = first !== undefined ? start + first : undefined;
return nodes.slice(start, end);
}
| 24.37234 | 120 | 0.591445 | 80 | 7 | 0 | 9 | 18 | 0 | 0 | 0 | 9 | 1 | 3 | 6.285714 | 675 | 0.023704 | 0.026667 | 0 | 0.001481 | 0.004444 | 0 | 0.264706 | 0.31402 | const AVAILABLES = {
extractClass,
extractId,
paginate,
} as const;
export type AvailableKeys = keyof typeof AVAILABLES;
export const buildLibrary = (dependencies) => {
const keys = Array.from(dependencies.values()).sort();
return keys.map((k) => AVAILABLES[k].toString()).join("\n");
};
export const library = `
${extractClass.toString()}
${extractId.toString()}
${paginate.toString()}
`;
export const FUNCS = {
extractClass: {
kind: "FunctionDependency",
name: "extractClass",
},
extractId: {
kind: "FunctionDependency",
name: "extractId",
},
paginate: {
kind: "FunctionDependency",
name: "paginate",
},
} as const;
declare const Automation;
declare const ObjectSpecifier;
/* eslint-disable @typescript-eslint/no-non-null-assertion */
/* Example usages of 'extractClass' are shown below:
;
extractClass.toString();
*/
function extractClass(obj) {
const s = ObjectSpecifier.classOf(eval(Automation.getDisplayString(obj)!))!;
return (s.match(/[a-zA-Z0-9]+/g) || []).map((w) => `${w[0].toUpperCase()}${w.slice(1)}`).join("");
}
/* eslint-enable @typescript-eslint/no-non-null-assertion */
/* Example usages of 'extractId' are shown below:
;
extractId.toString();
*/
function extractId(obj) {
const spec = Automation.getDisplayString(obj);
if (spec === undefined) {
return null;
}
let inStr = false;
let ret = "";
let nextEscape = null;
for (let i = 0; i < spec.length; i++) {
const c = spec[i];
const inEscape = nextEscape === i;
if (c === "\\") {
nextEscape = i + 1;
continue;
}
if (!inEscape && c === '"') {
inStr = !inStr;
continue;
}
if (!inStr) {
if (c === "(") {
ret = "";
continue;
}
if (c === ")") {
continue;
}
}
ret = `${ret}${c}`;
}
return ret !== "" ? ret : null;
}
/* Example usages of 'paginate' are shown below:
;
paginate.toString();
*/
function paginate<T>(nodes, { first, after }, getId) {
const afterIndex = after === undefined ? undefined : nodes.findIndex((n) => getId(n) === after);
if (afterIndex === -1) {
return [];
}
const start = afterIndex === undefined ? 0 : afterIndex + 1;
const end = first !== undefined ? start + first : undefined;
return nodes.slice(start, end);
}
|
58c7c373256854e72d351e5168b3896e46c295f4 | 2,050 | tsx | TypeScript | src/components/Landing/utils.tsx | sintel-dev/MTV | f5d882b6e5259b084a789a6b13d4131c13c0d818 | [
"MIT"
] | null | null | null | src/components/Landing/utils.tsx | sintel-dev/MTV | f5d882b6e5259b084a789a6b13d4131c13c0d818 | [
"MIT"
] | 1 | 2022-03-11T02:41:47.000Z | 2022-03-11T02:41:47.000Z | src/components/Landing/utils.tsx | sintel-dev/MTV | f5d882b6e5259b084a789a6b13d4131c13c0d818 | [
"MIT"
] | null | null | null | export const colorSchemes = {
tag: [
'#FF9100', // investigate
'#4684FF', // do not investigate
'#8446C2', // postpone
'#C24D4D', // problem
'#F2FF00', // previously seen
'#6BC969', // normal
'#D5D5D5', // untagged
],
};
// @TODO - later investigation for refactoring (fromIDToTag/fromTagToId)
export const tagSeq: Array<string> = [
'Investigate',
'Do not Investigate',
'Postpone',
'Problem',
'Previously seen',
'Normal',
'Untagged',
];
const tagClassNames: Array<string> = [
'investigate',
'do_not_investigate',
'postpone',
'problem',
'previously_seen',
'normal',
'untagged',
];
export const fromTagToClassName = (tag: string): string => {
switch (tag) {
case tagSeq[0]:
return tagClassNames[0];
case tagSeq[1]:
return tagClassNames[1];
case tagSeq[2]:
return tagClassNames[2];
case tagSeq[3]:
return tagClassNames[3];
case tagSeq[4]:
return tagClassNames[4];
case tagSeq[5]:
return tagClassNames[5];
default:
return 'untagged';
}
};
export const fromIDtoTag = (id: string): string => {
switch (id) {
case '1':
return tagSeq[0];
case '2':
return tagSeq[1];
case '3':
return tagSeq[2];
case '4':
return tagSeq[3];
case '5':
return tagSeq[4];
case '6':
return tagSeq[5];
default:
return 'untagged';
}
};
export const fromTagToID = (tag: string): string => {
switch (tag) {
case tagSeq[0]:
return '1';
case tagSeq[1]:
return '2';
case tagSeq[2]:
return '3';
case tagSeq[3]:
return '4';
case tagSeq[4]:
return '5';
case tagSeq[5]:
return '6';
default:
return 'untagged';
}
};
export const getTagColor = (tag: string): string => {
let colorIdx: number | undefined;
for (let i = 0; i < tagSeq.length; i += 1) {
if (tagSeq[i] === tag) {
colorIdx = i;
}
}
if (colorIdx === undefined) {
colorIdx = 6;
}
return colorSchemes.tag[colorIdx];
};
| 20.098039 | 72 | 0.569756 | 95 | 4 | 0 | 4 | 9 | 0 | 0 | 0 | 11 | 0 | 0 | 14.5 | 657 | 0.012177 | 0.013699 | 0 | 0 | 0 | 0 | 0.647059 | 0.242482 | export const colorSchemes = {
tag: [
'#FF9100', // investigate
'#4684FF', // do not investigate
'#8446C2', // postpone
'#C24D4D', // problem
'#F2FF00', // previously seen
'#6BC969', // normal
'#D5D5D5', // untagged
],
};
// @TODO - later investigation for refactoring (fromIDToTag/fromTagToId)
export const tagSeq = [
'Investigate',
'Do not Investigate',
'Postpone',
'Problem',
'Previously seen',
'Normal',
'Untagged',
];
const tagClassNames = [
'investigate',
'do_not_investigate',
'postpone',
'problem',
'previously_seen',
'normal',
'untagged',
];
export const fromTagToClassName = (tag) => {
switch (tag) {
case tagSeq[0]:
return tagClassNames[0];
case tagSeq[1]:
return tagClassNames[1];
case tagSeq[2]:
return tagClassNames[2];
case tagSeq[3]:
return tagClassNames[3];
case tagSeq[4]:
return tagClassNames[4];
case tagSeq[5]:
return tagClassNames[5];
default:
return 'untagged';
}
};
export const fromIDtoTag = (id) => {
switch (id) {
case '1':
return tagSeq[0];
case '2':
return tagSeq[1];
case '3':
return tagSeq[2];
case '4':
return tagSeq[3];
case '5':
return tagSeq[4];
case '6':
return tagSeq[5];
default:
return 'untagged';
}
};
export const fromTagToID = (tag) => {
switch (tag) {
case tagSeq[0]:
return '1';
case tagSeq[1]:
return '2';
case tagSeq[2]:
return '3';
case tagSeq[3]:
return '4';
case tagSeq[4]:
return '5';
case tagSeq[5]:
return '6';
default:
return 'untagged';
}
};
export const getTagColor = (tag) => {
let colorIdx;
for (let i = 0; i < tagSeq.length; i += 1) {
if (tagSeq[i] === tag) {
colorIdx = i;
}
}
if (colorIdx === undefined) {
colorIdx = 6;
}
return colorSchemes.tag[colorIdx];
};
|
58d26ac69de0b89cdf6c6dc3f7ab85a14b25f87a | 5,398 | ts | TypeScript | source/dwi/nodejs-assets/nodejs-project/src/idls/nns_uid.did.ts | fury02/Difiwallet | 7f4417546b0f51aa76901a720d9d64b392b13452 | [
"MIT"
] | 18 | 2022-01-21T07:50:36.000Z | 2022-01-26T16:33:22.000Z | source/dwi/nodejs-assets/nodejs-project/src/idls/nns_uid.did.ts | fury02/Difiwallet | 7f4417546b0f51aa76901a720d9d64b392b13452 | [
"MIT"
] | null | null | null | source/dwi/nodejs-assets/nodejs-project/src/idls/nns_uid.did.ts | fury02/Difiwallet | 7f4417546b0f51aa76901a720d9d64b392b13452 | [
"MIT"
] | null | null | null | /* eslint-disable @typescript-eslint/class-name-casing */
/* eslint-disable camelcase */
/* eslint-disable @typescript-eslint/camelcase */
export default ({ IDL }) => {
const AccountIdentifier = IDL.Text;
const AttachCanisterRequest = IDL.Record({
name: IDL.Text,
canister_id: IDL.Principal,
});
const AttachCanisterResponse = IDL.Variant({
Ok: IDL.Null,
CanisterAlreadyAttached: IDL.Null,
NameAlreadyTaken: IDL.Null,
NameTooLong: IDL.Null,
CanisterLimitExceeded: IDL.Null,
});
const SubAccount = IDL.Vec(IDL.Nat8);
const SubAccountDetails = IDL.Record({
name: IDL.Text,
sub_account: SubAccount,
account_identifier: AccountIdentifier,
});
const CreateSubAccountResponse = IDL.Variant({
Ok: SubAccountDetails,
AccountNotFound: IDL.Null,
NameTooLong: IDL.Null,
SubAccountLimitExceeded: IDL.Null,
});
const DetachCanisterRequest = IDL.Record({ canister_id: IDL.Principal });
const DetachCanisterResponse = IDL.Variant({
Ok: IDL.Null,
CanisterNotFound: IDL.Null,
});
const HardwareWalletAccountDetails = IDL.Record({
name: IDL.Text,
account_identifier: AccountIdentifier,
});
const AccountDetails = IDL.Record({
account_identifier: AccountIdentifier,
hardware_wallet_accounts: IDL.Vec(HardwareWalletAccountDetails),
sub_accounts: IDL.Vec(SubAccountDetails),
});
const GetAccountResponse = IDL.Variant({
Ok: AccountDetails,
AccountNotFound: IDL.Null,
});
const CanisterDetails = IDL.Record({
name: IDL.Text,
canister_id: IDL.Principal,
});
const BlockHeight = IDL.Nat64;
const Stats = IDL.Record({
latest_transaction_block_height: BlockHeight,
seconds_since_last_ledger_sync: IDL.Nat64,
sub_accounts_count: IDL.Nat64,
hardware_wallet_accounts_count: IDL.Nat64,
accounts_count: IDL.Nat64,
earliest_transaction_block_height: BlockHeight,
transactions_count: IDL.Nat64,
block_height_synced_up_to: IDL.Opt(IDL.Nat64),
latest_transaction_timestamp_nanos: IDL.Nat64,
earliest_transaction_timestamp_nanos: IDL.Nat64,
});
const GetTransactionsRequest = IDL.Record({
page_size: IDL.Nat8,
offset: IDL.Nat32,
account_identifier: AccountIdentifier,
});
const Timestamp = IDL.Record({ timestamp_nanos: IDL.Nat64 });
const ICPTs = IDL.Record({ e8s: IDL.Nat64 });
const Send = IDL.Record({
to: AccountIdentifier,
fee: ICPTs,
amount: ICPTs,
});
const Receive = IDL.Record({
fee: ICPTs,
from: AccountIdentifier,
amount: ICPTs,
});
const Transfer = IDL.Variant({
Burn: IDL.Record({ amount: ICPTs }),
Mint: IDL.Record({ amount: ICPTs }),
Send,
Receive,
});
const Transaction = IDL.Record({
memo: IDL.Nat64,
timestamp: Timestamp,
block_height: BlockHeight,
transfer: Transfer,
});
const GetTransactionsResponse = IDL.Record({
total: IDL.Nat32,
transactions: IDL.Vec(Transaction),
});
const HeaderField = IDL.Tuple(IDL.Text, IDL.Text);
const HttpRequest = IDL.Record({
url: IDL.Text,
method: IDL.Text,
body: IDL.Vec(IDL.Nat8),
headers: IDL.Vec(HeaderField),
});
const HttpResponse = IDL.Record({
body: IDL.Vec(IDL.Nat8),
headers: IDL.Vec(HeaderField),
status_code: IDL.Nat16,
});
const RegisterHardwareWalletRequest = IDL.Record({
name: IDL.Text,
account_identifier: AccountIdentifier,
});
const RegisterHardwareWalletResponse = IDL.Variant({
Ok: IDL.Null,
AccountNotFound: IDL.Null,
HardwareWalletAlreadyRegistered: IDL.Null,
HardwareWalletLimitExceeded: IDL.Null,
NameTooLong: IDL.Null,
});
const RemoveHardwareWalletRequest = IDL.Record({
account_identifier: AccountIdentifier,
});
const RemoveHardwareWalletResponse = IDL.Variant({
Ok: IDL.Null,
HardwareWalletNotFound: IDL.Null,
});
const RenameSubAccountRequest = IDL.Record({
new_name: IDL.Text,
account_identifier: AccountIdentifier,
});
const RenameSubAccountResponse = IDL.Variant({
Ok: IDL.Null,
AccountNotFound: IDL.Null,
SubAccountNotFound: IDL.Null,
NameTooLong: IDL.Null,
});
return IDL.Service({
add_account: IDL.Func([], [AccountIdentifier], []),
attach_canister: IDL.Func(
[AttachCanisterRequest],
[AttachCanisterResponse],
[]
),
create_sub_account: IDL.Func([IDL.Text], [CreateSubAccountResponse], []),
detach_canister: IDL.Func(
[DetachCanisterRequest],
[DetachCanisterResponse],
[]
),
get_account: IDL.Func([], [GetAccountResponse], ['query']),
get_canisters: IDL.Func([], [IDL.Vec(CanisterDetails)], ['query']),
get_icp_to_cycles_conversion_rate: IDL.Func([], [IDL.Nat64], ['query']),
get_stats: IDL.Func([], [Stats], ['query']),
get_transactions: IDL.Func(
[GetTransactionsRequest],
[GetTransactionsResponse],
['query']
),
http_request: IDL.Func([HttpRequest], [HttpResponse], ['query']),
register_hardware_wallet: IDL.Func(
[RegisterHardwareWalletRequest],
[RegisterHardwareWalletResponse],
[]
),
remove_hardware_wallet: IDL.Func(
[RemoveHardwareWalletRequest],
[RemoveHardwareWalletResponse],
[]
),
rename_sub_account: IDL.Func(
[RenameSubAccountRequest],
[RenameSubAccountResponse],
[]
),
});
};
export const init = _arg => {
return [];
};
| 29.988889 | 77 | 0.684328 | 176 | 2 | 0 | 2 | 32 | 0 | 0 | 0 | 0 | 0 | 0 | 86 | 1,586 | 0.002522 | 0.020177 | 0 | 0 | 0 | 0 | 0 | 0.242219 | /* eslint-disable @typescript-eslint/class-name-casing */
/* eslint-disable camelcase */
/* eslint-disable @typescript-eslint/camelcase */
export default ({ IDL }) => {
const AccountIdentifier = IDL.Text;
const AttachCanisterRequest = IDL.Record({
name: IDL.Text,
canister_id: IDL.Principal,
});
const AttachCanisterResponse = IDL.Variant({
Ok: IDL.Null,
CanisterAlreadyAttached: IDL.Null,
NameAlreadyTaken: IDL.Null,
NameTooLong: IDL.Null,
CanisterLimitExceeded: IDL.Null,
});
const SubAccount = IDL.Vec(IDL.Nat8);
const SubAccountDetails = IDL.Record({
name: IDL.Text,
sub_account: SubAccount,
account_identifier: AccountIdentifier,
});
const CreateSubAccountResponse = IDL.Variant({
Ok: SubAccountDetails,
AccountNotFound: IDL.Null,
NameTooLong: IDL.Null,
SubAccountLimitExceeded: IDL.Null,
});
const DetachCanisterRequest = IDL.Record({ canister_id: IDL.Principal });
const DetachCanisterResponse = IDL.Variant({
Ok: IDL.Null,
CanisterNotFound: IDL.Null,
});
const HardwareWalletAccountDetails = IDL.Record({
name: IDL.Text,
account_identifier: AccountIdentifier,
});
const AccountDetails = IDL.Record({
account_identifier: AccountIdentifier,
hardware_wallet_accounts: IDL.Vec(HardwareWalletAccountDetails),
sub_accounts: IDL.Vec(SubAccountDetails),
});
const GetAccountResponse = IDL.Variant({
Ok: AccountDetails,
AccountNotFound: IDL.Null,
});
const CanisterDetails = IDL.Record({
name: IDL.Text,
canister_id: IDL.Principal,
});
const BlockHeight = IDL.Nat64;
const Stats = IDL.Record({
latest_transaction_block_height: BlockHeight,
seconds_since_last_ledger_sync: IDL.Nat64,
sub_accounts_count: IDL.Nat64,
hardware_wallet_accounts_count: IDL.Nat64,
accounts_count: IDL.Nat64,
earliest_transaction_block_height: BlockHeight,
transactions_count: IDL.Nat64,
block_height_synced_up_to: IDL.Opt(IDL.Nat64),
latest_transaction_timestamp_nanos: IDL.Nat64,
earliest_transaction_timestamp_nanos: IDL.Nat64,
});
const GetTransactionsRequest = IDL.Record({
page_size: IDL.Nat8,
offset: IDL.Nat32,
account_identifier: AccountIdentifier,
});
const Timestamp = IDL.Record({ timestamp_nanos: IDL.Nat64 });
const ICPTs = IDL.Record({ e8s: IDL.Nat64 });
const Send = IDL.Record({
to: AccountIdentifier,
fee: ICPTs,
amount: ICPTs,
});
const Receive = IDL.Record({
fee: ICPTs,
from: AccountIdentifier,
amount: ICPTs,
});
const Transfer = IDL.Variant({
Burn: IDL.Record({ amount: ICPTs }),
Mint: IDL.Record({ amount: ICPTs }),
Send,
Receive,
});
const Transaction = IDL.Record({
memo: IDL.Nat64,
timestamp: Timestamp,
block_height: BlockHeight,
transfer: Transfer,
});
const GetTransactionsResponse = IDL.Record({
total: IDL.Nat32,
transactions: IDL.Vec(Transaction),
});
const HeaderField = IDL.Tuple(IDL.Text, IDL.Text);
const HttpRequest = IDL.Record({
url: IDL.Text,
method: IDL.Text,
body: IDL.Vec(IDL.Nat8),
headers: IDL.Vec(HeaderField),
});
const HttpResponse = IDL.Record({
body: IDL.Vec(IDL.Nat8),
headers: IDL.Vec(HeaderField),
status_code: IDL.Nat16,
});
const RegisterHardwareWalletRequest = IDL.Record({
name: IDL.Text,
account_identifier: AccountIdentifier,
});
const RegisterHardwareWalletResponse = IDL.Variant({
Ok: IDL.Null,
AccountNotFound: IDL.Null,
HardwareWalletAlreadyRegistered: IDL.Null,
HardwareWalletLimitExceeded: IDL.Null,
NameTooLong: IDL.Null,
});
const RemoveHardwareWalletRequest = IDL.Record({
account_identifier: AccountIdentifier,
});
const RemoveHardwareWalletResponse = IDL.Variant({
Ok: IDL.Null,
HardwareWalletNotFound: IDL.Null,
});
const RenameSubAccountRequest = IDL.Record({
new_name: IDL.Text,
account_identifier: AccountIdentifier,
});
const RenameSubAccountResponse = IDL.Variant({
Ok: IDL.Null,
AccountNotFound: IDL.Null,
SubAccountNotFound: IDL.Null,
NameTooLong: IDL.Null,
});
return IDL.Service({
add_account: IDL.Func([], [AccountIdentifier], []),
attach_canister: IDL.Func(
[AttachCanisterRequest],
[AttachCanisterResponse],
[]
),
create_sub_account: IDL.Func([IDL.Text], [CreateSubAccountResponse], []),
detach_canister: IDL.Func(
[DetachCanisterRequest],
[DetachCanisterResponse],
[]
),
get_account: IDL.Func([], [GetAccountResponse], ['query']),
get_canisters: IDL.Func([], [IDL.Vec(CanisterDetails)], ['query']),
get_icp_to_cycles_conversion_rate: IDL.Func([], [IDL.Nat64], ['query']),
get_stats: IDL.Func([], [Stats], ['query']),
get_transactions: IDL.Func(
[GetTransactionsRequest],
[GetTransactionsResponse],
['query']
),
http_request: IDL.Func([HttpRequest], [HttpResponse], ['query']),
register_hardware_wallet: IDL.Func(
[RegisterHardwareWalletRequest],
[RegisterHardwareWalletResponse],
[]
),
remove_hardware_wallet: IDL.Func(
[RemoveHardwareWalletRequest],
[RemoveHardwareWalletResponse],
[]
),
rename_sub_account: IDL.Func(
[RenameSubAccountRequest],
[RenameSubAccountResponse],
[]
),
});
};
export const init = _arg => {
return [];
};
|
58f2b078c66664f034b52162e751abed0e9f1cdf | 1,839 | ts | TypeScript | src/errors.ts | michaelwclark/mongodb-atlas-data-api-sdk | 6e8f545b893d6a05437099f439891853b0a99be7 | [
"MIT"
] | 2 | 2022-01-25T17:35:35.000Z | 2022-03-24T11:40:38.000Z | src/errors.ts | michaelwclark/mongodb-atlas-data-api-sdk | 6e8f545b893d6a05437099f439891853b0a99be7 | [
"MIT"
] | null | null | null | src/errors.ts | michaelwclark/mongodb-atlas-data-api-sdk | 6e8f545b893d6a05437099f439891853b0a99be7 | [
"MIT"
] | 1 | 2022-01-25T17:47:28.000Z | 2022-01-25T17:47:28.000Z | export class BadRequest extends Error {
description: string;
code: number;
type: string;
constructor ({ message, code, type }) {
super(message)
this.name = 'BadRequest'
this.description = `
The request was invalid. This might mean:
- A request header is missing.
- The request body is malformed or improperly encoded.
- A field has a value with an invalid type.
- The specified data source is disabled or does not exist.
- The specified database or collection does not exist.
`
this.code = code
this.type = type
}
}
export class Unauthorized extends Error {
description: string;
code: number;
type: string;
constructor ({ message, code, type }) {
super(message)
this.name = 'Unauthorized'
this.description = 'The request did not include an authorized and enabled Data API Key. Ensure that your Data API Key is enabled for the cluster.'
this.code = code
this.type = type
}
}
export class NotFound extends Error {
description: string;
code: number;
type: string;
constructor ({ message, code, type }) {
super(message)
this.name = 'NotFound'
this.description = 'The request was sent to an endpoint that does not exist.'
this.code = code
this.type = type
}
}
export class ServerError extends Error {
description: string;
code: number;
type: string;
constructor ({ message, code, type }) {
super(message)
this.name = 'ServerError'
this.description = 'The Data API encountered an internal error and could not complete the request.'
this.code = code
this.type = type
}
} | 29.190476 | 155 | 0.595432 | 55 | 4 | 0 | 4 | 0 | 12 | 0 | 0 | 12 | 4 | 0 | 6.75 | 395 | 0.020253 | 0 | 0.03038 | 0.010127 | 0 | 0 | 0.6 | 0.232989 | export class BadRequest extends Error {
description;
code;
type;
constructor ({ message, code, type }) {
super(message)
this.name = 'BadRequest'
this.description = `
The request was invalid. This might mean:
- A request header is missing.
- The request body is malformed or improperly encoded.
- A field has a value with an invalid type.
- The specified data source is disabled or does not exist.
- The specified database or collection does not exist.
`
this.code = code
this.type = type
}
}
export class Unauthorized extends Error {
description;
code;
type;
constructor ({ message, code, type }) {
super(message)
this.name = 'Unauthorized'
this.description = 'The request did not include an authorized and enabled Data API Key. Ensure that your Data API Key is enabled for the cluster.'
this.code = code
this.type = type
}
}
export class NotFound extends Error {
description;
code;
type;
constructor ({ message, code, type }) {
super(message)
this.name = 'NotFound'
this.description = 'The request was sent to an endpoint that does not exist.'
this.code = code
this.type = type
}
}
export class ServerError extends Error {
description;
code;
type;
constructor ({ message, code, type }) {
super(message)
this.name = 'ServerError'
this.description = 'The Data API encountered an internal error and could not complete the request.'
this.code = code
this.type = type
}
} |