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
|
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
9d61e511e4e6b71cc44ce64314bcfd9a6a1e7e4a | 2,384 | ts | TypeScript | src/utils/parserSchema.ts | restuwahyu13/sijago | eba29e63ae4378fc885875edb8b02a71679287d5 | [
"MIT"
] | 7 | 2022-02-15T18:00:05.000Z | 2022-03-13T17:23:43.000Z | src/utils/parserSchema.ts | restuwahyu13/sijago | eba29e63ae4378fc885875edb8b02a71679287d5 | [
"MIT"
] | null | null | null | src/utils/parserSchema.ts | restuwahyu13/sijago | eba29e63ae4378fc885875edb8b02a71679287d5 | [
"MIT"
] | null | null | null | export const queryParserNotParams = (query: Record<string, any>): string => {
const graphqlSchema: string = JSON.stringify(query)
.replace(
/\.*(GraphqlString|GraphqlNumber|GraphqlFloat|GraphqlBoolean|GraphqlDate|GraphqlObject|GraphqlArray|GraphqlArrayObject|GraphqlBuffer)/gi,
''
)
.replace(/[:,]/g, ' ')
.replace(/[""]/g, '')
return graphqlSchema
}
export const queryParserWithParams = (options: Record<string, any>): string => {
const resolversName: string = `{${Object.keys(options.body)[0]} `
const bodySchema: string = JSON.stringify(Object.assign(options.body))
.replace(
/\.*(GraphqlString|GraphqlNumber|GraphqlFloat|GraphqlBoolean|GraphqlDate|GraphqlObject|GraphqlArray|GraphqlArrayObject|GraphqlBuffer)/gi,
''
)
.replace(/[""]/g, '')
.replace(/[:,]/g, ' ')
const inputSchema: string = JSON.stringify({ input: options.input })
.replace(
/\.*(GraphqlString|GraphqlNumber|GraphqlFloat|GraphqlBoolean|GraphqlDate|GraphqlObject|GraphqlArray|GraphqlArrayObject|GraphqlBuffer)/gi,
''
)
.replace(/[""]/g, '')
const validInputSchema: string = inputSchema.replace(/^[{]+(input:)/i, '').replace(/[}]$/, '')
const addGroupBracket: string = validInputSchema.replace(/^[{]/, '(').replace(/[}]$/, ')')
const mergeSchema: string =
resolversName + addGroupBracket + bodySchema.replace(/^[{]/, '').replace(resolversName.replace(/^[{]/, ''), '')
return mergeSchema
}
export const mutationParserWithParams = (options: Record<string, any>): string => {
const resolversName: string = `mutation{${Object.keys(options.body)[0]} `
const bodySchema: string = JSON.stringify(Object.assign(options.body))
.replace(
/\.*(GraphqlString|GraphqlNumber|GraphqlFloat|GraphqlBoolean|GraphqlDate|GraphqlObject|GraphqlArray|GraphqlArrayObject|GraphqlBuffer)/gi,
''
)
.replace(/[""]/g, '')
.replace(/[:,]/g, ' ')
const inputSchema: string = JSON.stringify({ input: options.input })
.replace(
/\.*(GraphqlString|GraphqlNumber|GraphqlFloat|GraphqlBoolean|GraphqlDate|GraphqlObject|GraphqlArray|GraphqlArrayObject|GraphqlBuffer)/gi,
''
)
.replace(/[""]/g, '')
const addGroupBracket: string = inputSchema.replace(/^[{]/, '(').replace(/[}]$/, ')')
const mergeSchema: string =
resolversName + addGroupBracket + bodySchema.replace(/^[{]/, '').replace(resolversName.replace(/^(mutation)+[{]/i, ''), '')
return mergeSchema
}
| 37.84127 | 140 | 0.695889 | 51 | 3 | 0 | 3 | 15 | 0 | 0 | 3 | 18 | 0 | 0 | 15 | 737 | 0.008141 | 0.020353 | 0 | 0 | 0 | 0.142857 | 0.857143 | 0.252243 | export const queryParserNotParams = (query) => {
const graphqlSchema = JSON.stringify(query)
.replace(
/\.*(GraphqlString|GraphqlNumber|GraphqlFloat|GraphqlBoolean|GraphqlDate|GraphqlObject|GraphqlArray|GraphqlArrayObject|GraphqlBuffer)/gi,
''
)
.replace(/[:,]/g, ' ')
.replace(/[""]/g, '')
return graphqlSchema
}
export const queryParserWithParams = (options) => {
const resolversName = `{${Object.keys(options.body)[0]} `
const bodySchema = JSON.stringify(Object.assign(options.body))
.replace(
/\.*(GraphqlString|GraphqlNumber|GraphqlFloat|GraphqlBoolean|GraphqlDate|GraphqlObject|GraphqlArray|GraphqlArrayObject|GraphqlBuffer)/gi,
''
)
.replace(/[""]/g, '')
.replace(/[:,]/g, ' ')
const inputSchema = JSON.stringify({ input: options.input })
.replace(
/\.*(GraphqlString|GraphqlNumber|GraphqlFloat|GraphqlBoolean|GraphqlDate|GraphqlObject|GraphqlArray|GraphqlArrayObject|GraphqlBuffer)/gi,
''
)
.replace(/[""]/g, '')
const validInputSchema = inputSchema.replace(/^[{]+(input:)/i, '').replace(/[}]$/, '')
const addGroupBracket = validInputSchema.replace(/^[{]/, '(').replace(/[}]$/, ')')
const mergeSchema =
resolversName + addGroupBracket + bodySchema.replace(/^[{]/, '').replace(resolversName.replace(/^[{]/, ''), '')
return mergeSchema
}
export const mutationParserWithParams = (options) => {
const resolversName = `mutation{${Object.keys(options.body)[0]} `
const bodySchema = JSON.stringify(Object.assign(options.body))
.replace(
/\.*(GraphqlString|GraphqlNumber|GraphqlFloat|GraphqlBoolean|GraphqlDate|GraphqlObject|GraphqlArray|GraphqlArrayObject|GraphqlBuffer)/gi,
''
)
.replace(/[""]/g, '')
.replace(/[:,]/g, ' ')
const inputSchema = JSON.stringify({ input: options.input })
.replace(
/\.*(GraphqlString|GraphqlNumber|GraphqlFloat|GraphqlBoolean|GraphqlDate|GraphqlObject|GraphqlArray|GraphqlArrayObject|GraphqlBuffer)/gi,
''
)
.replace(/[""]/g, '')
const addGroupBracket = inputSchema.replace(/^[{]/, '(').replace(/[}]$/, ')')
const mergeSchema =
resolversName + addGroupBracket + bodySchema.replace(/^[{]/, '').replace(resolversName.replace(/^(mutation)+[{]/i, ''), '')
return mergeSchema
}
|
9d6a4bab4b261420f785509714bb281302dd5bb8 | 4,952 | ts | TypeScript | src/parse.ts | kevin940726/role-selector | d2bd422fce5e9d1f25000fbb516b30489f35bbfd | [
"MIT"
] | 2 | 2022-02-23T10:49:38.000Z | 2022-02-28T07:52:06.000Z | src/parse.ts | kevin940726/role-selector | d2bd422fce5e9d1f25000fbb516b30489f35bbfd | [
"MIT"
] | null | null | null | src/parse.ts | kevin940726/role-selector | d2bd422fce5e9d1f25000fbb516b30489f35bbfd | [
"MIT"
] | 2 | 2022-02-21T02:53:46.000Z | 2022-03-28T17:24:51.000Z | /**
* This file is heavily based on Playwright's `parseComponentSelector`, altered for this library's usage.
* @see https://github.com/microsoft/playwright/blob/585807b3bea6a998019200c16b06683115011d87/src/server/common/componentUtils.ts
*
* Copyright (c) Microsoft Corporation.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
interface ParsedAttribute {
name: string;
value: string | number | boolean | RegExp;
caseSensitive: boolean;
}
interface ParsedSelector {
role: string;
attributes: ParsedAttribute[];
}
function parseSelector(selector: string): ParsedSelector {
let wp = 0;
let EOL = selector.length === 0;
const next = () => selector[wp] || '';
const eat1 = () => {
const result = next();
++wp;
EOL = wp >= selector.length;
return result;
};
const syntaxError = (stage: string | undefined) => {
if (EOL)
throw new Error(
`Unexpected end of selector while parsing selector \`${selector}\``
);
throw new Error(
`Error while parsing selector \`${selector}\` - unexpected symbol "${next()}" at position ${wp}` +
(stage ? ' during ' + stage : '')
);
};
function skipSpaces() {
while (!EOL && /\s/.test(next())) eat1();
}
function readIdentifier() {
let result = '';
skipSpaces();
while (!EOL && /[-$0-9A-Z_\*]/i.test(next())) result += eat1();
return result;
}
function readQuotedString(quote: string) {
let result = eat1();
if (result !== quote) syntaxError('parsing quoted string');
while (!EOL && next() !== quote) {
if (next() === '\\') eat1();
result += eat1();
}
if (next() !== quote) syntaxError('parsing quoted string');
result += eat1();
return result;
}
function readRegexString() {
if (eat1() !== '/') syntaxError('parsing regex string');
let pattern = '';
let flags = '';
while (!EOL && next() !== '/') {
if (next() === '\\') eat1();
pattern += eat1();
}
if (next() !== '/') syntaxError('parsing regex string');
eat1();
while (!EOL && /[dgimsuy]/.test(next())) {
flags += eat1();
}
return [pattern, flags];
}
function readOperator() {
skipSpaces();
let op;
if (!EOL) op = eat1();
if (op !== '=') {
syntaxError('parsing operator');
}
return op;
}
function readAttribute(): ParsedAttribute {
// skip leading [
eat1();
// read attribute name:
const name = readIdentifier();
skipSpaces();
// check property is true: [focused]
if (next() === ']') {
eat1();
return { name, value: true, caseSensitive: false };
}
readOperator();
let value = undefined;
let caseSensitive = true;
skipSpaces();
if (next() === `'` || next() === `"`) {
value = readQuotedString(next()).slice(1, -1);
skipSpaces();
if (next() === 'i' || next() === 'I') {
caseSensitive = false;
eat1();
} else if (next() === 's' || next() === 'S') {
caseSensitive = true;
eat1();
}
} else if (next() === '/') {
const [pattern, flags] = readRegexString();
value = new RegExp(pattern, flags);
} else {
value = '';
while (!EOL && !/\s/.test(next()) && next() !== ']') value += eat1();
if (value === 'true') {
value = true;
} else if (value === 'false') {
value = false;
} else {
value = +value;
if (isNaN(value)) syntaxError('parsing attribute value');
}
}
skipSpaces();
if (next() !== ']') syntaxError('parsing attribute value');
eat1();
if (
typeof value !== 'string' &&
typeof value !== 'number' &&
typeof value !== 'boolean' &&
!(value instanceof RegExp)
)
throw new Error(
`Error while parsing selector \`${selector}\` - cannot use attribute ${name} with unsupported type ${typeof value} - ${value}`
);
return { name, value, caseSensitive };
}
const result: ParsedSelector = {
role: '',
attributes: [],
};
result.role = readIdentifier();
skipSpaces();
while (next() === '[') {
result.attributes.push(readAttribute());
skipSpaces();
}
if (!EOL) syntaxError(undefined);
if (!result.role && !result.attributes.length)
throw new Error(
`Error while parsing selector \`${selector}\` - selector cannot be empty`
);
return result;
}
export default parseSelector;
| 27.359116 | 134 | 0.574515 | 142 | 10 | 0 | 3 | 16 | 5 | 9 | 0 | 9 | 2 | 5 | 22.6 | 1,299 | 0.010008 | 0.012317 | 0.003849 | 0.00154 | 0.003849 | 0 | 0.264706 | 0.237626 | /**
* This file is heavily based on Playwright's `parseComponentSelector`, altered for this library's usage.
* @see https://github.com/microsoft/playwright/blob/585807b3bea6a998019200c16b06683115011d87/src/server/common/componentUtils.ts
*
* Copyright (c) Microsoft Corporation.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
interface ParsedAttribute {
name;
value;
caseSensitive;
}
interface ParsedSelector {
role;
attributes;
}
/* Example usages of 'parseSelector' are shown below:
;
*/
function parseSelector(selector) {
let wp = 0;
let EOL = selector.length === 0;
/* Example usages of 'next' are shown below:
next();
!EOL && /\s/.test(next());
!EOL && /[-$0-9A-Z_\*]/i.test(next());
!EOL && next() !== quote;
next() === '\\';
next() !== quote;
!EOL && next() !== '/';
next() !== '/';
!EOL && /[dgimsuy]/.test(next());
next() === ']';
next() === `'` || next() === `"`;
value = readQuotedString(next()).slice(1, -1);
next() === 'i' || next() === 'I';
next() === 's' || next() === 'S';
next() === '/';
!EOL && !/\s/.test(next()) && next() !== ']';
next() !== ']';
next() === '[';
*/
const next = () => selector[wp] || '';
/* Example usages of 'eat1' are shown below:
eat1();
result += eat1();
eat1() !== '/';
pattern += eat1();
flags += eat1();
op = eat1();
// skip leading [
eat1();
value += eat1();
*/
const eat1 = () => {
const result = next();
++wp;
EOL = wp >= selector.length;
return result;
};
/* Example usages of 'syntaxError' are shown below:
syntaxError('parsing quoted string');
syntaxError('parsing regex string');
syntaxError('parsing operator');
syntaxError('parsing attribute value');
syntaxError(undefined);
*/
const syntaxError = (stage) => {
if (EOL)
throw new Error(
`Unexpected end of selector while parsing selector \`${selector}\``
);
throw new Error(
`Error while parsing selector \`${selector}\` - unexpected symbol "${next()}" at position ${wp}` +
(stage ? ' during ' + stage : '')
);
};
/* Example usages of 'skipSpaces' are shown below:
skipSpaces();
*/
function skipSpaces() {
while (!EOL && /\s/.test(next())) eat1();
}
/* Example usages of 'readIdentifier' are shown below:
readIdentifier();
result.role = readIdentifier();
*/
function readIdentifier() {
let result = '';
skipSpaces();
while (!EOL && /[-$0-9A-Z_\*]/i.test(next())) result += eat1();
return result;
}
/* Example usages of 'readQuotedString' are shown below:
value = readQuotedString(next()).slice(1, -1);
*/
function readQuotedString(quote) {
let result = eat1();
if (result !== quote) syntaxError('parsing quoted string');
while (!EOL && next() !== quote) {
if (next() === '\\') eat1();
result += eat1();
}
if (next() !== quote) syntaxError('parsing quoted string');
result += eat1();
return result;
}
/* Example usages of 'readRegexString' are shown below:
readRegexString();
*/
function readRegexString() {
if (eat1() !== '/') syntaxError('parsing regex string');
let pattern = '';
let flags = '';
while (!EOL && next() !== '/') {
if (next() === '\\') eat1();
pattern += eat1();
}
if (next() !== '/') syntaxError('parsing regex string');
eat1();
while (!EOL && /[dgimsuy]/.test(next())) {
flags += eat1();
}
return [pattern, flags];
}
/* Example usages of 'readOperator' are shown below:
readOperator();
*/
function readOperator() {
skipSpaces();
let op;
if (!EOL) op = eat1();
if (op !== '=') {
syntaxError('parsing operator');
}
return op;
}
/* Example usages of 'readAttribute' are shown below:
result.attributes.push(readAttribute());
*/
function readAttribute() {
// skip leading [
eat1();
// read attribute name:
const name = readIdentifier();
skipSpaces();
// check property is true: [focused]
if (next() === ']') {
eat1();
return { name, value: true, caseSensitive: false };
}
readOperator();
let value = undefined;
let caseSensitive = true;
skipSpaces();
if (next() === `'` || next() === `"`) {
value = readQuotedString(next()).slice(1, -1);
skipSpaces();
if (next() === 'i' || next() === 'I') {
caseSensitive = false;
eat1();
} else if (next() === 's' || next() === 'S') {
caseSensitive = true;
eat1();
}
} else if (next() === '/') {
const [pattern, flags] = readRegexString();
value = new RegExp(pattern, flags);
} else {
value = '';
while (!EOL && !/\s/.test(next()) && next() !== ']') value += eat1();
if (value === 'true') {
value = true;
} else if (value === 'false') {
value = false;
} else {
value = +value;
if (isNaN(value)) syntaxError('parsing attribute value');
}
}
skipSpaces();
if (next() !== ']') syntaxError('parsing attribute value');
eat1();
if (
typeof value !== 'string' &&
typeof value !== 'number' &&
typeof value !== 'boolean' &&
!(value instanceof RegExp)
)
throw new Error(
`Error while parsing selector \`${selector}\` - cannot use attribute ${name} with unsupported type ${typeof value} - ${value}`
);
return { name, value, caseSensitive };
}
const result = {
role: '',
attributes: [],
};
result.role = readIdentifier();
skipSpaces();
while (next() === '[') {
result.attributes.push(readAttribute());
skipSpaces();
}
if (!EOL) syntaxError(undefined);
if (!result.role && !result.attributes.length)
throw new Error(
`Error while parsing selector \`${selector}\` - selector cannot be empty`
);
return result;
}
export default parseSelector;
|
9d73cd93cf6320bd4e2ebc05e06c880615bdddca | 1,716 | ts | TypeScript | cv.ts | script-development/rtcv_scraper_client | 483c04387b2b64ed5cd1cde1ee93db022633d4b7 | [
"MIT"
] | null | null | null | cv.ts | script-development/rtcv_scraper_client | 483c04387b2b64ed5cd1cde1ee93db022633d4b7 | [
"MIT"
] | null | null | null | cv.ts | script-development/rtcv_scraper_client | 483c04387b2b64ed5cd1cde1ee93db022633d4b7 | [
"MIT"
] | 1 | 2022-01-14T13:50:02.000Z | 2022-01-14T13:50:02.000Z | export interface CVToScan {
referenceNumber: string
link?: string,
presentation?: string
personalDetails: CVToScanPersonalDetails
preferredJobs: Array<string>
workExperiences: Array<CVToScanWorkExperience>
educations: Array<CVToScanEducation>
languages: Array<CVToScanLanguage>
driversLicenses: Array<string>
}
export function newCvToScan(referenceNumber: string): CVToScan {
return {
referenceNumber,
personalDetails: {},
preferredJobs: [],
workExperiences: [],
educations: [],
languages: [],
driversLicenses: [],
}
}
export interface CVToScanEducation {
is: 0 | 1 | 2
name: string
description: string
institute: string
isCompleted?: boolean
hasDiploma?: boolean
startDate: string | null // RFC3339
endDate: string | null // RFC3339
}
export interface CVToScanWorkExperience {
profession: string
description: string
employer: string
stillEmployed?: boolean
weeklyHoursWorked?: number
startDate: string | null // RFC3339
endDate: string | null // RFC3339
}
export interface CVToScanPersonalDetails {
city?: string
country?: string
dob?: string | null // RFC3339
email?: string
firstName?: string
gender?: string
houseNumber?: string
houseNumberSuffix?: string
initials?: string
phoneNumber?: string
streetName?: string
surName?: string
surNamePrefix?: string
zip?: string
}
export interface CVToScanLanguage {
levelSpoken: LangLevel | null
levelWritten: LangLevel | null
name: string
}
export enum LangLevel {
Unknown = 0,
Reasonable = 1,
Good = 2,
Excellent = 3,
}
| 22.88 | 64 | 0.668415 | 68 | 1 | 0 | 1 | 0 | 41 | 0 | 0 | 35 | 5 | 0 | 9 | 430 | 0.004651 | 0 | 0.095349 | 0.011628 | 0 | 0 | 0.813953 | 0.198625 | export interface CVToScan {
referenceNumber
link?,
presentation?
personalDetails
preferredJobs
workExperiences
educations
languages
driversLicenses
}
export function newCvToScan(referenceNumber) {
return {
referenceNumber,
personalDetails: {},
preferredJobs: [],
workExperiences: [],
educations: [],
languages: [],
driversLicenses: [],
}
}
export interface CVToScanEducation {
is
name
description
institute
isCompleted?
hasDiploma?
startDate // RFC3339
endDate // RFC3339
}
export interface CVToScanWorkExperience {
profession
description
employer
stillEmployed?
weeklyHoursWorked?
startDate // RFC3339
endDate // RFC3339
}
export interface CVToScanPersonalDetails {
city?
country?
dob? // RFC3339
email?
firstName?
gender?
houseNumber?
houseNumberSuffix?
initials?
phoneNumber?
streetName?
surName?
surNamePrefix?
zip?
}
export interface CVToScanLanguage {
levelSpoken
levelWritten
name
}
export enum LangLevel {
Unknown = 0,
Reasonable = 1,
Good = 2,
Excellent = 3,
}
|
9dc8b7d379a90c17e374d31bc1984737a7d6822d | 2,994 | ts | TypeScript | src/common/priority-action-queue/Heap.ts | rilldata/rill-developer | fafdf808a75c1ca85f442f4dce3414eae1912115 | [
"Apache-2.0"
] | 9 | 2022-03-29T18:58:01.000Z | 2022-03-31T18:34:02.000Z | src/common/priority-action-queue/Heap.ts | rilldata/rill-developer | fafdf808a75c1ca85f442f4dce3414eae1912115 | [
"Apache-2.0"
] | 5 | 2022-03-28T22:05:59.000Z | 2022-03-31T14:42:42.000Z | src/common/priority-action-queue/Heap.ts | rilldata/data-modeler-prototype | ab75032ee72985ca0e619c281d731ae138813faa | [
"Apache-2.0"
] | 1 | 2022-03-30T16:55:03.000Z | 2022-03-30T16:55:03.000Z | export class Heap<Item = any> {
private readonly array: Array<Item>;
private valueToIdxMap: Map<Item, number> = new Map();
private readonly compareFunction: (a: Item, b: Item) => number;
/**
* @constructor
* @param {Array} initArray
* @param {Function} compareFunction Return value > 0 to have a above b in the heap.
*/
constructor(
initArray = [],
compareFunction = function (a, b) {
return a - b;
}
) {
this.array = initArray;
this.compareFunction = compareFunction;
this.array.forEach((e, i) => {
this.valueToIdxMap.set(e, i);
});
}
public empty() {
return this.array.length === 0;
}
public peek(): Item {
return this.array[0];
}
public push(value: Item) {
this.valueToIdxMap.set(value, this.array.length);
this.array.push(value);
this.moveUp(this.array.length - 1);
}
public pop() {
if (this.array.length > 0) {
const value = this.array[0];
this.valueToIdxMap.delete(value);
if (this.array.length > 1) {
this.array[0] = this.array.pop();
this.valueToIdxMap.set(this.array[0], 0);
this.moveDown(0);
} else {
this.array.pop();
}
return value;
}
}
public delete(value: Item) {
const idx = this.valueToIdxMap.get(value);
if (idx >= 0) {
this.valueToIdxMap.delete(value);
if (idx < this.array.length - 1) {
this.array[idx] = this.array.pop();
this.valueToIdxMap.set(this.array[idx], idx);
this.moveDown(idx);
} else {
this.array.pop();
}
}
}
// doesnt work on literals
public updateItem(value: Item) {
const idx = this.valueToIdxMap.get(value);
if (!this.moveUp(idx)) {
this.moveDown(idx);
}
}
private moveUp(idx: number) {
let movedUp = false;
while (idx > 0) {
const parentIdx = (idx - 1) >> 1;
if (this.compareFunction(this.array[idx], this.array[parentIdx]) > 0) {
this.swap(idx, parentIdx);
idx = parentIdx;
movedUp = true;
} else {
break;
}
}
return movedUp;
}
private moveDown(idx: number) {
let movedDown = false;
while (idx < this.array.length) {
let childIdx = 2 * idx + 1;
if (childIdx >= this.array.length) {
break;
}
if (
childIdx + 1 < this.array.length &&
this.compareFunction(this.array[childIdx + 1], this.array[childIdx]) > 0
) {
childIdx++;
}
if (this.compareFunction(this.array[childIdx], this.array[idx]) > 0) {
this.swap(idx, childIdx);
idx = childIdx;
movedDown = true;
} else {
break;
}
}
return movedDown;
}
private swap(idx0: number, idx1: number) {
const val0 = this.array[idx0];
this.array[idx0] = this.array[idx1];
this.array[idx1] = val0;
this.valueToIdxMap.set(this.array[idx0], idx0);
this.valueToIdxMap.set(this.array[idx1], idx1);
}
}
| 23.761905 | 86 | 0.568136 | 105 | 12 | 0 | 13 | 8 | 3 | 6 | 1 | 6 | 1 | 0 | 6.416667 | 918 | 0.027233 | 0.008715 | 0.003268 | 0.001089 | 0 | 0.027778 | 0.166667 | 0.26487 | export class Heap<Item = any> {
private readonly array;
private valueToIdxMap = new Map();
private readonly compareFunction;
/**
* @constructor
* @param {Array} initArray
* @param {Function} compareFunction Return value > 0 to have a above b in the heap.
*/
constructor(
initArray = [],
compareFunction = function (a, b) {
return a - b;
}
) {
this.array = initArray;
this.compareFunction = compareFunction;
this.array.forEach((e, i) => {
this.valueToIdxMap.set(e, i);
});
}
public empty() {
return this.array.length === 0;
}
public peek() {
return this.array[0];
}
public push(value) {
this.valueToIdxMap.set(value, this.array.length);
this.array.push(value);
this.moveUp(this.array.length - 1);
}
public pop() {
if (this.array.length > 0) {
const value = this.array[0];
this.valueToIdxMap.delete(value);
if (this.array.length > 1) {
this.array[0] = this.array.pop();
this.valueToIdxMap.set(this.array[0], 0);
this.moveDown(0);
} else {
this.array.pop();
}
return value;
}
}
public delete(value) {
const idx = this.valueToIdxMap.get(value);
if (idx >= 0) {
this.valueToIdxMap.delete(value);
if (idx < this.array.length - 1) {
this.array[idx] = this.array.pop();
this.valueToIdxMap.set(this.array[idx], idx);
this.moveDown(idx);
} else {
this.array.pop();
}
}
}
// doesnt work on literals
public updateItem(value) {
const idx = this.valueToIdxMap.get(value);
if (!this.moveUp(idx)) {
this.moveDown(idx);
}
}
private moveUp(idx) {
let movedUp = false;
while (idx > 0) {
const parentIdx = (idx - 1) >> 1;
if (this.compareFunction(this.array[idx], this.array[parentIdx]) > 0) {
this.swap(idx, parentIdx);
idx = parentIdx;
movedUp = true;
} else {
break;
}
}
return movedUp;
}
private moveDown(idx) {
let movedDown = false;
while (idx < this.array.length) {
let childIdx = 2 * idx + 1;
if (childIdx >= this.array.length) {
break;
}
if (
childIdx + 1 < this.array.length &&
this.compareFunction(this.array[childIdx + 1], this.array[childIdx]) > 0
) {
childIdx++;
}
if (this.compareFunction(this.array[childIdx], this.array[idx]) > 0) {
this.swap(idx, childIdx);
idx = childIdx;
movedDown = true;
} else {
break;
}
}
return movedDown;
}
private swap(idx0, idx1) {
const val0 = this.array[idx0];
this.array[idx0] = this.array[idx1];
this.array[idx1] = val0;
this.valueToIdxMap.set(this.array[idx0], idx0);
this.valueToIdxMap.set(this.array[idx1], idx1);
}
}
|
9df566c660a96ca1ea9c774ead4166eff4ea2801 | 1,718 | ts | TypeScript | packages/js/src/utils/create-async-iterable/create-async-iteratable.ts | jonhamm/nx | 876d4d8a0e98fa9de7d0ff2dbc7ad7cf896d9b3d | [
"MIT"
] | 1 | 2022-03-10T09:51:39.000Z | 2022-03-10T09:51:39.000Z | packages/js/src/utils/create-async-iterable/create-async-iteratable.ts | jonhamm/nx | 876d4d8a0e98fa9de7d0ff2dbc7ad7cf896d9b3d | [
"MIT"
] | null | null | null | packages/js/src/utils/create-async-iterable/create-async-iteratable.ts | jonhamm/nx | 876d4d8a0e98fa9de7d0ff2dbc7ad7cf896d9b3d | [
"MIT"
] | 1 | 2022-03-10T09:34:36.000Z | 2022-03-10T09:34:36.000Z | 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>;
}
| 25.641791 | 70 | 0.445867 | 62 | 7 | 0 | 5 | 4 | 3 | 0 | 0 | 12 | 1 | 1 | 18.571429 | 440 | 0.027273 | 0.009091 | 0.006818 | 0.002273 | 0.002273 | 0 | 0.631579 | 0.266128 | 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>;
}
|
2bc224c64620085c5e7aa93f08e143f4e3b40903 | 2,805 | ts | TypeScript | ui/packages/app/src/components/utils/helpers.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/helpers.ts | aribornstein/gradio | 08ef8b0ed5c748250bfe8b6ffec1c63c5b6e81cd | [
"Apache-2.0"
] | null | null | null | ui/packages/app/src/components/utils/helpers.ts | aribornstein/gradio | 08ef8b0ed5c748250bfe8b6ffec1c63c5b6e81cd | [
"Apache-2.0"
] | null | null | null | // import mime from "mime-types";
export const playable = (filename: string): boolean => {
// let video_element = document.createElement("video");
// let mime_type = mime.lookup(filename);
// return video_element.canPlayType(mime_type) != "";
return true; // FIX BEFORE COMMIT - mime import causing issues
};
export const deepCopy = <T>(obj: T): T => {
return JSON.parse(JSON.stringify(obj));
};
export function randInt(min: number, max: number): number {
return Math.floor(Math.random() * (max - min) + min);
}
export const getNextColor = (index: number, alpha: number = 1): string => {
let default_colors = [
[255, 99, 132],
[54, 162, 235],
[240, 176, 26],
[153, 102, 255],
[75, 192, 192],
[255, 159, 64],
[194, 88, 74],
[44, 102, 219],
[44, 163, 23],
[191, 46, 217],
[160, 162, 162],
[163, 151, 27]
];
if (index < default_colors.length) {
var color_set = default_colors[index];
} else {
var color_set = [randInt(64, 196), randInt(64, 196), randInt(64, 196)];
}
return (
"rgba(" +
color_set[0] +
", " +
color_set[1] +
", " +
color_set[2] +
", " +
alpha +
")"
);
};
export const prettyBytes = (bytes: number): string => {
let units = ["B", "KB", "MB", "GB", "PB"];
let i = 0;
while (bytes > 1024) {
bytes /= 1024;
i++;
}
let unit = units[i];
return bytes.toFixed(1) + " " + unit;
};
export const getSaliencyColor = (value: number): string => {
var color: [number, number, number] | null = null;
if (value < 0) {
color = [52, 152, 219];
} else {
color = [231, 76, 60];
}
return colorToString(interpolate(Math.abs(value), [255, 255, 255], color));
};
const interpolate = (
val: number,
rgb1: [number, number, number],
rgb2: [number, number, number]
): [number, number, number] => {
if (val > 1) {
val = 1;
}
val = Math.sqrt(val);
var rgb: [number, number, number] = [0, 0, 0];
var i;
for (i = 0; i < 3; i++) {
rgb[i] = Math.round(rgb1[i] * (1.0 - val) + rgb2[i] * val);
}
return rgb;
};
const colorToString = (rgb: [number, number, number]): string => {
return "rgb(" + rgb[0] + ", " + rgb[1] + ", " + rgb[2] + ")";
};
export const getObjectFitSize = (
contains: boolean /* true = contain, false = cover */,
containerWidth: number,
containerHeight: number,
width: number,
height: number
) => {
var doRatio = width / height;
var cRatio = containerWidth / containerHeight;
var targetWidth = 0;
var targetHeight = 0;
var test = contains ? doRatio > cRatio : doRatio < cRatio;
if (test) {
targetWidth = containerWidth;
targetHeight = targetWidth / doRatio;
} else {
targetHeight = containerHeight;
targetWidth = targetHeight * doRatio;
}
return {
width: targetWidth,
height: targetHeight,
x: (containerWidth - targetWidth) / 2,
y: (containerHeight - targetHeight) / 2
};
};
| 23.181818 | 76 | 0.606417 | 105 | 9 | 0 | 17 | 22 | 0 | 3 | 0 | 37 | 0 | 0 | 8.555556 | 1,173 | 0.022165 | 0.018755 | 0 | 0 | 0 | 0 | 0.770833 | 0.282972 | // import mime from "mime-types";
export const playable = (filename) => {
// let video_element = document.createElement("video");
// let mime_type = mime.lookup(filename);
// return video_element.canPlayType(mime_type) != "";
return true; // FIX BEFORE COMMIT - mime import causing issues
};
export const deepCopy = <T>(obj) => {
return JSON.parse(JSON.stringify(obj));
};
export /* Example usages of 'randInt' are shown below:
randInt(64, 196);
*/
function randInt(min, max) {
return Math.floor(Math.random() * (max - min) + min);
}
export const getNextColor = (index, alpha = 1) => {
let default_colors = [
[255, 99, 132],
[54, 162, 235],
[240, 176, 26],
[153, 102, 255],
[75, 192, 192],
[255, 159, 64],
[194, 88, 74],
[44, 102, 219],
[44, 163, 23],
[191, 46, 217],
[160, 162, 162],
[163, 151, 27]
];
if (index < default_colors.length) {
var color_set = default_colors[index];
} else {
var color_set = [randInt(64, 196), randInt(64, 196), randInt(64, 196)];
}
return (
"rgba(" +
color_set[0] +
", " +
color_set[1] +
", " +
color_set[2] +
", " +
alpha +
")"
);
};
export const prettyBytes = (bytes) => {
let units = ["B", "KB", "MB", "GB", "PB"];
let i = 0;
while (bytes > 1024) {
bytes /= 1024;
i++;
}
let unit = units[i];
return bytes.toFixed(1) + " " + unit;
};
export const getSaliencyColor = (value) => {
var color = null;
if (value < 0) {
color = [52, 152, 219];
} else {
color = [231, 76, 60];
}
return colorToString(interpolate(Math.abs(value), [255, 255, 255], color));
};
/* Example usages of 'interpolate' are shown below:
colorToString(interpolate(Math.abs(value), [255, 255, 255], color));
*/
const interpolate = (
val,
rgb1,
rgb2
) => {
if (val > 1) {
val = 1;
}
val = Math.sqrt(val);
var rgb = [0, 0, 0];
var i;
for (i = 0; i < 3; i++) {
rgb[i] = Math.round(rgb1[i] * (1.0 - val) + rgb2[i] * val);
}
return rgb;
};
/* Example usages of 'colorToString' are shown below:
colorToString(interpolate(Math.abs(value), [255, 255, 255], color));
*/
const colorToString = (rgb) => {
return "rgb(" + rgb[0] + ", " + rgb[1] + ", " + rgb[2] + ")";
};
export const getObjectFitSize = (
contains /* true = contain, false = cover */,
containerWidth,
containerHeight,
width,
height
) => {
var doRatio = width / height;
var cRatio = containerWidth / containerHeight;
var targetWidth = 0;
var targetHeight = 0;
var test = contains ? doRatio > cRatio : doRatio < cRatio;
if (test) {
targetWidth = containerWidth;
targetHeight = targetWidth / doRatio;
} else {
targetHeight = containerHeight;
targetWidth = targetHeight * doRatio;
}
return {
width: targetWidth,
height: targetHeight,
x: (containerWidth - targetWidth) / 2,
y: (containerHeight - targetHeight) / 2
};
};
|
9fc94cc878ab26c5eed76d6845a7080110869aa3 | 5,318 | ts | TypeScript | src/config.ts | nodece/casbin.js | b2369ef7d3c79e972c61a208730ab6d8b1262210 | [
"Apache-2.0"
] | null | null | null | src/config.ts | nodece/casbin.js | b2369ef7d3c79e972c61a208730ab6d8b1262210 | [
"Apache-2.0"
] | 2 | 2022-03-25T09:43:50.000Z | 2022-03-25T09:44:15.000Z | src/config.ts | nodece/casbin.js | b2369ef7d3c79e972c61a208730ab6d8b1262210 | [
"Apache-2.0"
] | null | null | null | // Copyright 2018 The Casbin Authors. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// ConfigInterface defines the behavior of a Config implementation
export interface ConfigInterface {
getString(key: string): string;
getStrings(key: string): string[];
getBool(key: string): boolean;
getInt(key: string): number;
getFloat(key: string): number;
set(key: string, value: string): void;
}
export class Config implements ConfigInterface {
private static DEFAULT_SECTION = 'default';
private static DEFAULT_COMMENT = '#';
private static DEFAULT_COMMENT_SEM = ';';
private static DEFAULT_MULTI_LINE_SEPARATOR = '\\';
private data: Map<string, Map<string, string>>;
private constructor() {
this.data = new Map<string, Map<string, string>>();
}
/**
* newConfig create an empty configuration representation from file.
*
* @param text the content of the model file.
* @return the constructor of Config.
*/
public static newConfig(text: string): Config {
const config = new Config();
config.parseText(text);
return config;
}
/**
* newConfigFromText create an empty configuration representation from text.
*
* @param text the model text.
* @return the constructor of Config.
*/
public static newConfigFromText(text: string): Config {
const config = new Config();
config.parseText(text);
return config;
}
/**
* addConfig adds a new section->key:value to the configuration.
*/
private addConfig(section: string, option: string, value: string): boolean {
if (section === '') {
section = Config.DEFAULT_SECTION;
}
const hasKey = this.data.has(section);
if (!hasKey) {
this.data.set(section, new Map<string, string>());
}
const item = this.data.get(section);
if (item) {
item.set(option, value);
return item.has(option);
} else {
return false;
}
}
private parseText(text: string): void {
const lines = text.split('\n').filter((v) => v);
const linesCount = lines.length;
let section = '';
let currentLine = '';
lines.forEach((n, index) => {
let commentPos = n.indexOf(Config.DEFAULT_COMMENT);
if (commentPos > -1) {
n = n.slice(0, commentPos);
}
commentPos = n.indexOf(Config.DEFAULT_COMMENT_SEM);
if (commentPos > -1) {
n = n.slice(0, commentPos);
}
const line = n.trim();
if (!line) {
return;
}
const lineNumber = index + 1;
if (line.startsWith('[') && line.endsWith(']')) {
if (currentLine.length !== 0) {
this.write(section, lineNumber - 1, currentLine);
currentLine = '';
}
section = line.substring(1, line.length - 1);
} else {
let shouldWrite = false;
if (line.includes(Config.DEFAULT_MULTI_LINE_SEPARATOR)) {
currentLine += line.substring(0, line.length - 1).trim();
} else {
currentLine += line;
shouldWrite = true;
}
if (shouldWrite || lineNumber === linesCount) {
this.write(section, lineNumber, currentLine);
currentLine = '';
}
}
});
}
private write(section: string, lineNum: number, line: string): void {
const equalIndex = line.indexOf('=');
if (equalIndex === -1) {
throw new Error(`parse the content error : line ${lineNum}`);
}
const key = line.substring(0, equalIndex);
const value = line.substring(equalIndex + 1);
this.addConfig(section, key.trim(), value.trim());
}
public getBool(key: string): boolean {
return !!this.get(key);
}
public getInt(key: string): number {
return Number.parseInt(this.get(key), 10);
}
public getFloat(key: string): number {
return Number.parseFloat(this.get(key));
}
public getString(key: string): string {
return this.get(key);
}
public getStrings(key: string): string[] {
const v = this.get(key);
return v.split(',');
}
public set(key: string, value: string): void {
if (!key) {
throw new Error('key is empty');
}
let section = '';
let option;
const keys = key.toLowerCase().split('::');
if (keys.length >= 2) {
section = keys[0];
option = keys[1];
} else {
option = keys[0];
}
this.addConfig(section, option, value);
}
public get(key: string): string {
let section;
let option;
const keys = key.toLowerCase().split('::');
if (keys.length >= 2) {
section = keys[0];
option = keys[1];
} else {
section = Config.DEFAULT_SECTION;
option = keys[0];
}
const item = this.data.get(section);
const itemChild = item && item.get(option);
return itemChild ? itemChild : '';
}
}
| 26.457711 | 78 | 0.616961 | 139 | 15 | 6 | 27 | 24 | 5 | 5 | 0 | 48 | 2 | 0 | 8.733333 | 1,386 | 0.030303 | 0.017316 | 0.003608 | 0.001443 | 0 | 0 | 0.623377 | 0.300349 | // Copyright 2018 The Casbin Authors. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// ConfigInterface defines the behavior of a Config implementation
export interface ConfigInterface {
getString(key);
getStrings(key);
getBool(key);
getInt(key);
getFloat(key);
set(key, value);
}
export class Config implements ConfigInterface {
private static DEFAULT_SECTION = 'default';
private static DEFAULT_COMMENT = '#';
private static DEFAULT_COMMENT_SEM = ';';
private static DEFAULT_MULTI_LINE_SEPARATOR = '\\';
private data;
private constructor() {
this.data = new Map<string, Map<string, string>>();
}
/**
* newConfig create an empty configuration representation from file.
*
* @param text the content of the model file.
* @return the constructor of Config.
*/
public static newConfig(text) {
const config = new Config();
config.parseText(text);
return config;
}
/**
* newConfigFromText create an empty configuration representation from text.
*
* @param text the model text.
* @return the constructor of Config.
*/
public static newConfigFromText(text) {
const config = new Config();
config.parseText(text);
return config;
}
/**
* addConfig adds a new section->key:value to the configuration.
*/
private addConfig(section, option, value) {
if (section === '') {
section = Config.DEFAULT_SECTION;
}
const hasKey = this.data.has(section);
if (!hasKey) {
this.data.set(section, new Map<string, string>());
}
const item = this.data.get(section);
if (item) {
item.set(option, value);
return item.has(option);
} else {
return false;
}
}
private parseText(text) {
const lines = text.split('\n').filter((v) => v);
const linesCount = lines.length;
let section = '';
let currentLine = '';
lines.forEach((n, index) => {
let commentPos = n.indexOf(Config.DEFAULT_COMMENT);
if (commentPos > -1) {
n = n.slice(0, commentPos);
}
commentPos = n.indexOf(Config.DEFAULT_COMMENT_SEM);
if (commentPos > -1) {
n = n.slice(0, commentPos);
}
const line = n.trim();
if (!line) {
return;
}
const lineNumber = index + 1;
if (line.startsWith('[') && line.endsWith(']')) {
if (currentLine.length !== 0) {
this.write(section, lineNumber - 1, currentLine);
currentLine = '';
}
section = line.substring(1, line.length - 1);
} else {
let shouldWrite = false;
if (line.includes(Config.DEFAULT_MULTI_LINE_SEPARATOR)) {
currentLine += line.substring(0, line.length - 1).trim();
} else {
currentLine += line;
shouldWrite = true;
}
if (shouldWrite || lineNumber === linesCount) {
this.write(section, lineNumber, currentLine);
currentLine = '';
}
}
});
}
private write(section, lineNum, line) {
const equalIndex = line.indexOf('=');
if (equalIndex === -1) {
throw new Error(`parse the content error : line ${lineNum}`);
}
const key = line.substring(0, equalIndex);
const value = line.substring(equalIndex + 1);
this.addConfig(section, key.trim(), value.trim());
}
public getBool(key) {
return !!this.get(key);
}
public getInt(key) {
return Number.parseInt(this.get(key), 10);
}
public getFloat(key) {
return Number.parseFloat(this.get(key));
}
public getString(key) {
return this.get(key);
}
public getStrings(key) {
const v = this.get(key);
return v.split(',');
}
public set(key, value) {
if (!key) {
throw new Error('key is empty');
}
let section = '';
let option;
const keys = key.toLowerCase().split('::');
if (keys.length >= 2) {
section = keys[0];
option = keys[1];
} else {
option = keys[0];
}
this.addConfig(section, option, value);
}
public get(key) {
let section;
let option;
const keys = key.toLowerCase().split('::');
if (keys.length >= 2) {
section = keys[0];
option = keys[1];
} else {
section = Config.DEFAULT_SECTION;
option = keys[0];
}
const item = this.data.get(section);
const itemChild = item && item.get(option);
return itemChild ? itemChild : '';
}
}
|
487d30eb47ab01761611c56fba7726426dfdca30 | 3,791 | ts | TypeScript | src/video_canister_package/src/canisters/wallet_canister/walletCanister_idl.did.ts | IC-Kryptonic/Video-Canister | db9f36cecb1f07b1f06704586725b1ac89df30aa | [
"MIT"
] | null | null | null | src/video_canister_package/src/canisters/wallet_canister/walletCanister_idl.did.ts | IC-Kryptonic/Video-Canister | db9f36cecb1f07b1f06704586725b1ac89df30aa | [
"MIT"
] | 2 | 2022-03-20T07:29:13.000Z | 2022-03-21T09:43:51.000Z | src/video_canister_package/src/canisters/wallet_canister/walletCanister_idl.did.ts | IC-Kryptonic/Video-Canister | db9f36cecb1f07b1f06704586725b1ac89df30aa | [
"MIT"
] | null | null | null | /* tslint:disable */
// @ts-ignore
export const idlFactory = ({ IDL }) => {
const Kind = IDL.Variant({
User: IDL.Null,
Canister: IDL.Null,
Unknown: IDL.Null,
});
const Role = IDL.Variant({
Custodian: IDL.Null,
Contact: IDL.Null,
Controller: IDL.Null,
});
const AddressEntry = IDL.Record({
id: IDL.Principal,
kind: Kind,
name: IDL.Opt(IDL.Text),
role: Role,
});
const EventKind = IDL.Variant({
CyclesReceived: IDL.Record({
from: IDL.Principal,
amount: IDL.Nat64,
memo: IDL.Opt(IDL.Text),
}),
CanisterCreated: IDL.Record({
cycles: IDL.Nat64,
canister: IDL.Principal,
}),
CanisterCalled: IDL.Record({
cycles: IDL.Nat64,
method_name: IDL.Text,
canister: IDL.Principal,
}),
CyclesSent: IDL.Record({
to: IDL.Principal,
amount: IDL.Nat64,
refund: IDL.Nat64,
}),
AddressRemoved: IDL.Record({ id: IDL.Principal }),
WalletDeployed: IDL.Record({ canister: IDL.Principal }),
AddressAdded: IDL.Record({
id: IDL.Principal,
name: IDL.Opt(IDL.Text),
role: Role,
}),
});
const Event = IDL.Record({
id: IDL.Nat32,
kind: EventKind,
timestamp: IDL.Nat64,
});
const ResultCall = IDL.Variant({
Ok: IDL.Record({ return: IDL.Vec(IDL.Nat8) }),
Err: IDL.Text,
});
const CanisterSettings = IDL.Record({
controller: IDL.Opt(IDL.Principal),
controllers: IDL.Opt(IDL.Vec(IDL.Principal)),
freezing_threshold: IDL.Opt(IDL.Nat),
memory_allocation: IDL.Opt(IDL.Nat),
compute_allocation: IDL.Opt(IDL.Nat),
});
const CreateCanisterArgs = IDL.Record({
cycles: IDL.Nat64,
settings: CanisterSettings,
});
const ResultCreate = IDL.Variant({
Ok: IDL.Record({ canister_id: IDL.Principal }),
Err: IDL.Text,
});
const ResultSend = IDL.Variant({ Ok: IDL.Null, Err: IDL.Text });
return IDL.Service({
add_address: IDL.Func([AddressEntry], [], []),
add_controller: IDL.Func([IDL.Principal], [], []),
authorize: IDL.Func([IDL.Principal], [], []),
deauthorize: IDL.Func([IDL.Principal], [], []),
get_chart: IDL.Func(
[
IDL.Opt(
IDL.Record({
count: IDL.Opt(IDL.Nat32),
precision: IDL.Opt(IDL.Nat64),
}),
),
],
[IDL.Vec(IDL.Tuple(IDL.Nat64, IDL.Nat64))],
['query'],
),
get_controllers: IDL.Func([], [IDL.Vec(IDL.Principal)], ['query']),
get_custodians: IDL.Func([], [IDL.Vec(IDL.Principal)], ['query']),
get_events: IDL.Func(
[
IDL.Opt(
IDL.Record({
to: IDL.Opt(IDL.Nat32),
from: IDL.Opt(IDL.Nat32),
}),
),
],
[IDL.Vec(Event)],
['query'],
),
list_addresses: IDL.Func([], [IDL.Vec(AddressEntry)], ['query']),
name: IDL.Func([], [IDL.Opt(IDL.Text)], ['query']),
remove_address: IDL.Func([IDL.Principal], [], []),
remove_controller: IDL.Func([IDL.Principal], [], []),
set_name: IDL.Func([IDL.Text], [], []),
wallet_balance: IDL.Func([], [IDL.Record({ amount: IDL.Nat64 })], ['query']),
wallet_call: IDL.Func(
[
IDL.Record({
args: IDL.Vec(IDL.Nat8),
cycles: IDL.Nat64,
method_name: IDL.Text,
canister: IDL.Principal,
}),
],
[ResultCall],
[],
),
wallet_create_canister: IDL.Func([CreateCanisterArgs], [ResultCreate], []),
wallet_create_wallet: IDL.Func([CreateCanisterArgs], [ResultCreate], []),
wallet_receive: IDL.Func([], [], []),
wallet_send: IDL.Func([IDL.Record({ canister: IDL.Principal, amount: IDL.Nat64 })], [ResultSend], []),
wallet_store_wallet_wasm: IDL.Func([IDL.Record({ wasm_module: IDL.Vec(IDL.Nat8) })], [], []),
});
};
| 29.387597 | 106 | 0.572145 | 126 | 1 | 0 | 1 | 11 | 0 | 0 | 0 | 0 | 0 | 0 | 124 | 1,229 | 0.001627 | 0.00895 | 0 | 0 | 0 | 0 | 0 | 0.203615 | /* tslint:disable */
// @ts-ignore
export const idlFactory = ({ IDL }) => {
const Kind = IDL.Variant({
User: IDL.Null,
Canister: IDL.Null,
Unknown: IDL.Null,
});
const Role = IDL.Variant({
Custodian: IDL.Null,
Contact: IDL.Null,
Controller: IDL.Null,
});
const AddressEntry = IDL.Record({
id: IDL.Principal,
kind: Kind,
name: IDL.Opt(IDL.Text),
role: Role,
});
const EventKind = IDL.Variant({
CyclesReceived: IDL.Record({
from: IDL.Principal,
amount: IDL.Nat64,
memo: IDL.Opt(IDL.Text),
}),
CanisterCreated: IDL.Record({
cycles: IDL.Nat64,
canister: IDL.Principal,
}),
CanisterCalled: IDL.Record({
cycles: IDL.Nat64,
method_name: IDL.Text,
canister: IDL.Principal,
}),
CyclesSent: IDL.Record({
to: IDL.Principal,
amount: IDL.Nat64,
refund: IDL.Nat64,
}),
AddressRemoved: IDL.Record({ id: IDL.Principal }),
WalletDeployed: IDL.Record({ canister: IDL.Principal }),
AddressAdded: IDL.Record({
id: IDL.Principal,
name: IDL.Opt(IDL.Text),
role: Role,
}),
});
const Event = IDL.Record({
id: IDL.Nat32,
kind: EventKind,
timestamp: IDL.Nat64,
});
const ResultCall = IDL.Variant({
Ok: IDL.Record({ return: IDL.Vec(IDL.Nat8) }),
Err: IDL.Text,
});
const CanisterSettings = IDL.Record({
controller: IDL.Opt(IDL.Principal),
controllers: IDL.Opt(IDL.Vec(IDL.Principal)),
freezing_threshold: IDL.Opt(IDL.Nat),
memory_allocation: IDL.Opt(IDL.Nat),
compute_allocation: IDL.Opt(IDL.Nat),
});
const CreateCanisterArgs = IDL.Record({
cycles: IDL.Nat64,
settings: CanisterSettings,
});
const ResultCreate = IDL.Variant({
Ok: IDL.Record({ canister_id: IDL.Principal }),
Err: IDL.Text,
});
const ResultSend = IDL.Variant({ Ok: IDL.Null, Err: IDL.Text });
return IDL.Service({
add_address: IDL.Func([AddressEntry], [], []),
add_controller: IDL.Func([IDL.Principal], [], []),
authorize: IDL.Func([IDL.Principal], [], []),
deauthorize: IDL.Func([IDL.Principal], [], []),
get_chart: IDL.Func(
[
IDL.Opt(
IDL.Record({
count: IDL.Opt(IDL.Nat32),
precision: IDL.Opt(IDL.Nat64),
}),
),
],
[IDL.Vec(IDL.Tuple(IDL.Nat64, IDL.Nat64))],
['query'],
),
get_controllers: IDL.Func([], [IDL.Vec(IDL.Principal)], ['query']),
get_custodians: IDL.Func([], [IDL.Vec(IDL.Principal)], ['query']),
get_events: IDL.Func(
[
IDL.Opt(
IDL.Record({
to: IDL.Opt(IDL.Nat32),
from: IDL.Opt(IDL.Nat32),
}),
),
],
[IDL.Vec(Event)],
['query'],
),
list_addresses: IDL.Func([], [IDL.Vec(AddressEntry)], ['query']),
name: IDL.Func([], [IDL.Opt(IDL.Text)], ['query']),
remove_address: IDL.Func([IDL.Principal], [], []),
remove_controller: IDL.Func([IDL.Principal], [], []),
set_name: IDL.Func([IDL.Text], [], []),
wallet_balance: IDL.Func([], [IDL.Record({ amount: IDL.Nat64 })], ['query']),
wallet_call: IDL.Func(
[
IDL.Record({
args: IDL.Vec(IDL.Nat8),
cycles: IDL.Nat64,
method_name: IDL.Text,
canister: IDL.Principal,
}),
],
[ResultCall],
[],
),
wallet_create_canister: IDL.Func([CreateCanisterArgs], [ResultCreate], []),
wallet_create_wallet: IDL.Func([CreateCanisterArgs], [ResultCreate], []),
wallet_receive: IDL.Func([], [], []),
wallet_send: IDL.Func([IDL.Record({ canister: IDL.Principal, amount: IDL.Nat64 })], [ResultSend], []),
wallet_store_wallet_wasm: IDL.Func([IDL.Record({ wasm_module: IDL.Vec(IDL.Nat8) })], [], []),
});
};
|
48df0327cef37a44223febab50ee5a0a9894ba66 | 1,814 | ts | TypeScript | scripts/generate-widget-docs/tsdoc.ts | tenry92/flare-ui | 5db10680645bd48afec5d3df5ce80f544073c1e7 | [
"MIT"
] | null | null | null | scripts/generate-widget-docs/tsdoc.ts | tenry92/flare-ui | 5db10680645bd48afec5d3df5ce80f544073c1e7 | [
"MIT"
] | 6 | 2022-01-29T13:23:51.000Z | 2022-01-29T14:47:19.000Z | scripts/generate-widget-docs/tsdoc.ts | tenry92/flare-ui | 5db10680645bd48afec5d3df5ce80f544073c1e7 | [
"MIT"
] | null | null | null | export interface DocBlock {
tag: string;
content: string;
}
export interface DocComment {
summary?: string;
docBlocks: DocBlock[];
}
export function getDocBlocksByTag(docComment: DocComment, tag: string) {
return docComment.docBlocks.filter(block => block.tag == tag);
}
export function parseComment(comment: string) {
const rawContent = extractCommentContent(comment);
const regExp = /@(example|emits|cssProperty|htmlPart|reflectsHtmlAttribute|initsFromHtmlAttribute|cssState|param|return|internal)/g;
const docComment: DocComment = {
docBlocks: [],
};
let lastOffset = 0;
let precedingDocBlock: DocBlock | undefined;
while (true) {
const match = regExp.exec(rawContent);
if (!match) {
break;
}
const precedingContent = rawContent.substring(lastOffset, match.index);
lastOffset = match.index + match[0].length + 1;
if (docComment.summary == undefined) {
docComment.summary = precedingContent;
} else if (precedingDocBlock) {
precedingDocBlock.content = precedingContent;
}
precedingDocBlock = {
tag: match[0],
content: '',
};
docComment.docBlocks.push(precedingDocBlock);
}
const remainingContent = rawContent.substring(lastOffset);
if (docComment.summary == undefined) {
docComment.summary = remainingContent;
} else if (precedingDocBlock) {
precedingDocBlock.content = remainingContent;
}
return docComment;
}
/**
* Extract raw content from a multiline doc comment.
*/
function extractCommentContent(comment: string) {
return comment
.replace(/^\/\*\*+/, '') // remove leading /**
.replace(/\*+\/$/, '') // remove trailing */
.trim()
.split('\n').map(line => line.replace(/^\s*\*(\s|$)/, '')).join('\n') // remove * at start of a line
.trim()
;
}
| 24.513514 | 134 | 0.669239 | 54 | 5 | 0 | 6 | 8 | 4 | 1 | 0 | 6 | 2 | 0 | 8.4 | 484 | 0.022727 | 0.016529 | 0.008264 | 0.004132 | 0 | 0 | 0.26087 | 0.283822 | export interface DocBlock {
tag;
content;
}
export interface DocComment {
summary?;
docBlocks;
}
export function getDocBlocksByTag(docComment, tag) {
return docComment.docBlocks.filter(block => block.tag == tag);
}
export function parseComment(comment) {
const rawContent = extractCommentContent(comment);
const regExp = /@(example|emits|cssProperty|htmlPart|reflectsHtmlAttribute|initsFromHtmlAttribute|cssState|param|return|internal)/g;
const docComment = {
docBlocks: [],
};
let lastOffset = 0;
let precedingDocBlock;
while (true) {
const match = regExp.exec(rawContent);
if (!match) {
break;
}
const precedingContent = rawContent.substring(lastOffset, match.index);
lastOffset = match.index + match[0].length + 1;
if (docComment.summary == undefined) {
docComment.summary = precedingContent;
} else if (precedingDocBlock) {
precedingDocBlock.content = precedingContent;
}
precedingDocBlock = {
tag: match[0],
content: '',
};
docComment.docBlocks.push(precedingDocBlock);
}
const remainingContent = rawContent.substring(lastOffset);
if (docComment.summary == undefined) {
docComment.summary = remainingContent;
} else if (precedingDocBlock) {
precedingDocBlock.content = remainingContent;
}
return docComment;
}
/**
* Extract raw content from a multiline doc comment.
*/
/* Example usages of 'extractCommentContent' are shown below:
extractCommentContent(comment);
*/
function extractCommentContent(comment) {
return comment
.replace(/^\/\*\*+/, '') // remove leading /**
.replace(/\*+\/$/, '') // remove trailing */
.trim()
.split('\n').map(line => line.replace(/^\s*\*(\s|$)/, '')).join('\n') // remove * at start of a line
.trim()
;
}
|
48e9cb19d0024ad1b7d6dbe18f0828740f1395ef | 3,179 | ts | TypeScript | packages/rxlib-react/src/utils/mask.ts | rxcrud/rxlib | 4d0b580998ab7de2f6fb936b092811b93b986d86 | [
"MIT"
] | null | null | null | packages/rxlib-react/src/utils/mask.ts | rxcrud/rxlib | 4d0b580998ab7de2f6fb936b092811b93b986d86 | [
"MIT"
] | 2 | 2022-03-10T23:11:21.000Z | 2022-03-10T23:35:42.000Z | packages/rxlib-react/src/utils/mask.ts | rxcrud/rxlib-react | 4d0b580998ab7de2f6fb936b092811b93b986d86 | [
"MIT"
] | null | null | null | function maskCpf(value: string): string {
return value
.replace(/\D/g, '')
.replace(/(\d{3})(\d)/, '$1.$2')
.replace(/(\d{3})(\d)/, '$1.$2')
.replace(/(\d{3})(\d{1,2})/, '$1-$2')
.replace(/(-\d{2})\d+?$/, '$1');
}
function maskCnpj(value: string): string {
return value
.replace(/\D/g, '')
.replace(/(\d{2})(\d)/, '$1.$2')
.replace(/(\d{3})(\d)/, '$1.$2')
.replace(/(\d{3})(\d)/, '$1/$2')
.replace(/(\d{4})(\d{1,2})/, '$1-$2')
.replace(/(-\d{2})\d+?$/, '$1');
}
function maskCep(value: string): string {
return value
.replace(/\D/g, '')
.replace(/(\d{2})(\d)/, '$1.$2')
.replace(/(\d{3})(\d{1,3})/, '$1-$2')
.replace(/(-\d{3})\d+?$/, '$1');
}
function maskTelefone(value: string): string {
return value
.replace(/\D/g, '')
.replace(/(\d{2})(\d)/, '($1) $2')
.replace(/(\d{5})(\d{1,3})/, '$1-$2')
.replace(/(-\d{4})\d+?$/, '$1');
}
function maskCurrency(value: string): string {
value = value.replace(/\D/g, '');
if ((value.trim().length >= 4) && (value.startsWith('0')))
value = value.substring(1, value.trim().length);
switch (value.trim().length) {
case 0:
return '0,00';
case 1:
return value.replace(/(\d{1})/, '0,0$1');
case 2:
return value.replace(/(\d{2})/, '0,$1');
case 3:
return value.replace(/(\d{1})(\d{2})/, '$1,$2');
case 4:
return value.replace(/(\d{2})(\d{2})/, '$1,$2');
case 5:
return value.replace(/(\d{3})(\d{2})/, '$1,$2');
case 6:
return value.replace(/(\d{1})(\d{3})(\d{2})/, '$1.$2,$3');
case 7:
return value.replace(/(\d{2})(\d{3})(\d{2})/, '$1.$2,$3');
case 8:
return value.replace(/(\d{3})(\d{3})(\d{2})/, '$1.$2,$3');
case 9:
return value.replace(/(\d{1})(\d{3})(\d{3})(\d{2})/, '$1.$2.$3,$4');
case 10:
return value.replace(/(\d{2})(\d{3})(\d{3})(\d{2})/, '$1.$2.$3,$4');
case 11:
return value.replace(/(\d{3})(\d{3})(\d{3})(\d{2})/, '$1.$2.$3,$4');
default:
return value;
}
}
function maskNumber(value: string): string {
let valor = value
.replace(/\D/g, '')
.replaceAll('.', '')
.replaceAll(',', '');
return (valor === '')
? '0'
: String(parseInt(valor));
}
export type MaskType = 'cpf' | 'cnpj' | 'cep' | 'telefone' | 'currency' | 'number';
export function maskValue(value: string, mask: MaskType): string {
switch (mask) {
case 'cpf':
return maskCpf(value);
case 'cnpj':
return maskCnpj(value);
case 'cep':
return maskCep(value);
case 'telefone':
return maskTelefone(value);
case 'currency':
return maskCurrency(value);
case 'number':
return maskNumber(value);
default:
return value;
};
} | 31.166667 | 84 | 0.420573 | 92 | 7 | 0 | 8 | 1 | 0 | 6 | 0 | 14 | 1 | 0 | 11 | 1,017 | 0.014749 | 0.000983 | 0 | 0.000983 | 0 | 0 | 0.875 | 0.209763 | /* Example usages of 'maskCpf' are shown below:
maskCpf(value);
*/
function maskCpf(value) {
return value
.replace(/\D/g, '')
.replace(/(\d{3})(\d)/, '$1.$2')
.replace(/(\d{3})(\d)/, '$1.$2')
.replace(/(\d{3})(\d{1,2})/, '$1-$2')
.replace(/(-\d{2})\d+?$/, '$1');
}
/* Example usages of 'maskCnpj' are shown below:
maskCnpj(value);
*/
function maskCnpj(value) {
return value
.replace(/\D/g, '')
.replace(/(\d{2})(\d)/, '$1.$2')
.replace(/(\d{3})(\d)/, '$1.$2')
.replace(/(\d{3})(\d)/, '$1/$2')
.replace(/(\d{4})(\d{1,2})/, '$1-$2')
.replace(/(-\d{2})\d+?$/, '$1');
}
/* Example usages of 'maskCep' are shown below:
maskCep(value);
*/
function maskCep(value) {
return value
.replace(/\D/g, '')
.replace(/(\d{2})(\d)/, '$1.$2')
.replace(/(\d{3})(\d{1,3})/, '$1-$2')
.replace(/(-\d{3})\d+?$/, '$1');
}
/* Example usages of 'maskTelefone' are shown below:
maskTelefone(value);
*/
function maskTelefone(value) {
return value
.replace(/\D/g, '')
.replace(/(\d{2})(\d)/, '($1) $2')
.replace(/(\d{5})(\d{1,3})/, '$1-$2')
.replace(/(-\d{4})\d+?$/, '$1');
}
/* Example usages of 'maskCurrency' are shown below:
maskCurrency(value);
*/
function maskCurrency(value) {
value = value.replace(/\D/g, '');
if ((value.trim().length >= 4) && (value.startsWith('0')))
value = value.substring(1, value.trim().length);
switch (value.trim().length) {
case 0:
return '0,00';
case 1:
return value.replace(/(\d{1})/, '0,0$1');
case 2:
return value.replace(/(\d{2})/, '0,$1');
case 3:
return value.replace(/(\d{1})(\d{2})/, '$1,$2');
case 4:
return value.replace(/(\d{2})(\d{2})/, '$1,$2');
case 5:
return value.replace(/(\d{3})(\d{2})/, '$1,$2');
case 6:
return value.replace(/(\d{1})(\d{3})(\d{2})/, '$1.$2,$3');
case 7:
return value.replace(/(\d{2})(\d{3})(\d{2})/, '$1.$2,$3');
case 8:
return value.replace(/(\d{3})(\d{3})(\d{2})/, '$1.$2,$3');
case 9:
return value.replace(/(\d{1})(\d{3})(\d{3})(\d{2})/, '$1.$2.$3,$4');
case 10:
return value.replace(/(\d{2})(\d{3})(\d{3})(\d{2})/, '$1.$2.$3,$4');
case 11:
return value.replace(/(\d{3})(\d{3})(\d{3})(\d{2})/, '$1.$2.$3,$4');
default:
return value;
}
}
/* Example usages of 'maskNumber' are shown below:
maskNumber(value);
*/
function maskNumber(value) {
let valor = value
.replace(/\D/g, '')
.replaceAll('.', '')
.replaceAll(',', '');
return (valor === '')
? '0'
: String(parseInt(valor));
}
export type MaskType = 'cpf' | 'cnpj' | 'cep' | 'telefone' | 'currency' | 'number';
export function maskValue(value, mask) {
switch (mask) {
case 'cpf':
return maskCpf(value);
case 'cnpj':
return maskCnpj(value);
case 'cep':
return maskCep(value);
case 'telefone':
return maskTelefone(value);
case 'currency':
return maskCurrency(value);
case 'number':
return maskNumber(value);
default:
return value;
};
} |
5104c8f3f0b8ff16c0cac1d1b3d608c77dc68ee2 | 906 | ts | TypeScript | src/shared/utils/http.response.ts | kufre/farm-in | ac6775085be20ee885466a7f0d0dd9f8f0593d66 | [
"MIT"
] | 1 | 2022-03-07T22:06:12.000Z | 2022-03-07T22:06:12.000Z | src/shared/utils/http.response.ts | kufre/farm-in | ac6775085be20ee885466a7f0d0dd9f8f0593d66 | [
"MIT"
] | null | null | null | src/shared/utils/http.response.ts | kufre/farm-in | ac6775085be20ee885466a7f0d0dd9f8f0593d66 | [
"MIT"
] | null | null | null | class HttpStatusCode {
static OK() {
return {
value: 200,
writable: false,
enumerable: true,
configurable: false,
};
}
static CREATED() {
return {
value: 201,
writable: false,
enumerable: true,
configurable: false,
};
}
static UNPROCESSABLE_ENTITY() {
return {
value: 422,
writable: false,
enumerable: true,
configurable: false,
};
}
static INVALID_REQUEST() {
return {
value: 400,
writable: false,
enumerable: true,
configurable: false,
};
}
static UNAUTHORIZED() {
return {
value: 401,
writable: false,
enumerable: true,
configurable: false,
};
}
static FORBIDDEN() {
return {
value: 403,
writable: false,
enumerable: true,
configurable: false,
};
}
}
export default HttpStatusCode;
| 15.894737 | 33 | 0.546358 | 51 | 6 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 6 | 231 | 0.025974 | 0 | 0 | 0.004329 | 0 | 0 | 0 | 0.23779 | class HttpStatusCode {
static OK() {
return {
value: 200,
writable: false,
enumerable: true,
configurable: false,
};
}
static CREATED() {
return {
value: 201,
writable: false,
enumerable: true,
configurable: false,
};
}
static UNPROCESSABLE_ENTITY() {
return {
value: 422,
writable: false,
enumerable: true,
configurable: false,
};
}
static INVALID_REQUEST() {
return {
value: 400,
writable: false,
enumerable: true,
configurable: false,
};
}
static UNAUTHORIZED() {
return {
value: 401,
writable: false,
enumerable: true,
configurable: false,
};
}
static FORBIDDEN() {
return {
value: 403,
writable: false,
enumerable: true,
configurable: false,
};
}
}
export default HttpStatusCode;
|
5120d4f5b11f79cb9559fbe283d7ad380cf4cb36 | 2,752 | ts | TypeScript | packages/pro-table/shared/tool.ts | iheora/mina-components | 7e91b15d706b07a7caacd616eb177847f0ac2536 | [
"MIT"
] | 2 | 2022-02-07T03:49:56.000Z | 2022-02-07T06:04:07.000Z | packages/pro-table/shared/tool.ts | iheora/mina-components | 7e91b15d706b07a7caacd616eb177847f0ac2536 | [
"MIT"
] | 1 | 2022-02-07T05:40:14.000Z | 2022-02-07T12:53:03.000Z | packages/pro-table/shared/tool.ts | iheora/mina-components | 7e91b15d706b07a7caacd616eb177847f0ac2536 | [
"MIT"
] | 1 | 2022-02-07T06:04:14.000Z | 2022-02-07T06:04:14.000Z | /**
* @file 工具函数
* @module ProTable/shared
*/
/**
* @description 标准化列
* @param {Array} originColumns - 原始列
* @returns {Object}
*/
export const normalizeColumns = (originColumns) => {
const leftColumns = [] as any[];
const middleColumns = [] as any[];
const columns = originColumns.slice(0);
while (columns.length) {
const item = columns.shift();
if (item.fixed && item.fixed === 'left') {
leftColumns.push(item);
} else {
middleColumns.push(item);
}
}
return {
leftColumns,
middleColumns
};
};
/**
* @description 计算倍数
* @param {String} text
* @returns {Number}
*/
const getMultiiple = (text) => (/^\d+$/.test(text) ? 2 : 1);
/**
* @description 标准化数据源
* @param {Object} params
* @property {Array} params.leftColumns - 左侧固定列
* @property {Array} params.middleColumns - 正常列
* @property {Array} params.dataSource - 数据源
* @property {Number} params.hd - 表头高度
* @property {Number} params.wordLimit - 数据源
* @property {Number} params.rowH - 行高
* @returns {Object}
*/
export const normalizeDataSource = (
{
leftColumns = [] as any[],
middleColumns = [] as any[],
dataSource = [] as any[],
hd = 64,
wordLimit = 8,
rowH = 0
}
) => {
if (!dataSource.length) {
return {
height: hd,
dataSource
};
}
const increase = Math.floor(rowH / 3);
middleColumns = middleColumns.filter(col => col.tooltip) || [];
const height = dataSource.reduce((h, item, index) => {
let maxH = rowH;
middleColumns.forEach((col) => {
const { dataIndex, tooltip: { limit } } = col;
const field = item[dataIndex] || '';
if (field.length > limit) {
dataSource[index][dataIndex] = field.substr(0, limit);
dataSource[index][dataIndex + '_tooltip'] = field;
}
}, []);
leftColumns.forEach(col => {
let field = item[col.dataIndex] || '';
let divMultiple = getMultiiple(field);
if (col.sub) {
divMultiple = 2;
field += item[col.sub.dataIndex];
}
let multiple = Math.floor(field.length / (wordLimit * divMultiple));
if (col.extra && col.extra.merge) {
const mergeArr = Array.isArray(col.extra.merge) ? col.extra.merge : [col.extra.merge];
mergeArr.forEach(({ dataIndex, limit }) => {
const mergeField = item[dataIndex];
if (mergeField) {
const currMultiple = Math.floor(mergeField.length / (limit * getMultiiple(mergeField)));
multiple = Math.max(multiple, currMultiple);
}
});
}
maxH = rowH + increase * multiple;
dataSource[index]._custom_height = maxH;
});
return h + maxH;
}, rowH);
return {
height,
list: dataSource
};
};
| 22.373984 | 100 | 0.582122 | 74 | 8 | 0 | 10 | 18 | 0 | 1 | 5 | 0 | 0 | 5 | 15.375 | 796 | 0.022613 | 0.022613 | 0 | 0 | 0.006281 | 0.138889 | 0 | 0.29398 | /**
* @file 工具函数
* @module ProTable/shared
*/
/**
* @description 标准化列
* @param {Array} originColumns - 原始列
* @returns {Object}
*/
export const normalizeColumns = (originColumns) => {
const leftColumns = [] as any[];
const middleColumns = [] as any[];
const columns = originColumns.slice(0);
while (columns.length) {
const item = columns.shift();
if (item.fixed && item.fixed === 'left') {
leftColumns.push(item);
} else {
middleColumns.push(item);
}
}
return {
leftColumns,
middleColumns
};
};
/**
* @description 计算倍数
* @param {String} text
* @returns {Number}
*/
/* Example usages of 'getMultiiple' are shown below:
getMultiiple(field);
limit * getMultiiple(mergeField);
*/
const getMultiiple = (text) => (/^\d+$/.test(text) ? 2 : 1);
/**
* @description 标准化数据源
* @param {Object} params
* @property {Array} params.leftColumns - 左侧固定列
* @property {Array} params.middleColumns - 正常列
* @property {Array} params.dataSource - 数据源
* @property {Number} params.hd - 表头高度
* @property {Number} params.wordLimit - 数据源
* @property {Number} params.rowH - 行高
* @returns {Object}
*/
export const normalizeDataSource = (
{
leftColumns = [] as any[],
middleColumns = [] as any[],
dataSource = [] as any[],
hd = 64,
wordLimit = 8,
rowH = 0
}
) => {
if (!dataSource.length) {
return {
height: hd,
dataSource
};
}
const increase = Math.floor(rowH / 3);
middleColumns = middleColumns.filter(col => col.tooltip) || [];
const height = dataSource.reduce((h, item, index) => {
let maxH = rowH;
middleColumns.forEach((col) => {
const { dataIndex, tooltip: { limit } } = col;
const field = item[dataIndex] || '';
if (field.length > limit) {
dataSource[index][dataIndex] = field.substr(0, limit);
dataSource[index][dataIndex + '_tooltip'] = field;
}
}, []);
leftColumns.forEach(col => {
let field = item[col.dataIndex] || '';
let divMultiple = getMultiiple(field);
if (col.sub) {
divMultiple = 2;
field += item[col.sub.dataIndex];
}
let multiple = Math.floor(field.length / (wordLimit * divMultiple));
if (col.extra && col.extra.merge) {
const mergeArr = Array.isArray(col.extra.merge) ? col.extra.merge : [col.extra.merge];
mergeArr.forEach(({ dataIndex, limit }) => {
const mergeField = item[dataIndex];
if (mergeField) {
const currMultiple = Math.floor(mergeField.length / (limit * getMultiiple(mergeField)));
multiple = Math.max(multiple, currMultiple);
}
});
}
maxH = rowH + increase * multiple;
dataSource[index]._custom_height = maxH;
});
return h + maxH;
}, rowH);
return {
height,
list: dataSource
};
};
|
5138dfd36b6faf2623d71cd5a35b381d02adc19f | 1,997 | ts | TypeScript | src/utilities/index.ts | meecrobe/react-time-hook | 9ab9d822c7a54f79ba892b9b5da5bc48975e847a | [
"MIT"
] | null | null | null | src/utilities/index.ts | meecrobe/react-time-hook | 9ab9d822c7a54f79ba892b9b5da5bc48975e847a | [
"MIT"
] | 1 | 2022-01-02T13:29:24.000Z | 2022-01-02T14:40:00.000Z | src/utilities/index.ts | meecrobe/react-time-hook | 9ab9d822c7a54f79ba892b9b5da5bc48975e847a | [
"MIT"
] | null | null | null | export function getHoursAndMinutes(value: string): [number, number] {
let digits = value.split(':').map((digit) => digit.replace(/\D/g, '') || '0');
if (digits.length === 2) {
return [Number.parseInt(digits[0], 10), Number.parseInt(digits[1], 10)];
}
const timeValue = digits[0];
if (timeValue.length <= 2) {
return [Number.parseInt(timeValue, 10), 0];
}
return [
Number.parseInt(timeValue.substr(0, Math.floor(timeValue.length / 2)), 10),
Number.parseInt(timeValue.substr(Math.floor(timeValue.length / 2), 2), 10),
];
}
type TimePeriod = 'AM' | 'PM' | null;
export function getTimePeriod(value: string): TimePeriod {
const lowercaseValue = value.toLowerCase();
if (lowercaseValue.includes('p')) {
return 'PM';
}
if (lowercaseValue.includes('a')) {
return 'AM';
}
return null;
}
export function convertTo12Hour(
hours: number,
minutes: number,
timePeriod: TimePeriod,
padHoursWithZero: boolean = false,
) {
let _hours = hours;
let _minutes = minutes;
let _timePeriod = timePeriod;
if (hours > 24) {
_hours = 12;
}
if (timePeriod === null) {
_timePeriod = 'AM';
}
if (hours >= 12 && hours < 24 && timePeriod !== 'AM') {
_timePeriod = 'PM';
}
if (minutes > 59) {
_minutes = 0;
}
_hours = _hours % 12;
_hours = _hours ? _hours : 12;
return `${
padHoursWithZero ? addLeadingZero(_hours) : _hours
}:${addLeadingZero(_minutes)} ${_timePeriod}`;
}
export function convertTo24Hour(
hours: number,
minutes: number,
timePeriod: TimePeriod,
) {
let _hours = hours;
let _minutes = minutes;
if (hours >= 0 && hours < 12 && timePeriod === 'PM') {
_hours += 12;
}
if (hours > 23 || (hours === 12 && timePeriod === 'AM')) {
_hours = 0;
}
if (minutes > 59) {
_minutes = 0;
}
return `${addLeadingZero(_hours)}:${addLeadingZero(_minutes)}`;
}
function addLeadingZero(value: number): string {
return value < 10 ? '0' + value : value.toString();
}
| 20.802083 | 80 | 0.615423 | 73 | 6 | 0 | 11 | 8 | 0 | 1 | 0 | 11 | 1 | 0 | 9 | 658 | 0.025836 | 0.012158 | 0 | 0.00152 | 0 | 0 | 0.44 | 0.272372 | export function getHoursAndMinutes(value) {
let digits = value.split(':').map((digit) => digit.replace(/\D/g, '') || '0');
if (digits.length === 2) {
return [Number.parseInt(digits[0], 10), Number.parseInt(digits[1], 10)];
}
const timeValue = digits[0];
if (timeValue.length <= 2) {
return [Number.parseInt(timeValue, 10), 0];
}
return [
Number.parseInt(timeValue.substr(0, Math.floor(timeValue.length / 2)), 10),
Number.parseInt(timeValue.substr(Math.floor(timeValue.length / 2), 2), 10),
];
}
type TimePeriod = 'AM' | 'PM' | null;
export function getTimePeriod(value) {
const lowercaseValue = value.toLowerCase();
if (lowercaseValue.includes('p')) {
return 'PM';
}
if (lowercaseValue.includes('a')) {
return 'AM';
}
return null;
}
export function convertTo12Hour(
hours,
minutes,
timePeriod,
padHoursWithZero = false,
) {
let _hours = hours;
let _minutes = minutes;
let _timePeriod = timePeriod;
if (hours > 24) {
_hours = 12;
}
if (timePeriod === null) {
_timePeriod = 'AM';
}
if (hours >= 12 && hours < 24 && timePeriod !== 'AM') {
_timePeriod = 'PM';
}
if (minutes > 59) {
_minutes = 0;
}
_hours = _hours % 12;
_hours = _hours ? _hours : 12;
return `${
padHoursWithZero ? addLeadingZero(_hours) : _hours
}:${addLeadingZero(_minutes)} ${_timePeriod}`;
}
export function convertTo24Hour(
hours,
minutes,
timePeriod,
) {
let _hours = hours;
let _minutes = minutes;
if (hours >= 0 && hours < 12 && timePeriod === 'PM') {
_hours += 12;
}
if (hours > 23 || (hours === 12 && timePeriod === 'AM')) {
_hours = 0;
}
if (minutes > 59) {
_minutes = 0;
}
return `${addLeadingZero(_hours)}:${addLeadingZero(_minutes)}`;
}
/* Example usages of 'addLeadingZero' are shown below:
padHoursWithZero ? addLeadingZero(_hours) : _hours;
addLeadingZero(_minutes);
addLeadingZero(_hours);
*/
function addLeadingZero(value) {
return value < 10 ? '0' + value : value.toString();
}
|
892ec351e71d59a595c0c7da7c0870aba06f1532 | 1,499 | ts | TypeScript | tools/spiral.ts | ConnorUllmann/EngineTS | 9e5605fcc2140aabce49cc987d977565408d14f0 | [
"MIT"
] | 1 | 2022-01-14T20:35:58.000Z | 2022-01-14T20:35:58.000Z | tools/spiral.ts | ConnorUllmann/EngineTS | 9e5605fcc2140aabce49cc987d977565408d14f0 | [
"MIT"
] | null | null | null | tools/spiral.ts | ConnorUllmann/EngineTS | 9e5605fcc2140aabce49cc987d977565408d14f0 | [
"MIT"
] | null | null | null | // gives the x,y indices of a spiral along a tiled grid where n is the number of steps along the spiral
// n = 0 is (0, 0), n = 1 is (0, -1), then proceeds clockwise
export function spiral(n: number): { x: number, y: number } | null {
if(n < 0)
return null;
n++
const k = Math.ceil((Math.sqrt(n) - 1) / 2);
let t = 2 * k + 1;
let m = t * t;
t--;
return {
x: xSpiralHelper(n, m, t, k),
y: ySpiralHelper(n, m, t, k)
};
}
export function xSpiral(n: number): number | null {
if(n < 0)
return null;
n++
const k = Math.ceil((Math.sqrt(n) - 1) / 2);
let t = 2 * k + 1;
let m = t * t;
t--;
return xSpiralHelper(n, m, t, k);
}
export function ySpiral(n: number): number | null {
if(n < 0)
return null;
n++
const k = Math.ceil((Math.sqrt(n) - 1) / 2);
let t = 2 * k + 1;
let m = t * t;
t--;
return ySpiralHelper(n, m, t, k);
}
function xSpiralHelper(n: number, m: number, t: number, k: number): number {
if (n >= m - t)
return -k;
m -= t;
if (n >= m - t)
return m - n - k;
m -= t;
if (n >= m - t)
return k;
return -m + n + k + t;
}
function ySpiralHelper(n: number, m: number, t: number, k: number): number {
if (n >= m - t)
return -m + n + k;
m -= t;
if (n >= m - t)
return -k;
m -= t;
if (n >= m - t)
return m - k - n;
return k;
} | 20.256757 | 103 | 0.46431 | 55 | 5 | 0 | 11 | 9 | 0 | 2 | 0 | 17 | 0 | 0 | 9 | 546 | 0.029304 | 0.016484 | 0 | 0 | 0 | 0 | 0.68 | 0.292122 | // gives the x,y indices of a spiral along a tiled grid where n is the number of steps along the spiral
// n = 0 is (0, 0), n = 1 is (0, -1), then proceeds clockwise
export function spiral(n) {
if(n < 0)
return null;
n++
const k = Math.ceil((Math.sqrt(n) - 1) / 2);
let t = 2 * k + 1;
let m = t * t;
t--;
return {
x: xSpiralHelper(n, m, t, k),
y: ySpiralHelper(n, m, t, k)
};
}
export function xSpiral(n) {
if(n < 0)
return null;
n++
const k = Math.ceil((Math.sqrt(n) - 1) / 2);
let t = 2 * k + 1;
let m = t * t;
t--;
return xSpiralHelper(n, m, t, k);
}
export function ySpiral(n) {
if(n < 0)
return null;
n++
const k = Math.ceil((Math.sqrt(n) - 1) / 2);
let t = 2 * k + 1;
let m = t * t;
t--;
return ySpiralHelper(n, m, t, k);
}
/* Example usages of 'xSpiralHelper' are shown below:
xSpiralHelper(n, m, t, k);
*/
function xSpiralHelper(n, m, t, k) {
if (n >= m - t)
return -k;
m -= t;
if (n >= m - t)
return m - n - k;
m -= t;
if (n >= m - t)
return k;
return -m + n + k + t;
}
/* Example usages of 'ySpiralHelper' are shown below:
ySpiralHelper(n, m, t, k);
*/
function ySpiralHelper(n, m, t, k) {
if (n >= m - t)
return -m + n + k;
m -= t;
if (n >= m - t)
return -k;
m -= t;
if (n >= m - t)
return m - k - n;
return k;
} |
8942b9bffbeae8bdf02b8ff01a9a7a9bca89f53c | 6,118 | ts | TypeScript | src/compression/LZSS_LBA_type_1.ts | LBALab/hqr | 1ec3361283e0efbc8159c633580f538ae3c49e2f | [
"MIT"
] | 1 | 2022-01-25T13:12:22.000Z | 2022-01-25T13:12:22.000Z | src/compression/LZSS_LBA_type_1.ts | LBALab/hqr | 1ec3361283e0efbc8159c633580f538ae3c49e2f | [
"MIT"
] | 1 | 2022-01-25T01:30:08.000Z | 2022-01-25T01:58:58.000Z | src/compression/LZSS_LBA_type_1.ts | LBALab/hqr | 1ec3361283e0efbc8159c633580f538ae3c49e2f | [
"MIT"
] | null | null | null | const INDEX_BIT_COUNT = 12;
const LENGTH_BIT_COUNT = 4;
const WINDOW_SIZE = 1 << INDEX_BIT_COUNT;
const RAW_LOOK_AHEAD_SIZE = 1 << LENGTH_BIT_COUNT;
const BREAK_EVEN = Math.floor((1 + INDEX_BIT_COUNT + LENGTH_BIT_COUNT) / 9);
const LOOK_AHEAD_SIZE = RAW_LOOK_AHEAD_SIZE + BREAK_EVEN;
const TREE_ROOT = WINDOW_SIZE;
const UNUSED = -1;
const MOD_WINDOW = (a: number) => a & (WINDOW_SIZE - 1);
enum Child {
Smaller = 0,
Larger = 1,
}
interface DefTree {
parent: number;
children: [number, number];
}
let current_pos: number;
let match_pos: number;
const win = new Uint8Array(WINDOW_SIZE * 5);
const tree: DefTree[] = (() => {
const t = new Array<DefTree>(WINDOW_SIZE + 2);
for (let i = 0; i < t.length; i++) {
t[i] = { parent: 0, children: [0, 0] };
}
return t;
})();
function initTree(r: number) {
for (let i = 0; i <= WINDOW_SIZE; i++) {
const node = tree[i];
node.parent = UNUSED;
node.children[Child.Smaller] = UNUSED;
node.children[Child.Larger] = UNUSED;
}
tree[TREE_ROOT].children[Child.Larger] = r;
tree[r].parent = TREE_ROOT;
tree[-1] = tree[WINDOW_SIZE + 1];
}
function contractNode(old_node: number, new_node: number) {
tree[new_node].parent = tree[old_node].parent;
if (tree[tree[old_node].parent].children[Child.Larger] === old_node)
tree[tree[old_node].parent].children[Child.Larger] = new_node;
else tree[tree[old_node].parent].children[Child.Smaller] = new_node;
tree[old_node].parent = UNUSED;
}
function copyNode(new_node: number, old_node: number) {
tree[new_node].parent = tree[old_node].parent;
tree[new_node].children[Child.Smaller] =
tree[old_node].children[Child.Smaller];
tree[new_node].children[Child.Larger] = tree[old_node].children[Child.Larger];
}
function replaceNode(old_node: number, new_node: number) {
const parent = tree[old_node].parent;
if (tree[parent].children[Child.Smaller] === old_node)
tree[parent].children[Child.Smaller] = new_node;
else tree[parent].children[Child.Larger] = new_node;
copyNode(new_node, old_node);
if (tree[new_node].children[Child.Smaller] !== UNUSED)
tree[tree[new_node].children[Child.Smaller]].parent = new_node;
if (tree[new_node].children[Child.Larger] !== UNUSED)
tree[tree[new_node].children[Child.Larger]].parent = new_node;
tree[old_node].parent = UNUSED;
}
function findNextNode(node: number) {
let next = tree[node].children[Child.Smaller];
while (tree[next].children[Child.Larger] !== UNUSED)
next = tree[next].children[Child.Larger];
return next;
}
function deleteString(p: number) {
if (tree[p].parent === UNUSED) return;
if (tree[p].children[Child.Larger] === UNUSED)
contractNode(p, tree[p].children[Child.Smaller]);
else if (tree[p].children[Child.Smaller] === UNUSED)
contractNode(p, tree[p].children[Child.Larger]);
else {
const replacement = findNextNode(p);
deleteString(replacement);
replaceNode(p, replacement);
}
}
function addString(): number {
let i = 0;
let delta = 0;
let test_node = tree[TREE_ROOT].children[Child.Larger];
let match_length = 0;
for (;;) {
for (i = 0; i < LOOK_AHEAD_SIZE; i++) {
delta = win[MOD_WINDOW(current_pos + i)] - win[MOD_WINDOW(test_node + i)];
if (delta !== 0) break;
}
if (i >= match_length) {
match_length = i;
match_pos = test_node;
if (match_length >= LOOK_AHEAD_SIZE) {
replaceNode(test_node, current_pos);
return match_length;
}
}
const child_node = tree[test_node];
const child_prop = delta >= 0 ? Child.Larger : Child.Smaller;
if (child_node.children[child_prop] === UNUSED) {
child_node.children[child_prop] = current_pos;
tree[current_pos].parent = test_node;
tree[current_pos].children[Child.Larger] = UNUSED;
tree[current_pos].children[Child.Smaller] = UNUSED;
return match_length;
}
test_node = child_node.children[child_prop];
}
}
// Adapted from:
// https://github.com/2point21/lba2-classic/blob/main/SOURCES/LZSS.CPP
export function compressLZSS_LBA_type_1(data: ArrayBuffer): ArrayBuffer {
let i: number;
let read = 0;
let write = 0;
let info: number;
let look_ahead_bytes: number;
let replace_count: number;
let match_length: number;
let count_bits = 0;
let mask = 1;
let len = 0;
let length = data.byteLength;
const input = new Uint8Array(data);
const output = new Uint8Array(length);
const save_length = length;
current_pos = 0;
for (i = 0; i < LOOK_AHEAD_SIZE; i++) {
if (length === 0) break;
win[current_pos + i] = input[read++];
length--;
}
look_ahead_bytes = i;
initTree(current_pos);
match_length = 0;
match_pos = 0;
info = write++;
if (++len >= save_length) return data;
output[info] = 0;
while (look_ahead_bytes > 0) {
if (match_length > look_ahead_bytes) match_length = look_ahead_bytes;
if (match_length <= BREAK_EVEN) {
replace_count = 1;
output[info] |= mask;
output[write++] = win[current_pos];
if (++len >= save_length) return data;
} else {
if ((len = len + 2) >= save_length) return data;
const value =
(MOD_WINDOW(current_pos - match_pos - 1) << LENGTH_BIT_COUNT) |
(match_length - BREAK_EVEN - 1);
const low = (value & 0xff00) >> 8;
const high = value & 0xff;
output[write] = high;
output[write + 1] = low;
write += 2;
replace_count = match_length;
}
if (++count_bits === 8) {
if (++len >= save_length) return data;
info = write++;
output[info] = 0;
count_bits = 0;
mask = 1;
} else {
mask = (mask << 1) & 0xff;
}
for (i = 0; i < replace_count; i++) {
deleteString(MOD_WINDOW(current_pos + LOOK_AHEAD_SIZE));
if (length === 0) look_ahead_bytes--;
else {
win[MOD_WINDOW(current_pos + LOOK_AHEAD_SIZE)] = input[read++];
length--;
}
current_pos = MOD_WINDOW(current_pos + 1);
if (look_ahead_bytes) match_length = addString();
}
}
if (count_bits === 0) len--;
return output.buffer.slice(0, len);
}
| 29.272727 | 80 | 0.649722 | 181 | 10 | 0 | 11 | 43 | 2 | 8 | 0 | 21 | 1 | 0 | 14.4 | 2,083 | 0.010082 | 0.020643 | 0.00096 | 0.00048 | 0 | 0 | 0.318182 | 0.263516 | const INDEX_BIT_COUNT = 12;
const LENGTH_BIT_COUNT = 4;
const WINDOW_SIZE = 1 << INDEX_BIT_COUNT;
const RAW_LOOK_AHEAD_SIZE = 1 << LENGTH_BIT_COUNT;
const BREAK_EVEN = Math.floor((1 + INDEX_BIT_COUNT + LENGTH_BIT_COUNT) / 9);
const LOOK_AHEAD_SIZE = RAW_LOOK_AHEAD_SIZE + BREAK_EVEN;
const TREE_ROOT = WINDOW_SIZE;
const UNUSED = -1;
/* Example usages of 'MOD_WINDOW' are shown below:
delta = win[MOD_WINDOW(current_pos + i)] - win[MOD_WINDOW(test_node + i)];
MOD_WINDOW(current_pos - match_pos - 1) << LENGTH_BIT_COUNT;
deleteString(MOD_WINDOW(current_pos + LOOK_AHEAD_SIZE));
win[MOD_WINDOW(current_pos + LOOK_AHEAD_SIZE)] = input[read++];
current_pos = MOD_WINDOW(current_pos + 1);
*/
const MOD_WINDOW = (a) => a & (WINDOW_SIZE - 1);
enum Child {
Smaller = 0,
Larger = 1,
}
interface DefTree {
parent;
children;
}
let current_pos;
let match_pos;
const win = new Uint8Array(WINDOW_SIZE * 5);
const tree = (() => {
const t = new Array<DefTree>(WINDOW_SIZE + 2);
for (let i = 0; i < t.length; i++) {
t[i] = { parent: 0, children: [0, 0] };
}
return t;
})();
/* Example usages of 'initTree' are shown below:
initTree(current_pos);
*/
function initTree(r) {
for (let i = 0; i <= WINDOW_SIZE; i++) {
const node = tree[i];
node.parent = UNUSED;
node.children[Child.Smaller] = UNUSED;
node.children[Child.Larger] = UNUSED;
}
tree[TREE_ROOT].children[Child.Larger] = r;
tree[r].parent = TREE_ROOT;
tree[-1] = tree[WINDOW_SIZE + 1];
}
/* Example usages of 'contractNode' are shown below:
contractNode(p, tree[p].children[Child.Smaller]);
contractNode(p, tree[p].children[Child.Larger]);
*/
function contractNode(old_node, new_node) {
tree[new_node].parent = tree[old_node].parent;
if (tree[tree[old_node].parent].children[Child.Larger] === old_node)
tree[tree[old_node].parent].children[Child.Larger] = new_node;
else tree[tree[old_node].parent].children[Child.Smaller] = new_node;
tree[old_node].parent = UNUSED;
}
/* Example usages of 'copyNode' are shown below:
copyNode(new_node, old_node);
*/
function copyNode(new_node, old_node) {
tree[new_node].parent = tree[old_node].parent;
tree[new_node].children[Child.Smaller] =
tree[old_node].children[Child.Smaller];
tree[new_node].children[Child.Larger] = tree[old_node].children[Child.Larger];
}
/* Example usages of 'replaceNode' are shown below:
replaceNode(p, replacement);
replaceNode(test_node, current_pos);
*/
function replaceNode(old_node, new_node) {
const parent = tree[old_node].parent;
if (tree[parent].children[Child.Smaller] === old_node)
tree[parent].children[Child.Smaller] = new_node;
else tree[parent].children[Child.Larger] = new_node;
copyNode(new_node, old_node);
if (tree[new_node].children[Child.Smaller] !== UNUSED)
tree[tree[new_node].children[Child.Smaller]].parent = new_node;
if (tree[new_node].children[Child.Larger] !== UNUSED)
tree[tree[new_node].children[Child.Larger]].parent = new_node;
tree[old_node].parent = UNUSED;
}
/* Example usages of 'findNextNode' are shown below:
findNextNode(p);
*/
function findNextNode(node) {
let next = tree[node].children[Child.Smaller];
while (tree[next].children[Child.Larger] !== UNUSED)
next = tree[next].children[Child.Larger];
return next;
}
/* Example usages of 'deleteString' are shown below:
deleteString(replacement);
deleteString(MOD_WINDOW(current_pos + LOOK_AHEAD_SIZE));
*/
function deleteString(p) {
if (tree[p].parent === UNUSED) return;
if (tree[p].children[Child.Larger] === UNUSED)
contractNode(p, tree[p].children[Child.Smaller]);
else if (tree[p].children[Child.Smaller] === UNUSED)
contractNode(p, tree[p].children[Child.Larger]);
else {
const replacement = findNextNode(p);
deleteString(replacement);
replaceNode(p, replacement);
}
}
/* Example usages of 'addString' are shown below:
match_length = addString();
*/
function addString() {
let i = 0;
let delta = 0;
let test_node = tree[TREE_ROOT].children[Child.Larger];
let match_length = 0;
for (;;) {
for (i = 0; i < LOOK_AHEAD_SIZE; i++) {
delta = win[MOD_WINDOW(current_pos + i)] - win[MOD_WINDOW(test_node + i)];
if (delta !== 0) break;
}
if (i >= match_length) {
match_length = i;
match_pos = test_node;
if (match_length >= LOOK_AHEAD_SIZE) {
replaceNode(test_node, current_pos);
return match_length;
}
}
const child_node = tree[test_node];
const child_prop = delta >= 0 ? Child.Larger : Child.Smaller;
if (child_node.children[child_prop] === UNUSED) {
child_node.children[child_prop] = current_pos;
tree[current_pos].parent = test_node;
tree[current_pos].children[Child.Larger] = UNUSED;
tree[current_pos].children[Child.Smaller] = UNUSED;
return match_length;
}
test_node = child_node.children[child_prop];
}
}
// Adapted from:
// https://github.com/2point21/lba2-classic/blob/main/SOURCES/LZSS.CPP
export function compressLZSS_LBA_type_1(data) {
let i;
let read = 0;
let write = 0;
let info;
let look_ahead_bytes;
let replace_count;
let match_length;
let count_bits = 0;
let mask = 1;
let len = 0;
let length = data.byteLength;
const input = new Uint8Array(data);
const output = new Uint8Array(length);
const save_length = length;
current_pos = 0;
for (i = 0; i < LOOK_AHEAD_SIZE; i++) {
if (length === 0) break;
win[current_pos + i] = input[read++];
length--;
}
look_ahead_bytes = i;
initTree(current_pos);
match_length = 0;
match_pos = 0;
info = write++;
if (++len >= save_length) return data;
output[info] = 0;
while (look_ahead_bytes > 0) {
if (match_length > look_ahead_bytes) match_length = look_ahead_bytes;
if (match_length <= BREAK_EVEN) {
replace_count = 1;
output[info] |= mask;
output[write++] = win[current_pos];
if (++len >= save_length) return data;
} else {
if ((len = len + 2) >= save_length) return data;
const value =
(MOD_WINDOW(current_pos - match_pos - 1) << LENGTH_BIT_COUNT) |
(match_length - BREAK_EVEN - 1);
const low = (value & 0xff00) >> 8;
const high = value & 0xff;
output[write] = high;
output[write + 1] = low;
write += 2;
replace_count = match_length;
}
if (++count_bits === 8) {
if (++len >= save_length) return data;
info = write++;
output[info] = 0;
count_bits = 0;
mask = 1;
} else {
mask = (mask << 1) & 0xff;
}
for (i = 0; i < replace_count; i++) {
deleteString(MOD_WINDOW(current_pos + LOOK_AHEAD_SIZE));
if (length === 0) look_ahead_bytes--;
else {
win[MOD_WINDOW(current_pos + LOOK_AHEAD_SIZE)] = input[read++];
length--;
}
current_pos = MOD_WINDOW(current_pos + 1);
if (look_ahead_bytes) match_length = addString();
}
}
if (count_bits === 0) len--;
return output.buffer.slice(0, len);
}
|
899cd782647cca7af7edb8f3bf26809a9ec3ab37 | 2,532 | ts | TypeScript | docs/src/modules/utils/replaceMarkdownLinks.ts | MahmoudMans/material-ui | 510710c3a650dfecf616ba79ddb57e430c2752c5 | [
"MIT"
] | 2,045 | 2022-02-06T15:55:53.000Z | 2022-03-31T23:38:57.000Z | docs/src/modules/utils/replaceMarkdownLinks.ts | MahmoudMans/material-ui | 510710c3a650dfecf616ba79ddb57e430c2752c5 | [
"MIT"
] | 1,472 | 2022-02-06T14:49:30.000Z | 2022-03-31T21:38:20.000Z | docs/src/modules/utils/replaceMarkdownLinks.ts | MahmoudMans/material-ui | 510710c3a650dfecf616ba79ddb57e430c2752c5 | [
"MIT"
] | 1,127 | 2022-02-06T17:57:41.000Z | 2022-03-31T22:24:17.000Z | export const replaceMaterialLinks = (markdown: string) => {
return markdown.replace(
/\(\/(guides|customization|getting-started|discover-more)\/([^)]*)\)/gm,
'(/material-ui/$1/$2)',
);
};
export const replaceComponentLinks = (markdown: string) => {
return markdown
.replace(/\(\/components\/data-grid([^)]*)\)/gm, '(/x/react-data-grid$1)')
.replace(
/\(\/components\/((icons|material-icons|transitions|pickers|about-the-lab)\/?[^)]*)\)/gm,
'(/material-ui/$1)',
)
.replace(/\(\/components\/(?!tabs|breadcrumbs)([^)]*)\)/gm, '(/material-ui/react-$1)')
.replace(/\(\/material-ui\/(react-[-a-z]+)(x|ch)es(\/|#)([^)]*)\)/gm, '(/material-ui/$1$2$3$4)')
.replace(/\(\/material-ui\/(react-[-a-z]+)(x|ch)es"/gm, '(/material-ui/$1$2)')
.replace(
/\(\/material-ui\/(?!react-tabs|react-breadcrumbs)(react-[-a-z]+)s(\/|#)([^)]*)\)/gm,
'(/material-ui/$1$2$3)',
)
.replace(
/\(\/material-ui\/(?!react-tabs|react-breadcrumbs)(react-[-a-z]+)s"/gm,
'(/material-ui/$1)',
)
.replace(/react-trap-focu/gm, 'react-trap-focus')
.replace(/react-trap-focuss/gm, 'react-trap-focus')
.replace(/react-progres/gm, 'react-progress')
.replace(/react-progresss/gm, 'react-progress')
.replace(/\(\/components\/(tabs|breadcrumbs)([^)]*)\)/gm, '(/material-ui/react-$1$2)');
};
export const replaceAPILinks = (markdown: string) => {
return markdown
.replace(/\(\/api\/data-grid([^)]*)\)/gm, '(/x/api/data-grid$1)')
.replace(/\(\/api\/([^"/]+-unstyled)([^)]*)\)/gm, '(/base/api/$1$2)')
.replace(
/\(\/api\/(trap-focus|click-away-listener|no-ssr|portal|textarea-autosize)([^)]*)\)/gm,
'(/base/api/$1$2)',
)
.replace(
/\(\/api\/(loading-button|tab-list|tab-panel|date-picker|date-time-picker|time-picker|calendar-picker|calendar-picker-skeleton|desktop-picker|mobile-date-picker|month-picker|pickers-day|static-date-picker|year-picker|masonry|timeline|timeline-connector|timeline-content|timeline-dot|timeline-item|timeline-opposite-content|timeline-separator|unstable-trap-focus|tree-item|tree-view)([^)]*)\)/gm,
'(/material-ui/api/$1$2)',
)
.replace(/\(\/api\/([^)]*)\)/gm, '(/material-ui/api/$1)');
};
const replaceStylesLinks = (markdown: string) => {
return markdown.replace(/\(\/styles\/([^)]*)\)/gm, '(/system/styles/$1)');
};
export default function replaceMarkdownLinks(markdown: string) {
return replaceStylesLinks(replaceMaterialLinks(replaceAPILinks(replaceComponentLinks(markdown))));
}
| 46.036364 | 401 | 0.610979 | 50 | 5 | 0 | 5 | 4 | 0 | 4 | 0 | 5 | 0 | 0 | 8 | 863 | 0.011587 | 0.004635 | 0 | 0 | 0 | 0 | 0.357143 | 0.212847 | export /* Example usages of 'replaceMaterialLinks' are shown below:
replaceStylesLinks(replaceMaterialLinks(replaceAPILinks(replaceComponentLinks(markdown))));
*/
const replaceMaterialLinks = (markdown) => {
return markdown.replace(
/\(\/(guides|customization|getting-started|discover-more)\/([^)]*)\)/gm,
'(/material-ui/$1/$2)',
);
};
export /* Example usages of 'replaceComponentLinks' are shown below:
replaceStylesLinks(replaceMaterialLinks(replaceAPILinks(replaceComponentLinks(markdown))));
*/
const replaceComponentLinks = (markdown) => {
return markdown
.replace(/\(\/components\/data-grid([^)]*)\)/gm, '(/x/react-data-grid$1)')
.replace(
/\(\/components\/((icons|material-icons|transitions|pickers|about-the-lab)\/?[^)]*)\)/gm,
'(/material-ui/$1)',
)
.replace(/\(\/components\/(?!tabs|breadcrumbs)([^)]*)\)/gm, '(/material-ui/react-$1)')
.replace(/\(\/material-ui\/(react-[-a-z]+)(x|ch)es(\/|#)([^)]*)\)/gm, '(/material-ui/$1$2$3$4)')
.replace(/\(\/material-ui\/(react-[-a-z]+)(x|ch)es"/gm, '(/material-ui/$1$2)')
.replace(
/\(\/material-ui\/(?!react-tabs|react-breadcrumbs)(react-[-a-z]+)s(\/|#)([^)]*)\)/gm,
'(/material-ui/$1$2$3)',
)
.replace(
/\(\/material-ui\/(?!react-tabs|react-breadcrumbs)(react-[-a-z]+)s"/gm,
'(/material-ui/$1)',
)
.replace(/react-trap-focu/gm, 'react-trap-focus')
.replace(/react-trap-focuss/gm, 'react-trap-focus')
.replace(/react-progres/gm, 'react-progress')
.replace(/react-progresss/gm, 'react-progress')
.replace(/\(\/components\/(tabs|breadcrumbs)([^)]*)\)/gm, '(/material-ui/react-$1$2)');
};
export /* Example usages of 'replaceAPILinks' are shown below:
replaceStylesLinks(replaceMaterialLinks(replaceAPILinks(replaceComponentLinks(markdown))));
*/
const replaceAPILinks = (markdown) => {
return markdown
.replace(/\(\/api\/data-grid([^)]*)\)/gm, '(/x/api/data-grid$1)')
.replace(/\(\/api\/([^"/]+-unstyled)([^)]*)\)/gm, '(/base/api/$1$2)')
.replace(
/\(\/api\/(trap-focus|click-away-listener|no-ssr|portal|textarea-autosize)([^)]*)\)/gm,
'(/base/api/$1$2)',
)
.replace(
/\(\/api\/(loading-button|tab-list|tab-panel|date-picker|date-time-picker|time-picker|calendar-picker|calendar-picker-skeleton|desktop-picker|mobile-date-picker|month-picker|pickers-day|static-date-picker|year-picker|masonry|timeline|timeline-connector|timeline-content|timeline-dot|timeline-item|timeline-opposite-content|timeline-separator|unstable-trap-focus|tree-item|tree-view)([^)]*)\)/gm,
'(/material-ui/api/$1$2)',
)
.replace(/\(\/api\/([^)]*)\)/gm, '(/material-ui/api/$1)');
};
/* Example usages of 'replaceStylesLinks' are shown below:
replaceStylesLinks(replaceMaterialLinks(replaceAPILinks(replaceComponentLinks(markdown))));
*/
const replaceStylesLinks = (markdown) => {
return markdown.replace(/\(\/styles\/([^)]*)\)/gm, '(/system/styles/$1)');
};
export default function replaceMarkdownLinks(markdown) {
return replaceStylesLinks(replaceMaterialLinks(replaceAPILinks(replaceComponentLinks(markdown))));
}
|
89b6fb431a8a13a9a0b0406697e12861713892d4 | 2,821 | ts | TypeScript | problemset/longest-valid-parentheses/index.ts | OUDUIDUI/leet-code | 50e61ce16d1c419ccefc075ae9ead721cdd1cdbb | [
"MIT"
] | 6 | 2022-01-17T03:19:56.000Z | 2022-01-17T05:45:39.000Z | problemset/longest-valid-parentheses/index.ts | OUDUIDUI/leet-code | 50e61ce16d1c419ccefc075ae9ead721cdd1cdbb | [
"MIT"
] | null | null | null | problemset/longest-valid-parentheses/index.ts | OUDUIDUI/leet-code | 50e61ce16d1c419ccefc075ae9ead721cdd1cdbb | [
"MIT"
] | null | null | null | /**
* 暴力解法
* @desc 时间复杂度 O(N^2) 空间复杂度O(N)
* @param s {string}
* @return {number}
*/
export function longestValidParentheses(s: string): number {
if (s.length < 2) return 0
let ans = 0
let left = 0
while (left < s.length - 1) {
let maxLen = 0
const stack: string[] = []
for (let i: number = left; i < s.length; i++) {
if (!stack.length)
stack.push(s[i])
else if (stack[stack.length - 1] === '(' && s[i] === ')')
stack.pop()
else
stack.push(s[i])
if (stack.length === 0) maxLen = i - left + 1
}
ans = ans < maxLen ? maxLen : ans
left++
}
return ans
}
/**
* 栈
* @desc 时间复杂度 O(N) 空间复杂度O(N)
* @param s {string}
* @return {number}
*/
export function longestValidParentheses2(s: string): number {
if (s.length < 2) return 0
let ans = 0
const stack: number[] = [-1]
for (let i = 0; i < s.length; i++) {
if (s[i] === '(') {
// 当是'('的时候,将i放入栈中
stack.push(i)
}
else {
// 当是')'的时候,先弹出栈顶表示匹配当前有括号
stack.pop()
if (!stack.length) {
// 如果栈为空的话,则代表当前')'没有匹配的'(',因此将其下标发回栈中
// 此时i为最后一个没有匹配的右括号下标
stack.push(i)
}
else {
// 如果栈不为空,则i减去栈顶值为有效括号长度
ans = Math.max(ans, i - stack[stack.length - 1])
}
}
}
return ans
}
/**
* 动态规划
* @desc 时间复杂度 O(N) 空间复杂度O(N)
* @param s {string}
* @return {number}
*/
export function longestValidParentheses3(s: string): number {
if (s.length < 2) return 0
let ans = 0
// 初始化s.length长度的数组,填充为0
// 默认是'('为0
const dp: number[] = Array(s.length).fill(0)
for (let i = 1; i < s.length; i++) {
if (s[i] === ')') {
if (s[i - 1] === '(') {
// 当s[i]为'('同时s[i - 1]为'('时,dp[i]为dp[i - 2] + 2
dp[i] = (i >= 2 ? dp[i - 2] : 0) + 2
}
else if (i - dp[i - 1] > 0 && s[i - dp[i - 1] - 1] === '(') {
// 当多个')'一起时,同时前面还有一个'('与s[i]组合的话,dp[i]为dp[i - 1] + dp[i - dp[i - 1] - 2] + 2
dp[i]
= dp[i - 1] + (i - dp[i - 1] >= 2 ? dp[i - dp[i - 1] - 2] : 0) + 2
}
ans = Math.max(ans, dp[i])
}
}
return ans
}
/**
* 计数
* @desc 时间复杂度 O(2N) 空间复杂度O(1)
* @param s {string}
* @return {number}
*/
export function longestValidParentheses4(s: string): number {
if (s.length < 2) return 0
let ans = 0
let left = 0
let right = 0
for (let i = 0; i < s.length; i++) {
if (s[i] === '(')
left++
else
right++
if (left === right)
ans = Math.max(ans, left + right)
else if (right > left)
left = right = 0
}
left = right = 0
for (let j: number = s.length - 1; j >= 0; j--) {
if (s[j] === '(')
left++
else
right++
if (left === right)
ans = Math.max(ans, left + right)
else if (left > right)
left = right = 0
}
return ans
}
| 19.866197 | 85 | 0.479972 | 87 | 4 | 0 | 4 | 16 | 0 | 0 | 0 | 13 | 0 | 0 | 19.75 | 1,185 | 0.006751 | 0.013502 | 0 | 0 | 0 | 0 | 0.541667 | 0.229299 | /**
* 暴力解法
* @desc 时间复杂度 O(N^2) 空间复杂度O(N)
* @param s {string}
* @return {number}
*/
export function longestValidParentheses(s) {
if (s.length < 2) return 0
let ans = 0
let left = 0
while (left < s.length - 1) {
let maxLen = 0
const stack = []
for (let i = left; i < s.length; i++) {
if (!stack.length)
stack.push(s[i])
else if (stack[stack.length - 1] === '(' && s[i] === ')')
stack.pop()
else
stack.push(s[i])
if (stack.length === 0) maxLen = i - left + 1
}
ans = ans < maxLen ? maxLen : ans
left++
}
return ans
}
/**
* 栈
* @desc 时间复杂度 O(N) 空间复杂度O(N)
* @param s {string}
* @return {number}
*/
export function longestValidParentheses2(s) {
if (s.length < 2) return 0
let ans = 0
const stack = [-1]
for (let i = 0; i < s.length; i++) {
if (s[i] === '(') {
// 当是'('的时候,将i放入栈中
stack.push(i)
}
else {
// 当是')'的时候,先弹出栈顶表示匹配当前有括号
stack.pop()
if (!stack.length) {
// 如果栈为空的话,则代表当前')'没有匹配的'(',因此将其下标发回栈中
// 此时i为最后一个没有匹配的右括号下标
stack.push(i)
}
else {
// 如果栈不为空,则i减去栈顶值为有效括号长度
ans = Math.max(ans, i - stack[stack.length - 1])
}
}
}
return ans
}
/**
* 动态规划
* @desc 时间复杂度 O(N) 空间复杂度O(N)
* @param s {string}
* @return {number}
*/
export function longestValidParentheses3(s) {
if (s.length < 2) return 0
let ans = 0
// 初始化s.length长度的数组,填充为0
// 默认是'('为0
const dp = Array(s.length).fill(0)
for (let i = 1; i < s.length; i++) {
if (s[i] === ')') {
if (s[i - 1] === '(') {
// 当s[i]为'('同时s[i - 1]为'('时,dp[i]为dp[i - 2] + 2
dp[i] = (i >= 2 ? dp[i - 2] : 0) + 2
}
else if (i - dp[i - 1] > 0 && s[i - dp[i - 1] - 1] === '(') {
// 当多个')'一起时,同时前面还有一个'('与s[i]组合的话,dp[i]为dp[i - 1] + dp[i - dp[i - 1] - 2] + 2
dp[i]
= dp[i - 1] + (i - dp[i - 1] >= 2 ? dp[i - dp[i - 1] - 2] : 0) + 2
}
ans = Math.max(ans, dp[i])
}
}
return ans
}
/**
* 计数
* @desc 时间复杂度 O(2N) 空间复杂度O(1)
* @param s {string}
* @return {number}
*/
export function longestValidParentheses4(s) {
if (s.length < 2) return 0
let ans = 0
let left = 0
let right = 0
for (let i = 0; i < s.length; i++) {
if (s[i] === '(')
left++
else
right++
if (left === right)
ans = Math.max(ans, left + right)
else if (right > left)
left = right = 0
}
left = right = 0
for (let j = s.length - 1; j >= 0; j--) {
if (s[j] === '(')
left++
else
right++
if (left === right)
ans = Math.max(ans, left + right)
else if (left > right)
left = right = 0
}
return ans
}
|
89bac55eda5f6185180668d1e0cce46b3a2332fb | 7,195 | ts | TypeScript | source/dwi/nodejs-assets/nodejs-project/src/idls/ext.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/ext.did.ts | fury02/Difiwallet | 7f4417546b0f51aa76901a720d9d64b392b13452 | [
"MIT"
] | null | null | null | source/dwi/nodejs-assets/nodejs-project/src/idls/ext.did.ts | fury02/Difiwallet | 7f4417546b0f51aa76901a720d9d64b392b13452 | [
"MIT"
] | null | null | null | /* eslint-disable camelcase */
/* eslint-disable @typescript-eslint/camelcase */
export default ({ IDL }) => {
const SubAccount_2 = IDL.Vec(IDL.Nat8);
const SubAccount = SubAccount_2;
const SubAccount_3 = SubAccount;
const TokenIndex_2 = IDL.Nat32;
const TokenIndex = TokenIndex_2;
const AccountIdentifier_2 = IDL.Text;
const AccountIdentifier = AccountIdentifier_2;
const AccountIdentifier_3 = AccountIdentifier;
const Fee = IDL.Nat;
const Settlement = IDL.Record({
subaccount: SubAccount_3,
seller: IDL.Principal,
buyer: AccountIdentifier_3,
price: IDL.Nat64,
});
const Metadata_2 = IDL.Variant({
fungible: IDL.Record({
decimals: IDL.Nat8,
metadata: IDL.Opt(IDL.Vec(IDL.Nat8)),
name: IDL.Text,
symbol: IDL.Text,
}),
nonfungible: IDL.Record({ metadata: IDL.Opt(IDL.Vec(IDL.Nat8)) }),
});
const Metadata = Metadata_2;
const TokenIdentifier = IDL.Text;
const User = IDL.Variant({
principal: IDL.Principal,
address: AccountIdentifier,
});
const BalanceRequest_2 = IDL.Record({
token: TokenIdentifier,
user: User,
});
const BalanceRequest = BalanceRequest_2;
const Balance = IDL.Nat;
const CommonError_2 = IDL.Variant({
InvalidToken: TokenIdentifier,
Other: IDL.Text,
});
const Result_9 = IDL.Variant({ ok: Balance, err: CommonError_2 });
const BalanceResponse_2 = Result_9;
const BalanceResponse = BalanceResponse_2;
const TokenIdentifier_2 = TokenIdentifier;
const CommonError = CommonError_2;
const Result_6 = IDL.Variant({
ok: AccountIdentifier_3,
err: CommonError,
});
const Time_2 = IDL.Int;
const Time = Time_2;
const Listing = IDL.Record({
locked: IDL.Opt(Time),
seller: IDL.Principal,
price: IDL.Nat64,
});
const Result_8 = IDL.Variant({
ok: IDL.Tuple(AccountIdentifier_3, IDL.Opt(Listing)),
err: CommonError,
});
const User_2 = User;
const Extension_2 = IDL.Text;
const Extension = Extension_2;
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 Result_7 = IDL.Variant({ ok: TokenIndex, err: CommonError });
const ListRequest = IDL.Record({
token: TokenIdentifier_2,
from_subaccount: IDL.Opt(SubAccount_3),
price: IDL.Opt(IDL.Nat64),
});
const Result_4 = IDL.Variant({ ok: IDL.Null, err: CommonError });
const Result_5 = IDL.Variant({ ok: Metadata, err: CommonError });
const MintRequest_2 = IDL.Record({
to: User,
metadata: IDL.Opt(IDL.Vec(IDL.Nat8)),
});
const MintRequest = MintRequest_2;
const Balance_2 = Balance;
const Result_3 = IDL.Variant({ ok: Balance_2, err: CommonError });
const Result_2 = IDL.Variant({
ok: IDL.Vec(TokenIndex),
err: CommonError,
});
const Transaction2 = IDL.Record({
token: TokenIdentifier_2,
time: Time,
seller: IDL.Principal,
buyer: AccountIdentifier_3,
price: IDL.Nat64,
});
const Memo = IDL.Vec(IDL.Nat8);
const TransferRequest_2 = IDL.Record({
to: User,
token: TokenIdentifier,
notify: IDL.Bool,
from: User,
memo: Memo,
subaccount: IDL.Opt(SubAccount),
amount: Balance,
fee: Fee,
});
const TransferRequest = TransferRequest_2;
const Result = IDL.Variant({
ok: Balance,
err: IDL.Variant({
CannotNotify: AccountIdentifier,
InsufficientBalance: IDL.Null,
InvalidToken: TokenIdentifier,
Rejected: IDL.Null,
Unauthorized: AccountIdentifier,
Other: IDL.Text,
}),
});
const TransferResponse_2 = Result;
const TransferResponse = TransferResponse_2;
const erc721_token = IDL.Service({
acceptCycles: IDL.Func([], [], []),
addRefund: IDL.Func(
[IDL.Text, IDL.Principal, SubAccount_3],
[],
['oneway']
),
availableCycles: IDL.Func([], [IDL.Nat], ['query']),
backendRefundSettlement: IDL.Func(
[IDL.Text],
[
IDL.Vec(IDL.Tuple(TokenIndex, Settlement)),
IDL.Vec(IDL.Tuple(AccountIdentifier_3, IDL.Principal, SubAccount_3)),
IDL.Vec(IDL.Tuple(IDL.Principal, IDL.Vec(SubAccount_3))),
IDL.Vec(IDL.Tuple(IDL.Principal, IDL.Vec(SubAccount_3))),
],
['query']
),
backup: IDL.Func(
[],
[
IDL.Vec(IDL.Tuple(TokenIndex, AccountIdentifier_3)),
IDL.Vec(IDL.Tuple(AccountIdentifier_3, IDL.Vec(TokenIndex))),
IDL.Vec(IDL.Tuple(TokenIndex, Metadata)),
],
['query']
),
balance: IDL.Func([BalanceRequest], [BalanceResponse], ['query']),
bearer: IDL.Func([TokenIdentifier_2], [Result_6], ['query']),
details: IDL.Func([TokenIdentifier_2], [Result_8], ['query']),
disribute: IDL.Func([User_2], [], []),
extensions: IDL.Func([], [IDL.Vec(Extension)], ['query']),
freeGift: IDL.Func([AccountIdentifier_3], [IDL.Opt(TokenIndex)], []),
getAllPayments: IDL.Func(
[],
[IDL.Vec(IDL.Tuple(IDL.Principal, IDL.Vec(SubAccount_3)))],
['query']
),
getBuyers: IDL.Func(
[],
[IDL.Vec(IDL.Tuple(AccountIdentifier_3, IDL.Vec(TokenIndex)))],
['query']
),
getMinted: IDL.Func([], [TokenIndex], ['query']),
getMinter: IDL.Func([], [IDL.Principal], ['query']),
getRegistry: IDL.Func(
[],
[IDL.Vec(IDL.Tuple(TokenIndex, AccountIdentifier_3))],
['query']
),
getSold: IDL.Func([], [TokenIndex], ['query']),
getTokens: IDL.Func(
[],
[IDL.Vec(IDL.Tuple(TokenIndex, Metadata))],
['query']
),
http_request: IDL.Func([HttpRequest], [HttpResponse], ['query']),
index: IDL.Func([TokenIdentifier_2], [Result_7], ['query']),
list: IDL.Func([ListRequest], [Result_4], []),
listings: IDL.Func(
[],
[IDL.Vec(IDL.Tuple(TokenIndex, Listing, Metadata))],
['query']
),
lock: IDL.Func(
[TokenIdentifier_2, IDL.Nat64, AccountIdentifier_3, SubAccount_3],
[Result_6],
[]
),
metadata: IDL.Func([TokenIdentifier_2], [Result_5], ['query']),
mintNFT: IDL.Func([MintRequest], [TokenIndex], []),
payments: IDL.Func([], [IDL.Opt(IDL.Vec(SubAccount_3))], ['query']),
refunds: IDL.Func([], [IDL.Opt(IDL.Vec(SubAccount_3))], ['query']),
removePayments: IDL.Func([IDL.Vec(SubAccount_3)], [], []),
removeRefunds: IDL.Func([IDL.Vec(SubAccount_3)], [], []),
setMinter: IDL.Func([IDL.Principal], [], []),
settle: IDL.Func([TokenIdentifier_2], [Result_4], []),
settle_force: IDL.Func([IDL.Text, TokenIdentifier_2], [], ['oneway']),
settlements: IDL.Func(
[],
[IDL.Vec(IDL.Tuple(TokenIndex, AccountIdentifier_3, IDL.Nat64))],
['query']
),
supply: IDL.Func([TokenIdentifier_2], [Result_3], ['query']),
tokens: IDL.Func([AccountIdentifier_3], [Result_2], ['query']),
transactions: IDL.Func([], [IDL.Vec(Transaction2)], ['query']),
transfer: IDL.Func([TransferRequest], [TransferResponse], []),
});
return erc721_token;
};
export const init = () => {
return [];
};
| 32.264574 | 77 | 0.636136 | 220 | 2 | 0 | 1 | 52 | 0 | 0 | 0 | 0 | 0 | 0 | 108 | 2,239 | 0.00134 | 0.023225 | 0 | 0 | 0 | 0 | 0 | 0.249516 | /* eslint-disable camelcase */
/* eslint-disable @typescript-eslint/camelcase */
export default ({ IDL }) => {
const SubAccount_2 = IDL.Vec(IDL.Nat8);
const SubAccount = SubAccount_2;
const SubAccount_3 = SubAccount;
const TokenIndex_2 = IDL.Nat32;
const TokenIndex = TokenIndex_2;
const AccountIdentifier_2 = IDL.Text;
const AccountIdentifier = AccountIdentifier_2;
const AccountIdentifier_3 = AccountIdentifier;
const Fee = IDL.Nat;
const Settlement = IDL.Record({
subaccount: SubAccount_3,
seller: IDL.Principal,
buyer: AccountIdentifier_3,
price: IDL.Nat64,
});
const Metadata_2 = IDL.Variant({
fungible: IDL.Record({
decimals: IDL.Nat8,
metadata: IDL.Opt(IDL.Vec(IDL.Nat8)),
name: IDL.Text,
symbol: IDL.Text,
}),
nonfungible: IDL.Record({ metadata: IDL.Opt(IDL.Vec(IDL.Nat8)) }),
});
const Metadata = Metadata_2;
const TokenIdentifier = IDL.Text;
const User = IDL.Variant({
principal: IDL.Principal,
address: AccountIdentifier,
});
const BalanceRequest_2 = IDL.Record({
token: TokenIdentifier,
user: User,
});
const BalanceRequest = BalanceRequest_2;
const Balance = IDL.Nat;
const CommonError_2 = IDL.Variant({
InvalidToken: TokenIdentifier,
Other: IDL.Text,
});
const Result_9 = IDL.Variant({ ok: Balance, err: CommonError_2 });
const BalanceResponse_2 = Result_9;
const BalanceResponse = BalanceResponse_2;
const TokenIdentifier_2 = TokenIdentifier;
const CommonError = CommonError_2;
const Result_6 = IDL.Variant({
ok: AccountIdentifier_3,
err: CommonError,
});
const Time_2 = IDL.Int;
const Time = Time_2;
const Listing = IDL.Record({
locked: IDL.Opt(Time),
seller: IDL.Principal,
price: IDL.Nat64,
});
const Result_8 = IDL.Variant({
ok: IDL.Tuple(AccountIdentifier_3, IDL.Opt(Listing)),
err: CommonError,
});
const User_2 = User;
const Extension_2 = IDL.Text;
const Extension = Extension_2;
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 Result_7 = IDL.Variant({ ok: TokenIndex, err: CommonError });
const ListRequest = IDL.Record({
token: TokenIdentifier_2,
from_subaccount: IDL.Opt(SubAccount_3),
price: IDL.Opt(IDL.Nat64),
});
const Result_4 = IDL.Variant({ ok: IDL.Null, err: CommonError });
const Result_5 = IDL.Variant({ ok: Metadata, err: CommonError });
const MintRequest_2 = IDL.Record({
to: User,
metadata: IDL.Opt(IDL.Vec(IDL.Nat8)),
});
const MintRequest = MintRequest_2;
const Balance_2 = Balance;
const Result_3 = IDL.Variant({ ok: Balance_2, err: CommonError });
const Result_2 = IDL.Variant({
ok: IDL.Vec(TokenIndex),
err: CommonError,
});
const Transaction2 = IDL.Record({
token: TokenIdentifier_2,
time: Time,
seller: IDL.Principal,
buyer: AccountIdentifier_3,
price: IDL.Nat64,
});
const Memo = IDL.Vec(IDL.Nat8);
const TransferRequest_2 = IDL.Record({
to: User,
token: TokenIdentifier,
notify: IDL.Bool,
from: User,
memo: Memo,
subaccount: IDL.Opt(SubAccount),
amount: Balance,
fee: Fee,
});
const TransferRequest = TransferRequest_2;
const Result = IDL.Variant({
ok: Balance,
err: IDL.Variant({
CannotNotify: AccountIdentifier,
InsufficientBalance: IDL.Null,
InvalidToken: TokenIdentifier,
Rejected: IDL.Null,
Unauthorized: AccountIdentifier,
Other: IDL.Text,
}),
});
const TransferResponse_2 = Result;
const TransferResponse = TransferResponse_2;
const erc721_token = IDL.Service({
acceptCycles: IDL.Func([], [], []),
addRefund: IDL.Func(
[IDL.Text, IDL.Principal, SubAccount_3],
[],
['oneway']
),
availableCycles: IDL.Func([], [IDL.Nat], ['query']),
backendRefundSettlement: IDL.Func(
[IDL.Text],
[
IDL.Vec(IDL.Tuple(TokenIndex, Settlement)),
IDL.Vec(IDL.Tuple(AccountIdentifier_3, IDL.Principal, SubAccount_3)),
IDL.Vec(IDL.Tuple(IDL.Principal, IDL.Vec(SubAccount_3))),
IDL.Vec(IDL.Tuple(IDL.Principal, IDL.Vec(SubAccount_3))),
],
['query']
),
backup: IDL.Func(
[],
[
IDL.Vec(IDL.Tuple(TokenIndex, AccountIdentifier_3)),
IDL.Vec(IDL.Tuple(AccountIdentifier_3, IDL.Vec(TokenIndex))),
IDL.Vec(IDL.Tuple(TokenIndex, Metadata)),
],
['query']
),
balance: IDL.Func([BalanceRequest], [BalanceResponse], ['query']),
bearer: IDL.Func([TokenIdentifier_2], [Result_6], ['query']),
details: IDL.Func([TokenIdentifier_2], [Result_8], ['query']),
disribute: IDL.Func([User_2], [], []),
extensions: IDL.Func([], [IDL.Vec(Extension)], ['query']),
freeGift: IDL.Func([AccountIdentifier_3], [IDL.Opt(TokenIndex)], []),
getAllPayments: IDL.Func(
[],
[IDL.Vec(IDL.Tuple(IDL.Principal, IDL.Vec(SubAccount_3)))],
['query']
),
getBuyers: IDL.Func(
[],
[IDL.Vec(IDL.Tuple(AccountIdentifier_3, IDL.Vec(TokenIndex)))],
['query']
),
getMinted: IDL.Func([], [TokenIndex], ['query']),
getMinter: IDL.Func([], [IDL.Principal], ['query']),
getRegistry: IDL.Func(
[],
[IDL.Vec(IDL.Tuple(TokenIndex, AccountIdentifier_3))],
['query']
),
getSold: IDL.Func([], [TokenIndex], ['query']),
getTokens: IDL.Func(
[],
[IDL.Vec(IDL.Tuple(TokenIndex, Metadata))],
['query']
),
http_request: IDL.Func([HttpRequest], [HttpResponse], ['query']),
index: IDL.Func([TokenIdentifier_2], [Result_7], ['query']),
list: IDL.Func([ListRequest], [Result_4], []),
listings: IDL.Func(
[],
[IDL.Vec(IDL.Tuple(TokenIndex, Listing, Metadata))],
['query']
),
lock: IDL.Func(
[TokenIdentifier_2, IDL.Nat64, AccountIdentifier_3, SubAccount_3],
[Result_6],
[]
),
metadata: IDL.Func([TokenIdentifier_2], [Result_5], ['query']),
mintNFT: IDL.Func([MintRequest], [TokenIndex], []),
payments: IDL.Func([], [IDL.Opt(IDL.Vec(SubAccount_3))], ['query']),
refunds: IDL.Func([], [IDL.Opt(IDL.Vec(SubAccount_3))], ['query']),
removePayments: IDL.Func([IDL.Vec(SubAccount_3)], [], []),
removeRefunds: IDL.Func([IDL.Vec(SubAccount_3)], [], []),
setMinter: IDL.Func([IDL.Principal], [], []),
settle: IDL.Func([TokenIdentifier_2], [Result_4], []),
settle_force: IDL.Func([IDL.Text, TokenIdentifier_2], [], ['oneway']),
settlements: IDL.Func(
[],
[IDL.Vec(IDL.Tuple(TokenIndex, AccountIdentifier_3, IDL.Nat64))],
['query']
),
supply: IDL.Func([TokenIdentifier_2], [Result_3], ['query']),
tokens: IDL.Func([AccountIdentifier_3], [Result_2], ['query']),
transactions: IDL.Func([], [IDL.Vec(Transaction2)], ['query']),
transfer: IDL.Func([TransferRequest], [TransferResponse], []),
});
return erc721_token;
};
export const init = () => {
return [];
};
|
89e40ea2b5633d051536f49f82d26b4a0b2bd716 | 1,745 | ts | TypeScript | src/components/common/humanize/utils.ts | Lansweeper-public/NameChecker | 01780e3e35e6303d25386a555d45524e69f78ae7 | [
"MIT"
] | 1 | 2022-03-10T10:55:52.000Z | 2022-03-10T10:55:52.000Z | src/components/common/humanize/utils.ts | Lansweeper-public/NameChecker | 01780e3e35e6303d25386a555d45524e69f78ae7 | [
"MIT"
] | 13 | 2022-03-07T11:57:54.000Z | 2022-03-14T16:06:32.000Z | src/components/common/humanize/utils.ts | Lansweeper-public/NameChecker | 01780e3e35e6303d25386a555d45524e69f78ae7 | [
"MIT"
] | null | null | null | export const capitalize = (value: string, downCaseTail = false): string => {
return `${value.charAt(0).toUpperCase()}${
downCaseTail ? value.slice(1).toLowerCase() : value.slice(1)
}`;
};
export const capitalizeAll = (value: string): string => {
return value.replace(/(?:^|\s)\S/g, (a) => a.toUpperCase());
};
export const titleCase = (value: string, exceptions?: string[]): string => {
return doTitleCase(value, exceptions);
};
const doTitleCase = (
value: string,
exceptions?: string[],
hyphenated = false,
firstOrLast = true,
) => {
let smallWords =
/\b(a|an|and|at|but|by|de|en|for|if|in|of|on|or|the|to|via|vs?\.?)\b/i;
if (exceptions) {
smallWords = new RegExp(`\\b(${exceptions.join("||")}?\\.?)\\b`, "gi");
}
const internalCaps = /\S+[A-Z]+\S*/;
const splitOnWhiteSpaceRegex = /\s+/;
const splitOnHyphensRegex = /-/;
const titleCasedArray: string[] = [];
const stringArray = value.split(
hyphenated ? splitOnHyphensRegex : splitOnWhiteSpaceRegex,
);
stringArray.forEach((word, index) => {
if (word.indexOf("-") !== -1) {
titleCasedArray.push(
doTitleCase(
word,
exceptions,
true,
index === 0 || index === stringArray.length - 1,
),
);
} else if (
firstOrLast &&
(index === 0 || index === stringArray.length - 1)
) {
titleCasedArray.push(internalCaps.test(word) ? word : capitalize(word));
} else if (internalCaps.test(word)) {
titleCasedArray.push(word);
} else if (smallWords.test(word)) {
titleCasedArray.push(word.toLowerCase());
} else {
titleCasedArray.push(capitalize(word));
}
});
return titleCasedArray.join(hyphenated ? "-" : " ");
};
| 29.083333 | 78 | 0.597708 | 54 | 6 | 0 | 12 | 10 | 0 | 2 | 0 | 10 | 0 | 0 | 10.5 | 525 | 0.034286 | 0.019048 | 0 | 0 | 0 | 0 | 0.357143 | 0.312584 | export /* Example usages of 'capitalize' are shown below:
titleCasedArray.push(internalCaps.test(word) ? word : capitalize(word));
titleCasedArray.push(capitalize(word));
*/
const capitalize = (value, downCaseTail = false) => {
return `${value.charAt(0).toUpperCase()}${
downCaseTail ? value.slice(1).toLowerCase() : value.slice(1)
}`;
};
export const capitalizeAll = (value) => {
return value.replace(/(?:^|\s)\S/g, (a) => a.toUpperCase());
};
export const titleCase = (value, exceptions?) => {
return doTitleCase(value, exceptions);
};
/* Example usages of 'doTitleCase' are shown below:
doTitleCase(value, exceptions);
titleCasedArray.push(doTitleCase(word, exceptions, true, index === 0 || index === stringArray.length - 1));
*/
const doTitleCase = (
value,
exceptions?,
hyphenated = false,
firstOrLast = true,
) => {
let smallWords =
/\b(a|an|and|at|but|by|de|en|for|if|in|of|on|or|the|to|via|vs?\.?)\b/i;
if (exceptions) {
smallWords = new RegExp(`\\b(${exceptions.join("||")}?\\.?)\\b`, "gi");
}
const internalCaps = /\S+[A-Z]+\S*/;
const splitOnWhiteSpaceRegex = /\s+/;
const splitOnHyphensRegex = /-/;
const titleCasedArray = [];
const stringArray = value.split(
hyphenated ? splitOnHyphensRegex : splitOnWhiteSpaceRegex,
);
stringArray.forEach((word, index) => {
if (word.indexOf("-") !== -1) {
titleCasedArray.push(
doTitleCase(
word,
exceptions,
true,
index === 0 || index === stringArray.length - 1,
),
);
} else if (
firstOrLast &&
(index === 0 || index === stringArray.length - 1)
) {
titleCasedArray.push(internalCaps.test(word) ? word : capitalize(word));
} else if (internalCaps.test(word)) {
titleCasedArray.push(word);
} else if (smallWords.test(word)) {
titleCasedArray.push(word.toLowerCase());
} else {
titleCasedArray.push(capitalize(word));
}
});
return titleCasedArray.join(hyphenated ? "-" : " ");
};
|
872c5f267c59523bc3508e17ba4ae6029b87d8fc | 3,564 | ts | TypeScript | src/languageservice/utils/json.ts | msivasubramaniaan/yaml-language-server | eae5206655503a59023abed1713f4623ea1bd93d | [
"MIT"
] | 1 | 2022-03-14T14:11:42.000Z | 2022-03-14T14:11:42.000Z | src/languageservice/utils/json.ts | Jalalhejazi/yaml-language-server | 1f5c37b4c01673593cc897246e599c9d54c187c7 | [
"MIT"
] | null | null | null | src/languageservice/utils/json.ts | Jalalhejazi/yaml-language-server | 1f5c37b4c01673593cc897246e599c9d54c187c7 | [
"MIT"
] | null | null | null | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
export interface StringifySettings {
newLineFirst: boolean;
indentFirstObject: boolean;
shouldIndentWithTab: boolean;
}
interface StringifySettingsInternal extends StringifySettings {
indentation: string;
}
export function stringifyObject(
obj: unknown,
indent: string,
stringifyLiteral: (val: unknown) => string,
settings: StringifySettingsInternal,
depth = 0,
consecutiveArrays = 0
): string {
if (obj !== null && typeof obj === 'object') {
/**
* When we are autocompleting a snippet from a property we need the indent so everything underneath the property
* is propertly indented. When we are auto completion from a value we don't want the indent because the cursor
* is already in the correct place
*/
const newIndent = (depth === 0 && settings.shouldIndentWithTab) || depth > 0 ? indent + settings.indentation : '';
if (Array.isArray(obj)) {
consecutiveArrays += 1;
if (obj.length === 0) {
return '';
}
let result = '';
for (let i = 0; i < obj.length; i++) {
let pseudoObj = obj[i];
if (typeof obj[i] !== 'object') {
result += '\n' + newIndent + '- ' + stringifyLiteral(obj[i]);
continue;
}
if (!Array.isArray(obj[i])) {
pseudoObj = prependToObject(obj[i], consecutiveArrays);
}
result += stringifyObject(pseudoObj, indent, stringifyLiteral, settings, (depth += 1), consecutiveArrays);
}
return result;
} else {
const keys = Object.keys(obj);
if (keys.length === 0) {
return '';
}
let result = (depth === 0 && settings.newLineFirst) || depth > 0 ? '\n' : '';
for (let i = 0; i < keys.length; i++) {
const key = keys[i];
const isObject = typeof obj[key] === 'object';
const colonDelimiter = isObject ? ':' : ': '; // add space only when value is primitive
const parentArrayCompensation = isObject && /^\s|-/.test(key) ? settings.indentation : ''; // add extra space if parent is an array
const objectIndent = newIndent + parentArrayCompensation;
// The first child of an array needs to be treated specially, otherwise identations will be off
if (depth === 0 && i === 0 && !settings.indentFirstObject) {
const value = stringifyObject(obj[key], objectIndent, stringifyLiteral, settings, (depth += 1), 0);
result += indent + key + colonDelimiter + value;
} else {
const value = stringifyObject(obj[key], objectIndent, stringifyLiteral, settings, (depth += 1), 0);
result += newIndent + key + colonDelimiter + value;
}
if (i < keys.length - 1) {
result += '\n';
}
}
return result;
}
}
return stringifyLiteral(obj);
}
function prependToObject(obj: Record<string, unknown>, consecutiveArrays: number): Record<string, unknown> {
const newObj = {};
for (let i = 0; i < Object.keys(obj).length; i++) {
const key = Object.keys(obj)[i];
if (i === 0) {
newObj['- '.repeat(consecutiveArrays) + key] = obj[key];
} else {
newObj[' '.repeat(consecutiveArrays) + key] = obj[key];
}
}
return newObj;
}
| 38.73913 | 139 | 0.577441 | 76 | 2 | 0 | 8 | 17 | 4 | 2 | 0 | 14 | 2 | 3 | 28.5 | 871 | 0.011481 | 0.019518 | 0.004592 | 0.002296 | 0.003444 | 0 | 0.451613 | 0.263887 | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
export interface StringifySettings {
newLineFirst;
indentFirstObject;
shouldIndentWithTab;
}
interface StringifySettingsInternal extends StringifySettings {
indentation;
}
export /* Example usages of 'stringifyObject' are shown below:
result += stringifyObject(pseudoObj, indent, stringifyLiteral, settings, (depth += 1), consecutiveArrays);
stringifyObject(obj[key], objectIndent, stringifyLiteral, settings, (depth += 1), 0);
*/
function stringifyObject(
obj,
indent,
stringifyLiteral,
settings,
depth = 0,
consecutiveArrays = 0
) {
if (obj !== null && typeof obj === 'object') {
/**
* When we are autocompleting a snippet from a property we need the indent so everything underneath the property
* is propertly indented. When we are auto completion from a value we don't want the indent because the cursor
* is already in the correct place
*/
const newIndent = (depth === 0 && settings.shouldIndentWithTab) || depth > 0 ? indent + settings.indentation : '';
if (Array.isArray(obj)) {
consecutiveArrays += 1;
if (obj.length === 0) {
return '';
}
let result = '';
for (let i = 0; i < obj.length; i++) {
let pseudoObj = obj[i];
if (typeof obj[i] !== 'object') {
result += '\n' + newIndent + '- ' + stringifyLiteral(obj[i]);
continue;
}
if (!Array.isArray(obj[i])) {
pseudoObj = prependToObject(obj[i], consecutiveArrays);
}
result += stringifyObject(pseudoObj, indent, stringifyLiteral, settings, (depth += 1), consecutiveArrays);
}
return result;
} else {
const keys = Object.keys(obj);
if (keys.length === 0) {
return '';
}
let result = (depth === 0 && settings.newLineFirst) || depth > 0 ? '\n' : '';
for (let i = 0; i < keys.length; i++) {
const key = keys[i];
const isObject = typeof obj[key] === 'object';
const colonDelimiter = isObject ? ':' : ': '; // add space only when value is primitive
const parentArrayCompensation = isObject && /^\s|-/.test(key) ? settings.indentation : ''; // add extra space if parent is an array
const objectIndent = newIndent + parentArrayCompensation;
// The first child of an array needs to be treated specially, otherwise identations will be off
if (depth === 0 && i === 0 && !settings.indentFirstObject) {
const value = stringifyObject(obj[key], objectIndent, stringifyLiteral, settings, (depth += 1), 0);
result += indent + key + colonDelimiter + value;
} else {
const value = stringifyObject(obj[key], objectIndent, stringifyLiteral, settings, (depth += 1), 0);
result += newIndent + key + colonDelimiter + value;
}
if (i < keys.length - 1) {
result += '\n';
}
}
return result;
}
}
return stringifyLiteral(obj);
}
/* Example usages of 'prependToObject' are shown below:
pseudoObj = prependToObject(obj[i], consecutiveArrays);
*/
function prependToObject(obj, consecutiveArrays) {
const newObj = {};
for (let i = 0; i < Object.keys(obj).length; i++) {
const key = Object.keys(obj)[i];
if (i === 0) {
newObj['- '.repeat(consecutiveArrays) + key] = obj[key];
} else {
newObj[' '.repeat(consecutiveArrays) + key] = obj[key];
}
}
return newObj;
}
|
8754c697fdf9ce5ff66f7c342b41dc1c6e870d7e | 2,234 | ts | TypeScript | src/utils/type/getTypeInfoForTypeName.ts | backk-node/backk | 01ac30c22df82a7569cc5bf363e8c6cd9669eea9 | [
"MIT"
] | 22 | 2022-01-14T12:06:57.000Z | 2022-03-25T02:39:15.000Z | src/utils/type/getTypeInfoForTypeName.ts | backk-node/backk | 01ac30c22df82a7569cc5bf363e8c6cd9669eea9 | [
"MIT"
] | null | null | null | src/utils/type/getTypeInfoForTypeName.ts | backk-node/backk | 01ac30c22df82a7569cc5bf363e8c6cd9669eea9 | [
"MIT"
] | 2 | 2022-01-21T12:30:52.000Z | 2022-03-11T15:34:25.000Z | // noinspection OverlyComplexFunctionJS,FunctionTooLongJS
export default function getTypeInfoForTypeName(typeName: string) {
let canBeError = false;
if (typeName.startsWith('PromiseErrorOr<')) {
canBeError = true;
// noinspection AssignmentToFunctionParameterJS
typeName = typeName.slice(15, -1);
}
let isManyOf = false;
let isArrayType = false;
if (typeName.startsWith('Many<')) {
canBeError = true;
isManyOf = true;
isArrayType = true;
// noinspection AssignmentToFunctionParameterJS
typeName = typeName.slice(5, -1);
}
let isOneOf = false;
if (typeName.startsWith('One<')) {
canBeError = true;
isOneOf = true;
// noinspection AssignmentToFunctionParameterJS
typeName = typeName.slice(4, -1);
}
const isOptionalType = typeName.startsWith('?');
// noinspection AssignmentToFunctionParameterJS
typeName = isOptionalType ? typeName.slice(1) : typeName;
if (typeName.startsWith('(') && typeName.endsWith(')') && typeName.includes(' | null')) {
// noinspection AssignmentToFunctionParameterJS
typeName = typeName.slice(1, -1);
}
let defaultValueStr;
[typeName, defaultValueStr] = typeName.split(' = ');
if (typeName.endsWith('[]')) {
isArrayType = true;
// noinspection AssignmentToFunctionParameterJS
typeName = typeName.slice(0, -2);
} else if (typeName.startsWith('Array<')) {
isArrayType = true;
// noinspection AssignmentToFunctionParameterJS
typeName = typeName.slice(6, -1);
}
let isNullableType = false;
if (typeName.endsWith(' | null')) {
isNullableType = true;
// noinspection AssignmentToFunctionParameterJS
typeName = typeName.split(' | null')[0];
}
if (typeName.endsWith('[]') || typeName.startsWith('Array<')) {
if (isNullableType) {
throw new Error(
'Array type union with null type is not allowed, use empty array to denote a missing value.'
);
} else if (isArrayType) {
throw new Error('Multi-dimensional types not allowed');
}
}
return {
baseTypeName: typeName,
isNull: typeName === 'null',
canBeError,
defaultValueStr,
isArrayType,
isNullableType,
isOptionalType,
isManyOf,
isOneOf
};
}
| 27.580247 | 100 | 0.672784 | 60 | 1 | 0 | 1 | 7 | 0 | 0 | 0 | 1 | 0 | 0 | 58 | 558 | 0.003584 | 0.012545 | 0 | 0 | 0 | 0 | 0.111111 | 0.219489 | // noinspection OverlyComplexFunctionJS,FunctionTooLongJS
export default function getTypeInfoForTypeName(typeName) {
let canBeError = false;
if (typeName.startsWith('PromiseErrorOr<')) {
canBeError = true;
// noinspection AssignmentToFunctionParameterJS
typeName = typeName.slice(15, -1);
}
let isManyOf = false;
let isArrayType = false;
if (typeName.startsWith('Many<')) {
canBeError = true;
isManyOf = true;
isArrayType = true;
// noinspection AssignmentToFunctionParameterJS
typeName = typeName.slice(5, -1);
}
let isOneOf = false;
if (typeName.startsWith('One<')) {
canBeError = true;
isOneOf = true;
// noinspection AssignmentToFunctionParameterJS
typeName = typeName.slice(4, -1);
}
const isOptionalType = typeName.startsWith('?');
// noinspection AssignmentToFunctionParameterJS
typeName = isOptionalType ? typeName.slice(1) : typeName;
if (typeName.startsWith('(') && typeName.endsWith(')') && typeName.includes(' | null')) {
// noinspection AssignmentToFunctionParameterJS
typeName = typeName.slice(1, -1);
}
let defaultValueStr;
[typeName, defaultValueStr] = typeName.split(' = ');
if (typeName.endsWith('[]')) {
isArrayType = true;
// noinspection AssignmentToFunctionParameterJS
typeName = typeName.slice(0, -2);
} else if (typeName.startsWith('Array<')) {
isArrayType = true;
// noinspection AssignmentToFunctionParameterJS
typeName = typeName.slice(6, -1);
}
let isNullableType = false;
if (typeName.endsWith(' | null')) {
isNullableType = true;
// noinspection AssignmentToFunctionParameterJS
typeName = typeName.split(' | null')[0];
}
if (typeName.endsWith('[]') || typeName.startsWith('Array<')) {
if (isNullableType) {
throw new Error(
'Array type union with null type is not allowed, use empty array to denote a missing value.'
);
} else if (isArrayType) {
throw new Error('Multi-dimensional types not allowed');
}
}
return {
baseTypeName: typeName,
isNull: typeName === 'null',
canBeError,
defaultValueStr,
isArrayType,
isNullableType,
isOptionalType,
isManyOf,
isOneOf
};
}
|
87c2fd1a14baf39bec10e9b71840b1c10af0c114 | 1,715 | ts | TypeScript | src/utils/mime/mimeMapping.ts | enevtihq/enevti-app | cdf81db8b84845ef2f0f56939e1271a0dd03f1d4 | [
"Apache-2.0"
] | 1 | 2022-01-16T21:08:08.000Z | 2022-01-16T21:08:08.000Z | src/utils/mime/mimeMapping.ts | enevtihq/enevti-app | cdf81db8b84845ef2f0f56939e1271a0dd03f1d4 | [
"Apache-2.0"
] | null | null | null | src/utils/mime/mimeMapping.ts | enevtihq/enevti-app | cdf81db8b84845ef2f0f56939e1271a0dd03f1d4 | [
"Apache-2.0"
] | null | null | null | const typeMapping = {
image: /^image\//,
audio: /^audio\//,
video: /^video\//,
document: [
'application/pdf',
/ms-?word/,
'application/vnd.oasis.opendocument.text',
'application/vnd.openxmlformats-officedocument.wordprocessingml.document',
'application/vnd.openxmlformats-officedocument.wordprocessingml',
/ms-?excel/,
'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
'application/vnd.openxmlformats-officedocument.spreadsheetml',
'application/vnd.oasis.opendocument.spreadsheet',
/ms-?powerpoint/,
'application/vnd.openxmlformats-officedocument.presentationml.presentation',
'application/vnd.openxmlformats-officedocument.presentationml',
'application/vnd.oasis.opendocument.presentation',
],
file: 'text/plain',
code: ['text/html', 'text/javascript', 'application/json'],
archive: [
/^application\/x-(g?tar|xz|compress|bzip2|g?zip)$/,
/^application\/x-(7z|rar|zip)-compressed$/,
/^application\/(zip|gzip|tar)$/,
],
};
function match(mime: string, cond: string | (RegExp | string)[] | RegExp | undefined): boolean {
if (Array.isArray(cond)) {
for (let i = 0; i < cond.length; i++) {
if (match(mime, cond[i])) {
return true;
}
}
return false;
} else if (cond instanceof RegExp) {
return cond.test(mime);
} else if (cond === undefined) {
return true;
} else {
return mime === cond;
}
}
export default function mimeMapping(mime: string): keyof typeof typeMapping | 'undefined' {
for (const [type, condition] of Object.entries(typeMapping)) {
if (match(mime, condition)) {
return type as keyof typeof typeMapping;
}
}
return 'undefined';
}
| 31.759259 | 96 | 0.667638 | 51 | 2 | 0 | 3 | 2 | 0 | 1 | 0 | 5 | 0 | 2 | 10 | 475 | 0.010526 | 0.004211 | 0 | 0 | 0.004211 | 0 | 0.714286 | 0.207125 | const typeMapping = {
image: /^image\//,
audio: /^audio\//,
video: /^video\//,
document: [
'application/pdf',
/ms-?word/,
'application/vnd.oasis.opendocument.text',
'application/vnd.openxmlformats-officedocument.wordprocessingml.document',
'application/vnd.openxmlformats-officedocument.wordprocessingml',
/ms-?excel/,
'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
'application/vnd.openxmlformats-officedocument.spreadsheetml',
'application/vnd.oasis.opendocument.spreadsheet',
/ms-?powerpoint/,
'application/vnd.openxmlformats-officedocument.presentationml.presentation',
'application/vnd.openxmlformats-officedocument.presentationml',
'application/vnd.oasis.opendocument.presentation',
],
file: 'text/plain',
code: ['text/html', 'text/javascript', 'application/json'],
archive: [
/^application\/x-(g?tar|xz|compress|bzip2|g?zip)$/,
/^application\/x-(7z|rar|zip)-compressed$/,
/^application\/(zip|gzip|tar)$/,
],
};
/* Example usages of 'match' are shown below:
match(mime, cond[i]);
match(mime, condition);
*/
function match(mime, cond) {
if (Array.isArray(cond)) {
for (let i = 0; i < cond.length; i++) {
if (match(mime, cond[i])) {
return true;
}
}
return false;
} else if (cond instanceof RegExp) {
return cond.test(mime);
} else if (cond === undefined) {
return true;
} else {
return mime === cond;
}
}
export default function mimeMapping(mime) {
for (const [type, condition] of Object.entries(typeMapping)) {
if (match(mime, condition)) {
return type as keyof typeof typeMapping;
}
}
return 'undefined';
}
|
87c45d173a88a8085fea7c65e036d9547bec5542 | 2,531 | ts | TypeScript | src/comparators.ts | react-hookz/deep-equal | 06c150ceb8b982930397f55cc722ec35a238fd98 | [
"MIT"
] | 3 | 2022-01-18T11:52:10.000Z | 2022-03-28T10:21:00.000Z | src/comparators.ts | react-hookz/deep-equal | 06c150ceb8b982930397f55cc722ec35a238fd98 | [
"MIT"
] | 30 | 2022-01-12T17:26:26.000Z | 2022-03-30T00:37:34.000Z | src/comparators.ts | react-hookz/deep-equal | 06c150ceb8b982930397f55cc722ec35a238fd98 | [
"MIT"
] | 1 | 2022-01-14T11:42:57.000Z | 2022-01-14T11:42:57.000Z | /* eslint-disable @typescript-eslint/no-explicit-any,no-cond-assign,no-restricted-syntax,no-continue */
type EqualFn = (a: any, b: any) => boolean;
export const compareDates = (a: Date, b: Date): boolean => a.getTime() === b.getTime();
export const compareRegexps = (a: RegExp, b: RegExp): boolean =>
a.source === b.source && a.flags === b.flags;
export const compareArrays = (a: any[], b: any[], equal: EqualFn): boolean => {
let l = a.length;
if (l !== b.length) return false;
while (l-- && equal(a[l], b[l]));
return l === -1;
};
export const compareMaps = (a: Map<any, any>, b: Map<any, any>, equal: EqualFn): boolean => {
if (a.size !== b.size) return false;
const it = a.entries();
let i: any;
while (!(i = it.next()).done) {
if (!b.has(i.value[0]) || !equal(i.value[1], b.get(i.value[0]))) return false;
}
return true;
};
export const compareSets = (a: Set<any>, b: Set<any>): boolean => {
if (a.size !== b.size) return false;
const it = a.values();
let i: any;
while (!(i = it.next()).done) {
if (!b.has(i.value)) return false;
}
return true;
};
export const compareDataViews = (a: DataView, b: DataView): boolean => {
let l = a.byteLength;
if (l !== b.byteLength) return false;
while (l-- && a.getInt8(l) === b.getInt8(l));
return l === -1;
};
export const compareArrayBuffers = (a: ArrayLike<any>, b: ArrayLike<any>): boolean => {
let l = a.length;
if (l !== b.length) return false;
while (l-- && a[l] === b[l]);
return l === -1;
};
const { hasOwnProperty } = Object.prototype;
const oKeys = Object.keys;
export const compareObjects = (
a: Record<any, any>,
b: Record<any, any>,
equal: EqualFn
): boolean => {
let i;
let len = 0;
for (i in a) {
if (hasOwnProperty.call(a, i)) {
len++;
if (!hasOwnProperty.call(b, i)) return false;
if (!equal(a[i], b[i])) return false;
}
}
return oKeys(b).length === len;
};
export const compareObjectsReact = (
a: Record<any, any>,
b: Record<any, any>,
equal: EqualFn
): boolean => {
let i;
let len = 0;
for (i in a) {
if (hasOwnProperty.call(a, i)) {
len++;
if (a.$$typeof && (i === '_owner' || i === '__v' || i === '__o')) {
// in React and Preact these properties contain circular references
// .$$typeof is just reasonable marker of element
continue;
}
if (!hasOwnProperty.call(b, i)) return false;
if (!equal(a[i], b[i])) return false;
}
}
return oKeys(b).length === len;
};
| 23.009091 | 103 | 0.575267 | 77 | 9 | 0 | 22 | 22 | 0 | 0 | 22 | 10 | 1 | 0 | 5.666667 | 833 | 0.037215 | 0.026411 | 0 | 0.0012 | 0 | 0.415094 | 0.188679 | 0.338522 | /* eslint-disable @typescript-eslint/no-explicit-any,no-cond-assign,no-restricted-syntax,no-continue */
type EqualFn = (a, b) => boolean;
export const compareDates = (a, b) => a.getTime() === b.getTime();
export const compareRegexps = (a, b) =>
a.source === b.source && a.flags === b.flags;
export const compareArrays = (a, b, equal) => {
let l = a.length;
if (l !== b.length) return false;
while (l-- && equal(a[l], b[l]));
return l === -1;
};
export const compareMaps = (a, b, equal) => {
if (a.size !== b.size) return false;
const it = a.entries();
let i;
while (!(i = it.next()).done) {
if (!b.has(i.value[0]) || !equal(i.value[1], b.get(i.value[0]))) return false;
}
return true;
};
export const compareSets = (a, b) => {
if (a.size !== b.size) return false;
const it = a.values();
let i;
while (!(i = it.next()).done) {
if (!b.has(i.value)) return false;
}
return true;
};
export const compareDataViews = (a, b) => {
let l = a.byteLength;
if (l !== b.byteLength) return false;
while (l-- && a.getInt8(l) === b.getInt8(l));
return l === -1;
};
export const compareArrayBuffers = (a, b) => {
let l = a.length;
if (l !== b.length) return false;
while (l-- && a[l] === b[l]);
return l === -1;
};
const { hasOwnProperty } = Object.prototype;
const oKeys = Object.keys;
export const compareObjects = (
a,
b,
equal
) => {
let i;
let len = 0;
for (i in a) {
if (hasOwnProperty.call(a, i)) {
len++;
if (!hasOwnProperty.call(b, i)) return false;
if (!equal(a[i], b[i])) return false;
}
}
return oKeys(b).length === len;
};
export const compareObjectsReact = (
a,
b,
equal
) => {
let i;
let len = 0;
for (i in a) {
if (hasOwnProperty.call(a, i)) {
len++;
if (a.$$typeof && (i === '_owner' || i === '__v' || i === '__o')) {
// in React and Preact these properties contain circular references
// .$$typeof is just reasonable marker of element
continue;
}
if (!hasOwnProperty.call(b, i)) return false;
if (!equal(a[i], b[i])) return false;
}
}
return oKeys(b).length === len;
};
|
9b43716649831a6b0a5fff85e210dfc54b96687f | 2,757 | ts | TypeScript | src/web/commands/utils/meta-data.ts | rodydavis/vscode-router-generator | 03ed8f0c4bb47b5903acd315e97b2a2aa964c40b | [
"Apache-2.0"
] | 12 | 2022-01-14T07:07:06.000Z | 2022-01-23T06:18:11.000Z | src/web/utils/meta-data.ts | rodydavis/vscode-dynamic-theme | b0bf235acdecf483234501fb804b3a078de12675 | [
"Apache-2.0"
] | 1 | 2022-01-23T10:48:28.000Z | 2022-02-01T20:30:22.000Z | src/web/utils/meta-data.ts | rodydavis/vscode-dynamic-theme | b0bf235acdecf483234501fb804b3a078de12675 | [
"Apache-2.0"
] | 1 | 2022-01-23T10:50:36.000Z | 2022-01-23T10:50:36.000Z | export function convertComponents<T extends Component>(components: T[]) {
for (let i = 0; i < components.length; i++) {
const component = components[i];
const args: string[] = [];
for (const part of component.route.split("/")) {
if (part.startsWith(":")) {
args.push(part.slice(1));
}
}
component.route = component.route.toLowerCase();
component.args = args;
// Remove extension
const file = component.path;
let idx = file.length - 1;
while (file[idx] !== ".") {
idx--;
}
const ext = file.slice(idx + 1, file.length);
let relativePath = component.path.split("pages")[1];
relativePath = relativePath.replace(`.${ext}`, "");
component.ext = ext;
component.alias = `route${i}`;
component.relativePath = "pages" + relativePath;
const route = `${component.route}`;
if (route === "") {
continue;
}
let parentRoute: string | undefined;
if (route.endsWith("/")) {
parentRoute = route.slice(0, -1);
} else {
let implicitIndex = false;
const implicitRoute = route + "/";
for (const c of components) {
if (c.route === implicitRoute) {
implicitIndex = true;
break;
}
}
component.implicitIndex = implicitIndex;
// /settings/admin --> /settings --> ""
// /settings/ --> /settings --> ""
// /settings --> ""
parentRoute = route.split("/").slice(0, -1).join("/");
}
const hasParentRoute = components.find((c) => c.route === parentRoute);
if (hasParentRoute !== undefined && parentRoute !== "/") {
component.parentRoute = parentRoute;
} else if (parentRoute === "/") {
const rootComponent = components.find((c) => c.route === "");
if (rootComponent) {
component.parentRoute = "";
}
}
}
return components
.sort((a, b) => {
if (a.route < b.route) {
return -1;
}
if (a.route > b.route) {
return 1;
}
return 0;
})
.reverse();
}
export function getComponentTree<T extends Component>(
component: T,
components: T[]
) {
const tree: T[] = [component];
while (component.parentRoute) {
const parent = components.find((c) => c.route === component.parentRoute);
if (parent) {
tree.push(parent);
component = parent;
} else {
break;
}
}
// Add root
const root = components.find((c) => c.route === "");
if (root && root !== component) {
tree.push(root);
}
return tree.reverse();
}
export interface Component {
route: string;
name: string;
path: string;
ext?: string;
relativePath?: string;
alias?: string;
implicitIndex?: boolean;
parentRoute?: string;
args: string[];
}
| 26.009434 | 77 | 0.560754 | 94 | 7 | 0 | 9 | 16 | 9 | 0 | 0 | 11 | 1 | 0 | 12.428571 | 719 | 0.022253 | 0.022253 | 0.012517 | 0.001391 | 0 | 0 | 0.268293 | 0.296748 | export function convertComponents<T extends Component>(components) {
for (let i = 0; i < components.length; i++) {
const component = components[i];
const args = [];
for (const part of component.route.split("/")) {
if (part.startsWith(":")) {
args.push(part.slice(1));
}
}
component.route = component.route.toLowerCase();
component.args = args;
// Remove extension
const file = component.path;
let idx = file.length - 1;
while (file[idx] !== ".") {
idx--;
}
const ext = file.slice(idx + 1, file.length);
let relativePath = component.path.split("pages")[1];
relativePath = relativePath.replace(`.${ext}`, "");
component.ext = ext;
component.alias = `route${i}`;
component.relativePath = "pages" + relativePath;
const route = `${component.route}`;
if (route === "") {
continue;
}
let parentRoute;
if (route.endsWith("/")) {
parentRoute = route.slice(0, -1);
} else {
let implicitIndex = false;
const implicitRoute = route + "/";
for (const c of components) {
if (c.route === implicitRoute) {
implicitIndex = true;
break;
}
}
component.implicitIndex = implicitIndex;
// /settings/admin --> /settings --> ""
// /settings/ --> /settings --> ""
// /settings --> ""
parentRoute = route.split("/").slice(0, -1).join("/");
}
const hasParentRoute = components.find((c) => c.route === parentRoute);
if (hasParentRoute !== undefined && parentRoute !== "/") {
component.parentRoute = parentRoute;
} else if (parentRoute === "/") {
const rootComponent = components.find((c) => c.route === "");
if (rootComponent) {
component.parentRoute = "";
}
}
}
return components
.sort((a, b) => {
if (a.route < b.route) {
return -1;
}
if (a.route > b.route) {
return 1;
}
return 0;
})
.reverse();
}
export function getComponentTree<T extends Component>(
component,
components
) {
const tree = [component];
while (component.parentRoute) {
const parent = components.find((c) => c.route === component.parentRoute);
if (parent) {
tree.push(parent);
component = parent;
} else {
break;
}
}
// Add root
const root = components.find((c) => c.route === "");
if (root && root !== component) {
tree.push(root);
}
return tree.reverse();
}
export interface Component {
route;
name;
path;
ext?;
relativePath?;
alias?;
implicitIndex?;
parentRoute?;
args;
}
|
79351c246efcc616bee253e50d6482e71d07d840 | 1,586 | ts | TypeScript | fastcar-core/src/utils/DataFormat.ts | williamDazhangyu/fast-car | c485ab6637e29e8c49b00af6600e2ded2b9a0c57 | [
"MIT"
] | 4 | 2022-03-08T06:02:31.000Z | 2022-03-14T04:33:39.000Z | fastcar-core/src/utils/DataFormat.ts | williamDazhangyu/fast-car | c485ab6637e29e8c49b00af6600e2ded2b9a0c57 | [
"MIT"
] | null | null | null | fastcar-core/src/utils/DataFormat.ts | williamDazhangyu/fast-car | c485ab6637e29e8c49b00af6600e2ded2b9a0c57 | [
"MIT"
] | null | null | null | /***
* @version 1.0 数据格式处理
*/
class DataFormat {
static formatNumber(value: any, type: string): number | null {
if (type === "int") {
return parseInt(value);
}
if (type === "float" || type == "number") {
return parseFloat(value);
}
return null;
}
static formatString(value: any): string | null {
if (typeof value != "string") {
return null;
}
return value;
}
static formatBoolean(value: any): boolean {
if (typeof value == "string") {
if ((value = "false")) {
return false;
}
}
return !!value;
}
static formatArray(value: any[], type: string): any[] {
if (type.startsWith("array")) {
if (typeof value === "string") {
value = JSON.parse(value);
}
if (Array.isArray(value)) {
let ntype = type.replace(/array/, "");
value = value.map(item => {
return DataFormat.formatValue(item, ntype);
});
return value;
}
}
return [];
}
static formatDate(value: any): Date {
if (value instanceof Date) {
return value;
}
return new Date(value);
}
static formatValue(value: any, type: string): any {
if (type.startsWith("array")) {
return DataFormat.formatArray(value, type);
}
switch (type) {
case "string": {
return DataFormat.formatString(value);
}
case "boolean": {
return DataFormat.formatBoolean(value);
}
case "int":
case "float":
case "number": {
return DataFormat.formatNumber(value, type);
}
case "date": {
return DataFormat.formatDate(value);
}
default: {
return value;
}
}
}
}
export default DataFormat;
| 17.622222 | 63 | 0.594578 | 71 | 7 | 0 | 10 | 1 | 0 | 6 | 8 | 6 | 1 | 4 | 8.142857 | 522 | 0.032567 | 0.001916 | 0 | 0.001916 | 0.007663 | 0.444444 | 0.333333 | 0.248484 | /***
* @version 1.0 数据格式处理
*/
class DataFormat {
static formatNumber(value, type) {
if (type === "int") {
return parseInt(value);
}
if (type === "float" || type == "number") {
return parseFloat(value);
}
return null;
}
static formatString(value) {
if (typeof value != "string") {
return null;
}
return value;
}
static formatBoolean(value) {
if (typeof value == "string") {
if ((value = "false")) {
return false;
}
}
return !!value;
}
static formatArray(value, type) {
if (type.startsWith("array")) {
if (typeof value === "string") {
value = JSON.parse(value);
}
if (Array.isArray(value)) {
let ntype = type.replace(/array/, "");
value = value.map(item => {
return DataFormat.formatValue(item, ntype);
});
return value;
}
}
return [];
}
static formatDate(value) {
if (value instanceof Date) {
return value;
}
return new Date(value);
}
static formatValue(value, type) {
if (type.startsWith("array")) {
return DataFormat.formatArray(value, type);
}
switch (type) {
case "string": {
return DataFormat.formatString(value);
}
case "boolean": {
return DataFormat.formatBoolean(value);
}
case "int":
case "float":
case "number": {
return DataFormat.formatNumber(value, type);
}
case "date": {
return DataFormat.formatDate(value);
}
default: {
return value;
}
}
}
}
export default DataFormat;
|
e0adc0a947e9e83b8bc03219033fde3d085cbfad | 3,697 | ts | TypeScript | src/lib.ts | tomymolina/promise-bulk | 66a09555fcc06cadfd6a7761e59a0e2a5ca073e9 | [
"Apache-2.0"
] | 3 | 2022-01-06T01:16:00.000Z | 2022-03-28T12:44:51.000Z | src/lib.ts | tomymolina/promise-bulk | 66a09555fcc06cadfd6a7761e59a0e2a5ca073e9 | [
"Apache-2.0"
] | null | null | null | src/lib.ts | tomymolina/promise-bulk | 66a09555fcc06cadfd6a7761e59a0e2a5ca073e9 | [
"Apache-2.0"
] | null | null | null |
/**
* The **bulk function** receives and array of atomic inputs and returns and array of outputs processed in bulk mode.
* It is essential that this function works more effeciently with an array of items than doing the same operation individually.
* The response of this function is an array where the items must be placed in the same position than the input items.
* ```typescript
* //bulk operation
* mongodb.insertMany([obj1, obj2, obj3])
* //atomic operation
* Promise.all([
* mongodb.insertOne(obj1),
* mongodb.insertOne(obj2),
* mongodb.insertOne(obj3)
* ])
* ```
*
* @typeParam Input The input item type.
* @typeParam Output The output response type.
*/
export type ExecuteBulkFn<Input,Output> = (items: Input[]) => Promise<Output[]>
class PromiseBulkSingle<I,O> {
private _executionItemsPromise: Promise<O[]> = Promise.resolve([])
private _pendingItems = []
private _free = true
constructor(private readonly _executeBulk: ExecuteBulkFn<I,O>) {}
async execute(item: I) {
const newSize = this._pendingItems.push(item)
const myIndex = newSize - 1
if (this._free) {
this._free = false
const itemsToExecute = this._pendingItems
this._pendingItems = []
this._executionItemsPromise = this.executeBulk(itemsToExecute)
const executedItems = await this._executionItemsPromise
this._free = true
return executedItems[myIndex]
} else {
await this._executionItemsPromise
if (this._free) {
this._free = false
const itemsToExecute = this._pendingItems
this._pendingItems = []
this._executionItemsPromise = this.executeBulk(itemsToExecute)
const executionItems = await this._executionItemsPromise
this._free = true
return executionItems[myIndex]
} else {
const executedItems = await this._executionItemsPromise
return executedItems[myIndex]
}
}
}
executeBulk(items) {
if (!this._executeBulk) {
throw new Error('Execute bulk not implemented')
}
return this._executeBulk(items)
}
}
/**
* This is the main `promise-bulk` feature.
* This class allows to instantiate bulk processes.
*
* A bulk function is the only required constructor parameter.
*
* @typeParam Input The type of the input items to be processed by the bulk function.
*
* @typeParam Output The type of the response items of the bulk function.
*/
export class PromiseBulk<Input = unknown, Output = unknown> {
private _index = 0
private readonly _bulks: PromiseBulkSingle<Input,Output>[]
/**
*
* @param bulkFn Bulk function. Receives an array of imputs and returns an array of outputs.
* @param _concurrency Limit of concurrent calls to the bulk function.
*/
constructor(bulkFn: ExecuteBulkFn<Input,Output>, private readonly _concurrency = 1) {
this._index = 0
this._bulks = Array.from({length: _concurrency}, () => new PromiseBulkSingle(bulkFn))
}
/**
* Execute
*
* This function adds one item to the bulk process and waits for its response in a bulk operation.
* @param item Atomic input that will be included in a bulk process
* @returns The associated response to the input (will be returned from a bulk process)
*/
async execute(item: Input) {
const index = this._index
this._index = (this._index+1) % this._concurrency
return this._bulks[index].execute(item)
}
} | 33.306306 | 127 | 0.644577 | 53 | 6 | 0 | 6 | 8 | 5 | 2 | 0 | 2 | 3 | 0 | 5.833333 | 855 | 0.014035 | 0.009357 | 0.005848 | 0.003509 | 0 | 0 | 0.08 | 0.239504 |
/**
* The **bulk function** receives and array of atomic inputs and returns and array of outputs processed in bulk mode.
* It is essential that this function works more effeciently with an array of items than doing the same operation individually.
* The response of this function is an array where the items must be placed in the same position than the input items.
* ```typescript
* //bulk operation
* mongodb.insertMany([obj1, obj2, obj3])
* //atomic operation
* Promise.all([
* mongodb.insertOne(obj1),
* mongodb.insertOne(obj2),
* mongodb.insertOne(obj3)
* ])
* ```
*
* @typeParam Input The input item type.
* @typeParam Output The output response type.
*/
export type ExecuteBulkFn<Input,Output> = (items) => Promise<Output[]>
class PromiseBulkSingle<I,O> {
private _executionItemsPromise = Promise.resolve([])
private _pendingItems = []
private _free = true
constructor(private readonly _executeBulk) {}
async execute(item) {
const newSize = this._pendingItems.push(item)
const myIndex = newSize - 1
if (this._free) {
this._free = false
const itemsToExecute = this._pendingItems
this._pendingItems = []
this._executionItemsPromise = this.executeBulk(itemsToExecute)
const executedItems = await this._executionItemsPromise
this._free = true
return executedItems[myIndex]
} else {
await this._executionItemsPromise
if (this._free) {
this._free = false
const itemsToExecute = this._pendingItems
this._pendingItems = []
this._executionItemsPromise = this.executeBulk(itemsToExecute)
const executionItems = await this._executionItemsPromise
this._free = true
return executionItems[myIndex]
} else {
const executedItems = await this._executionItemsPromise
return executedItems[myIndex]
}
}
}
executeBulk(items) {
if (!this._executeBulk) {
throw new Error('Execute bulk not implemented')
}
return this._executeBulk(items)
}
}
/**
* This is the main `promise-bulk` feature.
* This class allows to instantiate bulk processes.
*
* A bulk function is the only required constructor parameter.
*
* @typeParam Input The type of the input items to be processed by the bulk function.
*
* @typeParam Output The type of the response items of the bulk function.
*/
export class PromiseBulk<Input = unknown, Output = unknown> {
private _index = 0
private readonly _bulks
/**
*
* @param bulkFn Bulk function. Receives an array of imputs and returns an array of outputs.
* @param _concurrency Limit of concurrent calls to the bulk function.
*/
constructor(bulkFn, private readonly _concurrency = 1) {
this._index = 0
this._bulks = Array.from({length: _concurrency}, () => new PromiseBulkSingle(bulkFn))
}
/**
* Execute
*
* This function adds one item to the bulk process and waits for its response in a bulk operation.
* @param item Atomic input that will be included in a bulk process
* @returns The associated response to the input (will be returned from a bulk process)
*/
async execute(item) {
const index = this._index
this._index = (this._index+1) % this._concurrency
return this._bulks[index].execute(item)
}
} |
e0ddebc87ef9453bc72a26de0e73313b5e391cfa | 3,193 | ts | TypeScript | src/transformArabicToHapin.ts | HerbertHe/hapin-js | 8228b182d0c557e7c76b8cb1c7d85ddfc54a4f9c | [
"MIT"
] | 1 | 2022-03-11T06:56:37.000Z | 2022-03-11T06:56:37.000Z | src/transformArabicToHapin.ts | HerbertHe/hapin-js | 8228b182d0c557e7c76b8cb1c7d85ddfc54a4f9c | [
"MIT"
] | null | null | null | src/transformArabicToHapin.ts | HerbertHe/hapin-js | 8228b182d0c557e7c76b8cb1c7d85ddfc54a4f9c | [
"MIT"
] | null | null | null | enum SpecialChar {
"S1653" = "ٴا",
"S1654" = "ٴو",
"S1655" = "ٴۇ",
"S1656" = "ٴى",
}
enum NormalChar {
"C1548" = ",",
"C1563" = ";",
"C1567" = "?",
"C1569" = "x",
"C1575" = "a",
"C1576" = "b",
"C1578" = "t",
"C1580" = "j",
"C1581" = "h",
"C1583" = "d",
"C1585" = "r",
"C1586" = "z",
"C1587" = "s",
"C1588" = "sh",
"C1593" = "gh",
"C1600" = "-",
"C1601" = "f",
"C1602" = "q",
"C1603" = "k",
"C1604" = "l",
"C1605" = "m",
"C1606" = "n",
"C1608" = "o",
"C1609" = "e",
"C1610" = "i",
"C1652" = "x",
"C1662" = "p",
"C1670" = "ch",
"C1709" = "ng",
"C1711" = "g",
"C1726" = "hh",
"C1734" = "v",
"C1735" = "u",
"C1739" = "w",
"C1749" = "ye",
"SC1575" = "xa",
"SC1608" = "xo",
"SC1735" = "xu",
"SC1609" = "xe",
}
const VowelsID = [1575, 1608, 1735, 1609]
/**
* 处理哈语特殊字符, 重整化解决可能导致的字体显示问题
* @param word 词组序列
* @returns
*/
const handleSpecialCharacters = (word: string): string => {
return word
.split("")
.map((i) => {
const code = i.charCodeAt(0)
if (code > 1652 && code < 1657) {
return SpecialChar[`S${code}`]
}
return i
})
.join("")
}
class HapinTransformer {
private _weakTone = false
private _word = ""
private _index = 0
private _res = ""
constructor(word: string) {
this._word = word
}
private addSeparator = (easy: boolean) => {
if (easy && this._index !== this._word.length - 1) {
this._res += `'`
}
}
go = (easy: boolean) => {
if (!this._word) {
return ""
}
while (this._index < this._word.length) {
const c = this._word[this._index].charCodeAt(0)
if ([1652, 1569].includes(c)) {
this._weakTone = true
this._index++
continue
}
// 处理元音
if (VowelsID.includes(c)) {
if (this._weakTone) {
this._weakTone = false
this._res += NormalChar[`SC${c}`]
} else {
this._res += NormalChar[`C${c}`]
}
this.addSeparator(easy)
this._index++
continue
}
// 处理普通字符
if (Object.keys(NormalChar).includes(`C${c}`)) {
this._res += NormalChar[`C${c}`]
} else {
this._res += this._word[this._index]
}
this.addSeparator(easy)
this._index++
continue
}
return this._res
}
}
export const transformArabicToHapin = (o: string, easy = false) => {
const array = o
.split(/( +)/g)
.map((item) => item.trim())
.filter((item) => !!item)
const res = array
.map((item: string) => {
const tmp = handleSpecialCharacters(item)
return new HapinTransformer(tmp).go(easy)
})
.join(" ")
return res.replace(/(?=[\s])( +)(?=[!-\/\:-\@])/g, "")
}
| 22.485915 | 68 | 0.417789 | 120 | 9 | 0 | 10 | 8 | 6 | 1 | 0 | 7 | 1 | 0 | 7.222222 | 1,162 | 0.016351 | 0.006885 | 0.005164 | 0.000861 | 0 | 0 | 0.212121 | 0.232154 | enum SpecialChar {
"S1653" = "ٴا",
"S1654" = "ٴو",
"S1655" = "ٴۇ",
"S1656" = "ٴى",
}
enum NormalChar {
"C1548" = ",",
"C1563" = ";",
"C1567" = "?",
"C1569" = "x",
"C1575" = "a",
"C1576" = "b",
"C1578" = "t",
"C1580" = "j",
"C1581" = "h",
"C1583" = "d",
"C1585" = "r",
"C1586" = "z",
"C1587" = "s",
"C1588" = "sh",
"C1593" = "gh",
"C1600" = "-",
"C1601" = "f",
"C1602" = "q",
"C1603" = "k",
"C1604" = "l",
"C1605" = "m",
"C1606" = "n",
"C1608" = "o",
"C1609" = "e",
"C1610" = "i",
"C1652" = "x",
"C1662" = "p",
"C1670" = "ch",
"C1709" = "ng",
"C1711" = "g",
"C1726" = "hh",
"C1734" = "v",
"C1735" = "u",
"C1739" = "w",
"C1749" = "ye",
"SC1575" = "xa",
"SC1608" = "xo",
"SC1735" = "xu",
"SC1609" = "xe",
}
const VowelsID = [1575, 1608, 1735, 1609]
/**
* 处理哈语特殊字符, 重整化解决可能导致的字体显示问题
* @param word 词组序列
* @returns
*/
/* Example usages of 'handleSpecialCharacters' are shown below:
handleSpecialCharacters(item);
*/
const handleSpecialCharacters = (word) => {
return word
.split("")
.map((i) => {
const code = i.charCodeAt(0)
if (code > 1652 && code < 1657) {
return SpecialChar[`S${code}`]
}
return i
})
.join("")
}
class HapinTransformer {
private _weakTone = false
private _word = ""
private _index = 0
private _res = ""
constructor(word) {
this._word = word
}
private addSeparator = (easy) => {
if (easy && this._index !== this._word.length - 1) {
this._res += `'`
}
}
go = (easy) => {
if (!this._word) {
return ""
}
while (this._index < this._word.length) {
const c = this._word[this._index].charCodeAt(0)
if ([1652, 1569].includes(c)) {
this._weakTone = true
this._index++
continue
}
// 处理元音
if (VowelsID.includes(c)) {
if (this._weakTone) {
this._weakTone = false
this._res += NormalChar[`SC${c}`]
} else {
this._res += NormalChar[`C${c}`]
}
this.addSeparator(easy)
this._index++
continue
}
// 处理普通字符
if (Object.keys(NormalChar).includes(`C${c}`)) {
this._res += NormalChar[`C${c}`]
} else {
this._res += this._word[this._index]
}
this.addSeparator(easy)
this._index++
continue
}
return this._res
}
}
export const transformArabicToHapin = (o, easy = false) => {
const array = o
.split(/( +)/g)
.map((item) => item.trim())
.filter((item) => !!item)
const res = array
.map((item) => {
const tmp = handleSpecialCharacters(item)
return new HapinTransformer(tmp).go(easy)
})
.join(" ")
return res.replace(/(?=[\s])( +)(?=[!-\/\:-\@])/g, "")
}
|
024341193dae1b9d0dcab8a3a9b2d1a112d154e5 | 2,637 | tsx | TypeScript | jasmine-webui/src/jasmine-view/state-reducers.tsx | andrewsmike/jasmine | 5209a65975e067eb0678b03dd3abf89729f1e5f2 | [
"Apache-2.0"
] | 3 | 2022-02-01T06:39:29.000Z | 2022-02-01T13:08:17.000Z | jasmine-webui/src/jasmine-view/state-reducers.tsx | andrewsmike/jasmine | 5209a65975e067eb0678b03dd3abf89729f1e5f2 | [
"Apache-2.0"
] | null | null | null | jasmine-webui/src/jasmine-view/state-reducers.tsx | andrewsmike/jasmine | 5209a65975e067eb0678b03dd3abf89729f1e5f2 | [
"Apache-2.0"
] | null | null | null | export type query = {
queryId: number;
fullPath: string;
queryText: string;
};
export type viewState = {
feedbackCollapsed: boolean;
settingsVisible: boolean;
originalQuery?: query;
editorQuery?: query;
};
export const toggleFeedback = () => ({ type: "view/toggle_feedback" } as const);
export const toggleSettings = () => ({ type: "view/toggle_settings" } as const);
export const setEditorQueryText = (queryText: string) =>
({ type: "view/set_editor_query_text", queryText } as const);
export const setEditorQueryFullPath = (fullPath: string) =>
({ type: "view/set_editor_query_full_path", fullPath } as const);
export const queryEditorPartialReset = (partialQuery: Partial<query>) =>
({ type: "view/query_editor_partial_reset", partialQuery } as const);
export type viewAction = ReturnType<
| typeof toggleFeedback
| typeof toggleSettings
| typeof setEditorQueryText
| typeof setEditorQueryFullPath
| typeof queryEditorPartialReset
>;
export const defaultViewState: viewState = {
feedbackCollapsed: true,
settingsVisible: false,
originalQuery: undefined,
editorQuery: undefined,
};
export function viewReducer(
state: viewState = defaultViewState,
action: viewAction
) {
switch (action.type) {
case "view/toggle_feedback":
return {
...state,
feedbackCollapsed: !state.feedbackCollapsed,
};
case "view/toggle_settings":
return {
...state,
settingsVisible: !state.settingsVisible,
};
case "view/set_editor_query_text":
return {
...state,
editorQuery: {
...state.editorQuery,
queryText: action.queryText,
},
};
case "view/set_editor_query_full_path":
return {
...state,
editorQuery: {
...state.editorQuery,
fullPath: action.fullPath,
},
};
case "view/query_editor_partial_reset":
return {
...state,
originalQuery: {
...(state.originalQuery || {}), // May not be initialized at this point.
...action.partialQuery,
},
editorQuery: {
...(state.editorQuery || {}), // May not be initialized at this point.
...action.partialQuery,
},
};
default:
return state;
}
}
| 30.310345 | 92 | 0.554797 | 79 | 6 | 0 | 5 | 6 | 7 | 0 | 0 | 7 | 3 | 5 | 7.833333 | 570 | 0.019298 | 0.010526 | 0.012281 | 0.005263 | 0.008772 | 0 | 0.291667 | 0.256383 | export type query = {
queryId;
fullPath;
queryText;
};
export type viewState = {
feedbackCollapsed;
settingsVisible;
originalQuery?;
editorQuery?;
};
export /* Example usages of 'toggleFeedback' are shown below:
;
*/
const toggleFeedback = () => ({ type: "view/toggle_feedback" } as const);
export /* Example usages of 'toggleSettings' are shown below:
;
*/
const toggleSettings = () => ({ type: "view/toggle_settings" } as const);
export /* Example usages of 'setEditorQueryText' are shown below:
;
*/
const setEditorQueryText = (queryText) =>
({ type: "view/set_editor_query_text", queryText } as const);
export /* Example usages of 'setEditorQueryFullPath' are shown below:
;
*/
const setEditorQueryFullPath = (fullPath) =>
({ type: "view/set_editor_query_full_path", fullPath } as const);
export /* Example usages of 'queryEditorPartialReset' are shown below:
;
*/
const queryEditorPartialReset = (partialQuery) =>
({ type: "view/query_editor_partial_reset", partialQuery } as const);
export type viewAction = ReturnType<
| typeof toggleFeedback
| typeof toggleSettings
| typeof setEditorQueryText
| typeof setEditorQueryFullPath
| typeof queryEditorPartialReset
>;
export const defaultViewState = {
feedbackCollapsed: true,
settingsVisible: false,
originalQuery: undefined,
editorQuery: undefined,
};
export function viewReducer(
state = defaultViewState,
action
) {
switch (action.type) {
case "view/toggle_feedback":
return {
...state,
feedbackCollapsed: !state.feedbackCollapsed,
};
case "view/toggle_settings":
return {
...state,
settingsVisible: !state.settingsVisible,
};
case "view/set_editor_query_text":
return {
...state,
editorQuery: {
...state.editorQuery,
queryText: action.queryText,
},
};
case "view/set_editor_query_full_path":
return {
...state,
editorQuery: {
...state.editorQuery,
fullPath: action.fullPath,
},
};
case "view/query_editor_partial_reset":
return {
...state,
originalQuery: {
...(state.originalQuery || {}), // May not be initialized at this point.
...action.partialQuery,
},
editorQuery: {
...(state.editorQuery || {}), // May not be initialized at this point.
...action.partialQuery,
},
};
default:
return state;
}
}
|
02cf19770b07f698309c3cdf2bf82225b9649841 | 9,190 | ts | TypeScript | src/arithmetic/rule_three.ts | donatto-minaya/ax-calculator | 1b015e2e58796b76bd40fa3055b8709e51137a08 | [
"Apache-2.0"
] | 3 | 2022-01-04T20:01:33.000Z | 2022-02-24T03:27:24.000Z | src/arithmetic/rule_three.ts | donatto22/ax-calculator | 1b015e2e58796b76bd40fa3055b8709e51137a08 | [
"Apache-2.0"
] | null | null | null | src/arithmetic/rule_three.ts | donatto22/ax-calculator | 1b015e2e58796b76bd40fa3055b8709e51137a08 | [
"Apache-2.0"
] | 1 | 2022-02-15T23:35:52.000Z | 2022-02-15T23:35:52.000Z | export const RuleOfThree = {
/**
@param type Can be direct or inverse
**/
simple: function(type: string, a: number, b: number, c: number, d: number): number | string | undefined {
if(type == 'direct') {
if(a === undefined) {
let top = b * c, bottom = d
let bober = top < 0 ? true : false
let a2: string | number = top / bottom;
if(!Number.isInteger(a2)) {
if(bober == true)
top = top * -1
for(let i = 2; i < 13; i++) {
while((top / i > 0) && ((bottom / i) > 0)) {
if((top % i == 0) && ((bottom % i) == 0)) {
top = top / i;
bottom = bottom / i;
}
else {
if(bober)
a2 = `-${top}/${bottom}`
else
a2 = `${top}/${bottom}`
break
}
}
}
}
return a2;
}
else if(b === undefined) {
let top = a * d, bottom = c
let bober = top < 0 ? true : false
let b2: string | number = top / bottom;
if(!Number.isInteger(b2)) {
if(bober == true) {
top = top * -1
}
for(let i = 2; i < 13; i++) {
while((top / i > 0) && ((bottom / i) > 0)) {
if((top % i == 0) && ((bottom % i) == 0)) {
top = top / i;
bottom = bottom / i;
}
else {
if(bober) {
b2 = `-${top}/${bottom}`;
}
else {
b2 = `${top}/${bottom}`;
}
break;
}
}
}
}
return b2
}
else if(c === undefined) {
let top = d * a, bottom = b
var bober = top < 0 ? true : false
let c2: string | number = top / bottom
if(!Number.isInteger(c2)) {
if(bober == true)
top = top * -1
for(let i = 2; i < 13; i++) {
while((top / i > 0) && ((bottom / i) > 0)) {
if((top % i == 0) && ((bottom % i) == 0)) {
top = top / i;
bottom = bottom / i;
}
else {
if(bober)
c2 = `-${top}/${bottom}`
else
c2 = `${top}/${bottom}`
break;
}
}
}
}
return c2
}
else {
let top = b * c, bottom = a
let bober = top < 0 ? true : false
let d2: string | number = top / bottom
if(!Number.isInteger(d2)) {
if(bober == true)
top = top * -1
for(let i = 2; i < 13; i++) {
while((top / i > 0) && ((bottom / i) > 0)) {
if((top % i == 0) && ((bottom % i) == 0)) {
top = top / i;
bottom = bottom / i;
}
else {
if(bober)
d2 = `-${top}/${bottom}`
else
d2 = `${top}/${bottom}`
break;
}
}
}
}
return d2
}
}
else if (type == 'inverse') {
if(a === undefined) {
let top = b * d, bottom = c
let bober = top < 0 ? true : false
let a2: string | number = top / bottom
if(!Number.isInteger(a2)) {
if(bober == true)
top = top * -1
for(let i = 2; i < 13; i++) {
while((top / i > 0) && ((bottom / i) > 0)) {
if((top % i == 0) && ((bottom % i) == 0)) {
top = top / i;
bottom = bottom / i;
}
else {
if(bober)
a2 = `-${top}/${bottom}`
else
a2 = `${top}/${bottom}`
break
}
}
}
return a2
}
}
else if(b === undefined) {
let top = a * c, bottom = d
let bober = top < 0 ? true : false
let b2: string | number = top / bottom;
if(!Number.isInteger(b2)) {
if(bober == true)
top = top * -1
for(let i = 2; i < 13; i++) {
while((top / i > 0) && ((bottom / i) > 0)) {
if((top % i == 0) && ((bottom % i) == 0)) {
top = top / i;
bottom = bottom / i;
}
else {
if(bober)
b2 = `-${top}/${bottom}`
else
b2 = `${top}/${bottom}`
break
}
}
}
}
return b2
}
else if(c === undefined) {
let top = b * d, bottom = a
let bober = top < 0 ? true : false
let c2: string | number = top / bottom
if(!Number.isInteger(c2)) {
if(bober == true)
top = top * -1
for(let i = 2; i < 13; i++) {
while((top / i > 0) && ((bottom / i) > 0)) {
if((top % i == 0) && ((bottom % i) == 0)) {
top = top / i;
bottom = bottom / i;
}
else {
if(bober)
c2 = `-${top}/${bottom}`
else
c2 = `${top}/${bottom}`
break
}
}
}
}
return c2
}
else {
let top = a * c, bottom = b
let bober = top < 0 ? true : false
let d2: string | number = top / bottom
if(!Number.isInteger(d2)) {
if(bober == true)
top = top * -1
for(let i = 2; i < 13; i++) {
while((top / i > 0) && ((bottom / i) > 0)) {
if((top % i == 0) && ((bottom % i) == 0)) {
top = top / i;
bottom = bottom / i;
}
else {
if(bober)
d2= `-${top}/${bottom}`
else
d2 = `${top}/${bottom}`
break
}
}
}
}
return d2
}
}
else { return "You must write 'direct' or 'inverse', there are no other ways." }
}
} | 32.939068 | 109 | 0.219478 | 212 | 1 | 0 | 5 | 41 | 0 | 0 | 0 | 23 | 0 | 0 | 208 | 1,654 | 0.003628 | 0.024788 | 0 | 0 | 0 | 0 | 0.489362 | 0.259827 | export const RuleOfThree = {
/**
@param type Can be direct or inverse
**/
simple: function(type, a, b, c, d) {
if(type == 'direct') {
if(a === undefined) {
let top = b * c, bottom = d
let bober = top < 0 ? true : false
let a2 = top / bottom;
if(!Number.isInteger(a2)) {
if(bober == true)
top = top * -1
for(let i = 2; i < 13; i++) {
while((top / i > 0) && ((bottom / i) > 0)) {
if((top % i == 0) && ((bottom % i) == 0)) {
top = top / i;
bottom = bottom / i;
}
else {
if(bober)
a2 = `-${top}/${bottom}`
else
a2 = `${top}/${bottom}`
break
}
}
}
}
return a2;
}
else if(b === undefined) {
let top = a * d, bottom = c
let bober = top < 0 ? true : false
let b2 = top / bottom;
if(!Number.isInteger(b2)) {
if(bober == true) {
top = top * -1
}
for(let i = 2; i < 13; i++) {
while((top / i > 0) && ((bottom / i) > 0)) {
if((top % i == 0) && ((bottom % i) == 0)) {
top = top / i;
bottom = bottom / i;
}
else {
if(bober) {
b2 = `-${top}/${bottom}`;
}
else {
b2 = `${top}/${bottom}`;
}
break;
}
}
}
}
return b2
}
else if(c === undefined) {
let top = d * a, bottom = b
var bober = top < 0 ? true : false
let c2 = top / bottom
if(!Number.isInteger(c2)) {
if(bober == true)
top = top * -1
for(let i = 2; i < 13; i++) {
while((top / i > 0) && ((bottom / i) > 0)) {
if((top % i == 0) && ((bottom % i) == 0)) {
top = top / i;
bottom = bottom / i;
}
else {
if(bober)
c2 = `-${top}/${bottom}`
else
c2 = `${top}/${bottom}`
break;
}
}
}
}
return c2
}
else {
let top = b * c, bottom = a
let bober = top < 0 ? true : false
let d2 = top / bottom
if(!Number.isInteger(d2)) {
if(bober == true)
top = top * -1
for(let i = 2; i < 13; i++) {
while((top / i > 0) && ((bottom / i) > 0)) {
if((top % i == 0) && ((bottom % i) == 0)) {
top = top / i;
bottom = bottom / i;
}
else {
if(bober)
d2 = `-${top}/${bottom}`
else
d2 = `${top}/${bottom}`
break;
}
}
}
}
return d2
}
}
else if (type == 'inverse') {
if(a === undefined) {
let top = b * d, bottom = c
let bober = top < 0 ? true : false
let a2 = top / bottom
if(!Number.isInteger(a2)) {
if(bober == true)
top = top * -1
for(let i = 2; i < 13; i++) {
while((top / i > 0) && ((bottom / i) > 0)) {
if((top % i == 0) && ((bottom % i) == 0)) {
top = top / i;
bottom = bottom / i;
}
else {
if(bober)
a2 = `-${top}/${bottom}`
else
a2 = `${top}/${bottom}`
break
}
}
}
return a2
}
}
else if(b === undefined) {
let top = a * c, bottom = d
let bober = top < 0 ? true : false
let b2 = top / bottom;
if(!Number.isInteger(b2)) {
if(bober == true)
top = top * -1
for(let i = 2; i < 13; i++) {
while((top / i > 0) && ((bottom / i) > 0)) {
if((top % i == 0) && ((bottom % i) == 0)) {
top = top / i;
bottom = bottom / i;
}
else {
if(bober)
b2 = `-${top}/${bottom}`
else
b2 = `${top}/${bottom}`
break
}
}
}
}
return b2
}
else if(c === undefined) {
let top = b * d, bottom = a
let bober = top < 0 ? true : false
let c2 = top / bottom
if(!Number.isInteger(c2)) {
if(bober == true)
top = top * -1
for(let i = 2; i < 13; i++) {
while((top / i > 0) && ((bottom / i) > 0)) {
if((top % i == 0) && ((bottom % i) == 0)) {
top = top / i;
bottom = bottom / i;
}
else {
if(bober)
c2 = `-${top}/${bottom}`
else
c2 = `${top}/${bottom}`
break
}
}
}
}
return c2
}
else {
let top = a * c, bottom = b
let bober = top < 0 ? true : false
let d2 = top / bottom
if(!Number.isInteger(d2)) {
if(bober == true)
top = top * -1
for(let i = 2; i < 13; i++) {
while((top / i > 0) && ((bottom / i) > 0)) {
if((top % i == 0) && ((bottom % i) == 0)) {
top = top / i;
bottom = bottom / i;
}
else {
if(bober)
d2= `-${top}/${bottom}`
else
d2 = `${top}/${bottom}`
break
}
}
}
}
return d2
}
}
else { return "You must write 'direct' or 'inverse', there are no other ways." }
}
} |
2900eedd5bc258ebde3232ddf569b5248fc59ab4 | 2,517 | ts | TypeScript | src/util/extract.ts | Akryum/vue-typegen | 5145030c7fce2d6f8dad432bcac849610146a50d | [
"MIT"
] | 31 | 2022-01-04T01:00:17.000Z | 2022-02-23T06:17:14.000Z | src/util/extract.ts | Akryum/vue-typegen | 5145030c7fce2d6f8dad432bcac849610146a50d | [
"MIT"
] | 1 | 2022-02-18T00:20:06.000Z | 2022-02-18T00:20:06.000Z | src/util/extract.ts | Akryum/vue-typegen | 5145030c7fce2d6f8dad432bcac849610146a50d | [
"MIT"
] | null | null | null | type RawScript = ['normal' | 'setup', string[]]
export function extractScripts (source: string) {
const lines = source.split('\n')
const rawScripts = extractScriptLines(lines)
const normalScripts = rawScripts.filter(([type]) => type === 'normal')
const setupScripts = rawScripts.filter(([type]) => type === 'setup')
const finalLines: string[] = []
for (const rawScript of normalScripts) {
finalLines.push(...rawScript[1])
}
// Export
let exportIndex = finalLines.findIndex(line => isExportDefault(line))
if (exportIndex === -1) {
finalLines.unshift('import { defineComponent } from "vue"')
exportIndex = finalLines.length
finalLines.push('export default defineComponent({', '})')
}
// add the setup function
if (setupScripts.length > 0) {
finalLines.splice(exportIndex + 1, 0, 'setup () {', '},')
exportIndex++
}
const setupVariables: string[] = []
for (const rawScript of setupScripts) {
finalLines.splice(exportIndex + 1, 0, ...rawScript[1])
exportIndex += rawScript[1].length
for (const line of rawScript[1]) {
const variable = getVariableName(line)
if (variable) {
setupVariables.push(variable)
}
}
}
// Setup return
if (setupVariables.length > 0) {
finalLines.splice(exportIndex + 1, 0, `return {${setupVariables.join(',')}}`)
exportIndex++
}
return finalLines.join('\n')
}
export function isScriptTagStart (line: string) {
return line.trim().startsWith('<script')
}
export function isScriptTagEnd (line: string) {
return line.trim() === '</script>'
}
export function isSetupScript (line: string) {
return line.includes('setup')
}
export function isExportDefault (line: string) {
return line.trim().startsWith('export default')
}
export function getVariableName (line: string) {
const matched = /(var|const|let)\s+([\w\d_]+)/.exec(line)
if (matched) {
return matched[2]
}
return null
}
export function extractScriptLines (lines: string[]): RawScript[] {
let depth = 0
const scripts: RawScript[] = []
let scriptLines: string[] = []
for (const line of lines) {
if (isScriptTagStart(line)) {
depth++
if (depth === 1) {
scriptLines = []
scripts.push([isSetupScript(line) ? 'setup' : 'normal', scriptLines])
}
} else if (isScriptTagEnd(line)) {
depth--
} else if (depth > 0) {
scriptLines.push(line)
}
}
if (depth > 0) {
throw new Error('unclosed script tag')
}
return scripts
}
| 24.676471 | 81 | 0.638856 | 78 | 10 | 0 | 10 | 12 | 0 | 6 | 0 | 11 | 1 | 0 | 6.6 | 709 | 0.028209 | 0.016925 | 0 | 0.00141 | 0 | 0 | 0.34375 | 0.294721 | type RawScript = ['normal' | 'setup', string[]]
export function extractScripts (source) {
const lines = source.split('\n')
const rawScripts = extractScriptLines(lines)
const normalScripts = rawScripts.filter(([type]) => type === 'normal')
const setupScripts = rawScripts.filter(([type]) => type === 'setup')
const finalLines = []
for (const rawScript of normalScripts) {
finalLines.push(...rawScript[1])
}
// Export
let exportIndex = finalLines.findIndex(line => isExportDefault(line))
if (exportIndex === -1) {
finalLines.unshift('import { defineComponent } from "vue"')
exportIndex = finalLines.length
finalLines.push('export default defineComponent({', '})')
}
// add the setup function
if (setupScripts.length > 0) {
finalLines.splice(exportIndex + 1, 0, 'setup () {', '},')
exportIndex++
}
const setupVariables = []
for (const rawScript of setupScripts) {
finalLines.splice(exportIndex + 1, 0, ...rawScript[1])
exportIndex += rawScript[1].length
for (const line of rawScript[1]) {
const variable = getVariableName(line)
if (variable) {
setupVariables.push(variable)
}
}
}
// Setup return
if (setupVariables.length > 0) {
finalLines.splice(exportIndex + 1, 0, `return {${setupVariables.join(',')}}`)
exportIndex++
}
return finalLines.join('\n')
}
export /* Example usages of 'isScriptTagStart' are shown below:
isScriptTagStart(line);
*/
function isScriptTagStart (line) {
return line.trim().startsWith('<script')
}
export /* Example usages of 'isScriptTagEnd' are shown below:
isScriptTagEnd(line);
*/
function isScriptTagEnd (line) {
return line.trim() === '</script>'
}
export /* Example usages of 'isSetupScript' are shown below:
isSetupScript(line) ? 'setup' : 'normal';
*/
function isSetupScript (line) {
return line.includes('setup')
}
export /* Example usages of 'isExportDefault' are shown below:
isExportDefault(line);
*/
function isExportDefault (line) {
return line.trim().startsWith('export default')
}
export /* Example usages of 'getVariableName' are shown below:
getVariableName(line);
*/
function getVariableName (line) {
const matched = /(var|const|let)\s+([\w\d_]+)/.exec(line)
if (matched) {
return matched[2]
}
return null
}
export /* Example usages of 'extractScriptLines' are shown below:
extractScriptLines(lines);
*/
function extractScriptLines (lines) {
let depth = 0
const scripts = []
let scriptLines = []
for (const line of lines) {
if (isScriptTagStart(line)) {
depth++
if (depth === 1) {
scriptLines = []
scripts.push([isSetupScript(line) ? 'setup' : 'normal', scriptLines])
}
} else if (isScriptTagEnd(line)) {
depth--
} else if (depth > 0) {
scriptLines.push(line)
}
}
if (depth > 0) {
throw new Error('unclosed script tag')
}
return scripts
}
|
2948a7bd1878307b6d7ac842363b471f9e5d3971 | 1,754 | ts | TypeScript | src/app/models/platform-api/requests/vaults/vault-proposals-filter.ts | Opdex/opdex-v1-ui | 2ece9c2405d6e6b0b1aec342e381d5aad6a2a1e7 | [
"MIT"
] | 2 | 2022-01-06T23:47:44.000Z | 2022-01-06T23:49:37.000Z | src/app/models/platform-api/requests/vaults/vault-proposals-filter.ts | Opdex/opdex-v1-ui | 2ece9c2405d6e6b0b1aec342e381d5aad6a2a1e7 | [
"MIT"
] | null | null | null | src/app/models/platform-api/requests/vaults/vault-proposals-filter.ts | Opdex/opdex-v1-ui | 2ece9c2405d6e6b0b1aec342e381d5aad6a2a1e7 | [
"MIT"
] | null | null | null | export enum VaultProposalTypeFilter {
create = 'Create',
revoke = 'Revoke',
totalPledgeMinimum = 'TotalPledgeMinimum',
totalVoteMinimum = 'TotalVoteMinimum'
}
export enum VaultProposalStatusFilter {
pledge = 'Pledge',
vote = 'Vote',
complete = 'Complete'
}
export interface IVaultProposalsFilter {
status?: VaultProposalStatusFilter[];
type?: VaultProposalTypeFilter[];
limit?: number;
direction?: string;
cursor?: string;
}
export class VaultProposalsFilter implements IVaultProposalsFilter {
status?: VaultProposalStatusFilter[];
type?: VaultProposalTypeFilter[];
limit?: number;
direction?: string;
cursor?: string;
constructor(request?: IVaultProposalsFilter) {
if (request === null || request === undefined) {
this.limit = 5;
this.direction = 'DESC';
return;
};
this.type = request.type;
this.status = request.status;
this.cursor = request.cursor;
this.limit = request.limit;
this.direction = request.direction;
}
public buildQueryString(): string {
if (this.cursor?.length) return `?cursor=${this.cursor}`;
let query = '';
if (this.status?.length > 0) {
this.status.forEach(status => query = this.addToQuery(query, 'status', status));
}
if (this.type?.length > 0) {
this.type.forEach(type => query = this.addToQuery(query, 'type', type));
}
query = this.addToQuery(query, 'limit', this.limit);
query = this.addToQuery(query, 'direction', this.direction);
return query
}
private addToQuery(query: string, key: string, value: string | number): string {
if (!!value === false) return query;
const leading = query.length > 0 ? '&' : '?';
return `${query}${leading}${key}=${value}`;
}
}
| 25.057143 | 86 | 0.656784 | 55 | 5 | 0 | 6 | 2 | 10 | 1 | 0 | 12 | 2 | 0 | 5.2 | 464 | 0.023707 | 0.00431 | 0.021552 | 0.00431 | 0 | 0 | 0.521739 | 0.246122 | export enum VaultProposalTypeFilter {
create = 'Create',
revoke = 'Revoke',
totalPledgeMinimum = 'TotalPledgeMinimum',
totalVoteMinimum = 'TotalVoteMinimum'
}
export enum VaultProposalStatusFilter {
pledge = 'Pledge',
vote = 'Vote',
complete = 'Complete'
}
export interface IVaultProposalsFilter {
status?;
type?;
limit?;
direction?;
cursor?;
}
export class VaultProposalsFilter implements IVaultProposalsFilter {
status?;
type?;
limit?;
direction?;
cursor?;
constructor(request?) {
if (request === null || request === undefined) {
this.limit = 5;
this.direction = 'DESC';
return;
};
this.type = request.type;
this.status = request.status;
this.cursor = request.cursor;
this.limit = request.limit;
this.direction = request.direction;
}
public buildQueryString() {
if (this.cursor?.length) return `?cursor=${this.cursor}`;
let query = '';
if (this.status?.length > 0) {
this.status.forEach(status => query = this.addToQuery(query, 'status', status));
}
if (this.type?.length > 0) {
this.type.forEach(type => query = this.addToQuery(query, 'type', type));
}
query = this.addToQuery(query, 'limit', this.limit);
query = this.addToQuery(query, 'direction', this.direction);
return query
}
private addToQuery(query, key, value) {
if (!!value === false) return query;
const leading = query.length > 0 ? '&' : '?';
return `${query}${leading}${key}=${value}`;
}
}
|
296932523e3b4463c9162828391a37d94cb76f5d | 2,291 | ts | TypeScript | mock-server/src/util/http-exception.ts | Lindeneg/cl-react-hooks | 46f4eef7bba77aacc38f2a5fdabf83ef796c5f54 | [
"MIT"
] | 2 | 2022-03-09T08:18:36.000Z | 2022-03-10T18:51:15.000Z | mock-server/src/util/http-exception.ts | Lindeneg/lindeneg-npm-packages | 46f4eef7bba77aacc38f2a5fdabf83ef796c5f54 | [
"MIT"
] | null | null | null | mock-server/src/util/http-exception.ts | Lindeneg/lindeneg-npm-packages | 46f4eef7bba77aacc38f2a5fdabf83ef796c5f54 | [
"MIT"
] | null | null | null | export type ErrorResponse = {
message: string;
dev?: unknown;
};
export class HTTPException extends Error {
readonly statusCode: number;
readonly error?: unknown;
constructor(message: string, statusCode: number, error?: unknown) {
super(message);
this.error = typeof error !== 'undefined' ? error : '';
this.statusCode = statusCode;
}
public toResponse() {
const obj: ErrorResponse = { message: this.message };
if (this.error) {
obj.dev = this.error;
}
return obj;
}
public static notFoundErr(error?: unknown) {
return new HTTPException(
'The requested resource could not be found.',
404,
error
);
}
public static methodErr(error?: unknown) {
return new HTTPException(
'The requested action is made using an illegal method.',
405,
error
);
}
public static malformedErr(error?: unknown) {
return new HTTPException(
'The requested action could not be exercised due to malformed syntax.',
400,
error
);
}
public static internalErr(error?: unknown) {
return new HTTPException(
'Something went wrong. Please try again later.',
500,
error
);
}
public static unprocessableErr(error?: unknown) {
return new HTTPException(
'The request was well-formed but not honored.' +
' Perhaps the action trying to be performed has already been done?',
422,
error
);
}
public static authErr(error?: unknown) {
return new HTTPException(
'The provided credentials are either invalid or has' +
' insufficient privilege to perform the requested action.',
401,
error
);
}
public static getError(error: unknown) {
const isHttpException = error instanceof HTTPException;
const isError = error instanceof Error;
const result: ErrorResponse & { statusCode: number } = {
statusCode: isHttpException ? error.statusCode : 500,
message: 'Something went wrong. Please try again.',
};
if (isHttpException) {
const res = error.toResponse();
result.message = res.message;
if (res.dev) {
result.dev = res.dev;
}
} else if (isError) {
result.message = error.message;
}
return result;
}
}
| 24.37234 | 77 | 0.633348 | 82 | 9 | 0 | 10 | 5 | 4 | 1 | 0 | 15 | 2 | 3 | 6.222222 | 535 | 0.035514 | 0.009346 | 0.007477 | 0.003738 | 0.005607 | 0 | 0.535714 | 0.288437 | export type ErrorResponse = {
message;
dev?;
};
export class HTTPException extends Error {
readonly statusCode;
readonly error?;
constructor(message, statusCode, error?) {
super(message);
this.error = typeof error !== 'undefined' ? error : '';
this.statusCode = statusCode;
}
public toResponse() {
const obj = { message: this.message };
if (this.error) {
obj.dev = this.error;
}
return obj;
}
public static notFoundErr(error?) {
return new HTTPException(
'The requested resource could not be found.',
404,
error
);
}
public static methodErr(error?) {
return new HTTPException(
'The requested action is made using an illegal method.',
405,
error
);
}
public static malformedErr(error?) {
return new HTTPException(
'The requested action could not be exercised due to malformed syntax.',
400,
error
);
}
public static internalErr(error?) {
return new HTTPException(
'Something went wrong. Please try again later.',
500,
error
);
}
public static unprocessableErr(error?) {
return new HTTPException(
'The request was well-formed but not honored.' +
' Perhaps the action trying to be performed has already been done?',
422,
error
);
}
public static authErr(error?) {
return new HTTPException(
'The provided credentials are either invalid or has' +
' insufficient privilege to perform the requested action.',
401,
error
);
}
public static getError(error) {
const isHttpException = error instanceof HTTPException;
const isError = error instanceof Error;
const result = {
statusCode: isHttpException ? error.statusCode : 500,
message: 'Something went wrong. Please try again.',
};
if (isHttpException) {
const res = error.toResponse();
result.message = res.message;
if (res.dev) {
result.dev = res.dev;
}
} else if (isError) {
result.message = error.message;
}
return result;
}
}
|
bf1b147699a129a0be2294eda1b49d55dd0ddd29 | 1,540 | ts | TypeScript | src/models/registration/RegisterRequest.ts | Sink-or-be-Sunk/Websocket_Server | a432935ee6fbf7e05d469cd983cbdd84da196c35 | [
"MIT"
] | null | null | null | src/models/registration/RegisterRequest.ts | Sink-or-be-Sunk/Websocket_Server | a432935ee6fbf7e05d469cd983cbdd84da196c35 | [
"MIT"
] | 1 | 2022-01-24T01:23:45.000Z | 2022-01-24T01:23:45.000Z | src/models/registration/RegisterRequest.ts | Sink-or-be-Sunk/Websocket_Server | a432935ee6fbf7e05d469cd983cbdd84da196c35 | [
"MIT"
] | null | null | null | export class RegisterRequest {
type: REGISTER_TYPE;
ssid: string;
data: string;
constructor(raw: any) {
this.type = REGISTER_TYPE.INVALID;
this.ssid = "";
this.data = "";
try {
if (isInstance(raw)) {
const req = raw as RegisterRequest;
this.ssid = req.ssid;
this.type = req.type;
if (req.data) {
this.data = req.data;
}
} else {
this.type = REGISTER_TYPE.INVALID;
}
} catch (err) {
this.type = REGISTER_TYPE.BAD_FORMAT;
}
}
isValid(): boolean {
if (
this.type == REGISTER_TYPE.BAD_FORMAT ||
this.type == REGISTER_TYPE.INVALID
) {
return false;
} else {
return true;
}
}
toString(): string {
return JSON.stringify(this);
}
}
export function isInstance(object: any): boolean {
if ("ssid" in object && "type" in object) {
if (
object.type === REGISTER_TYPE.ENQUEUE ||
object.type === REGISTER_TYPE.CONFIRM ||
object.type === REGISTER_TYPE.INITIATE ||
object.type === REGISTER_TYPE.GET_LIST ||
object.type === REGISTER_TYPE.DEQUEUE
) {
return true;
}
}
return false;
}
export enum REGISTER_TYPE {
/** client wants on registration pending list */
ENQUEUE = "ENQUEUE",
/** web client initiate pairing */
INITIATE = "INITIATE",
/** client confirms registration match */
CONFIRM = "CONFIRM",
/** web client able to get list of pending devices */
GET_LIST = "GET_LIST",
/** terminates the registration operation, removes device from register list */
DEQUEUE = "DEQUEUE",
INVALID = "INVALID",
BAD_FORMAT = "BAD FORMAT",
}
| 21.690141 | 80 | 0.646104 | 60 | 4 | 0 | 2 | 1 | 3 | 1 | 2 | 5 | 1 | 1 | 9.5 | 504 | 0.011905 | 0.001984 | 0.005952 | 0.001984 | 0.001984 | 0.2 | 0.5 | 0.203705 | export class RegisterRequest {
type;
ssid;
data;
constructor(raw) {
this.type = REGISTER_TYPE.INVALID;
this.ssid = "";
this.data = "";
try {
if (isInstance(raw)) {
const req = raw as RegisterRequest;
this.ssid = req.ssid;
this.type = req.type;
if (req.data) {
this.data = req.data;
}
} else {
this.type = REGISTER_TYPE.INVALID;
}
} catch (err) {
this.type = REGISTER_TYPE.BAD_FORMAT;
}
}
isValid() {
if (
this.type == REGISTER_TYPE.BAD_FORMAT ||
this.type == REGISTER_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 ("ssid" in object && "type" in object) {
if (
object.type === REGISTER_TYPE.ENQUEUE ||
object.type === REGISTER_TYPE.CONFIRM ||
object.type === REGISTER_TYPE.INITIATE ||
object.type === REGISTER_TYPE.GET_LIST ||
object.type === REGISTER_TYPE.DEQUEUE
) {
return true;
}
}
return false;
}
export enum REGISTER_TYPE {
/** client wants on registration pending list */
ENQUEUE = "ENQUEUE",
/** web client initiate pairing */
INITIATE = "INITIATE",
/** client confirms registration match */
CONFIRM = "CONFIRM",
/** web client able to get list of pending devices */
GET_LIST = "GET_LIST",
/** terminates the registration operation, removes device from register list */
DEQUEUE = "DEQUEUE",
INVALID = "INVALID",
BAD_FORMAT = "BAD FORMAT",
}
|
bf5af5ab42deacf6b88092fb6e864954e155f0e1 | 3,300 | ts | TypeScript | pkg/ts/utils/object.ts | project-oak/arcsjs-core | ec70f5330136f20bc6e097c1c42c08ef2c604b8e | [
"BSD-3-Clause"
] | 1 | 2022-03-10T20:53:13.000Z | 2022-03-10T20:53:13.000Z | pkg/demo/vs/arcsjs/src/web/ts/utils/object.ts | project-oak/arcsjs-chromium | 353f4e74c26178d28b0f5cc354f3b7f7110b4f02 | [
"BSD-3-Clause"
] | 1 | 2022-03-24T17:06:04.000Z | 2022-03-24T17:06:04.000Z | pkg/ts/utils/object.ts | project-oak/arcsjs-core | ec70f5330136f20bc6e097c1c42c08ef2c604b8e | [
"BSD-3-Clause"
] | 2 | 2022-03-17T18:25:33.000Z | 2022-03-30T20:35:42.000Z | /**
* Copyright 2022 Google LLC
*
* Use of this source code is governed by a BSD-style
* license that can be found in the LICENSE file or at
* https://developers.google.com/open-source/licenses/bsd
*/
/*
* update the fields of `obj` with the fields of `data`,
* perturbing `obj` as little as possible (since it might be a magic proxy thing
* like an Automerge document)
*/
export const shallowUpdate = (obj: any, data: any) => {
let result = data;
if (!data) {
//
} else if (Array.isArray(data)) {
if (!Array.isArray(obj)) {
// TODO(sjmiles): eek, very perturbing to obj
obj = [];
}
for (let i=0; i<data.length; i++) {
const value = data[i];
if (obj[i] !== value) {
obj[i] = value;
}
}
const overage = obj.length - data.length;
if (overage > 0) {
obj.splice(data.length, overage);
}
} else if (typeof data === 'object') {
result = (obj && typeof obj === 'object') ? obj : Object.create(null);
const seen = {};
// for each key in input data ...
Object.keys(data).forEach(key => {
// copy that data into output
result[key] = data[key];
// remember the key
seen[key] = true;
});
// for each key in the output data...
Object.keys(result).forEach(key => {
// if this key was not in the input, remove it
if (!seen[key]) {
delete result[key];
}
});
}
return result;
};
export const shallowMerge = (obj: any, data: any) => {
if (data == null) {
return null;
}
if (typeof data === 'object') {
const result = (obj && typeof obj === 'object') ? obj : Object.create(null);
Object.keys(data).forEach(key => result[key] = data[key]);
return result;
}
return data;
};
export function deepCopy<T>(datum: T): T {
if (!datum) {
return datum;
} else if (Array.isArray(datum)) {
// This is trivially type safe but tsc needs help
return datum.map(element => deepCopy(element)) as unknown as T;
} else if (typeof datum === 'object') {
const clone = Object.create(null);
Object.entries(datum).forEach(([key, value]) => {
clone[key] = deepCopy(value);
});
return clone;
} else {
return datum;
}
}
export const deepEqual = (a: any, b: any) => {
const type = typeof a;
// must be same type to be equal
if (type !== typeof b) {
return false;
}
// we are `deep` because we recursively study object types
if (type === 'object' && a && b) {
const aProps = Object.getOwnPropertyNames(a);
const bProps = Object.getOwnPropertyNames(b);
// equal if same # of props, and no prop is not deepEqual
return (aProps.length == bProps.length) && !aProps.some(name => !deepEqual(a[name], b[name]));
}
// finally, perform simple comparison
return (a === b);
};
export const deepUndefinedToNull = (obj: any) => {
if (obj === undefined) {
return null;
}
if (obj && (typeof obj === 'object')) {
// we are `deep` because we recursively study object types
const props = Object.getOwnPropertyNames(obj);
props.forEach(name => {
const prop = obj[name];
if (prop === undefined) {
delete obj[name];
//obj[name] = null;
} else {
deepUndefinedToNull(prop);
}
});
}
return obj;
};
| 27.731092 | 98 | 0.585455 | 87 | 12 | 0 | 15 | 16 | 0 | 3 | 7 | 1 | 0 | 10 | 7.666667 | 949 | 0.028451 | 0.01686 | 0 | 0 | 0.010537 | 0.162791 | 0.023256 | 0.288268 | /**
* Copyright 2022 Google LLC
*
* Use of this source code is governed by a BSD-style
* license that can be found in the LICENSE file or at
* https://developers.google.com/open-source/licenses/bsd
*/
/*
* update the fields of `obj` with the fields of `data`,
* perturbing `obj` as little as possible (since it might be a magic proxy thing
* like an Automerge document)
*/
export const shallowUpdate = (obj, data) => {
let result = data;
if (!data) {
//
} else if (Array.isArray(data)) {
if (!Array.isArray(obj)) {
// TODO(sjmiles): eek, very perturbing to obj
obj = [];
}
for (let i=0; i<data.length; i++) {
const value = data[i];
if (obj[i] !== value) {
obj[i] = value;
}
}
const overage = obj.length - data.length;
if (overage > 0) {
obj.splice(data.length, overage);
}
} else if (typeof data === 'object') {
result = (obj && typeof obj === 'object') ? obj : Object.create(null);
const seen = {};
// for each key in input data ...
Object.keys(data).forEach(key => {
// copy that data into output
result[key] = data[key];
// remember the key
seen[key] = true;
});
// for each key in the output data...
Object.keys(result).forEach(key => {
// if this key was not in the input, remove it
if (!seen[key]) {
delete result[key];
}
});
}
return result;
};
export const shallowMerge = (obj, data) => {
if (data == null) {
return null;
}
if (typeof data === 'object') {
const result = (obj && typeof obj === 'object') ? obj : Object.create(null);
Object.keys(data).forEach(key => result[key] = data[key]);
return result;
}
return data;
};
export /* Example usages of 'deepCopy' are shown below:
deepCopy(element);
clone[key] = deepCopy(value);
*/
function deepCopy<T>(datum) {
if (!datum) {
return datum;
} else if (Array.isArray(datum)) {
// This is trivially type safe but tsc needs help
return datum.map(element => deepCopy(element)) as unknown as T;
} else if (typeof datum === 'object') {
const clone = Object.create(null);
Object.entries(datum).forEach(([key, value]) => {
clone[key] = deepCopy(value);
});
return clone;
} else {
return datum;
}
}
export /* Example usages of 'deepEqual' are shown below:
!deepEqual(a[name], b[name]);
*/
const deepEqual = (a, b) => {
const type = typeof a;
// must be same type to be equal
if (type !== typeof b) {
return false;
}
// we are `deep` because we recursively study object types
if (type === 'object' && a && b) {
const aProps = Object.getOwnPropertyNames(a);
const bProps = Object.getOwnPropertyNames(b);
// equal if same # of props, and no prop is not deepEqual
return (aProps.length == bProps.length) && !aProps.some(name => !deepEqual(a[name], b[name]));
}
// finally, perform simple comparison
return (a === b);
};
export /* Example usages of 'deepUndefinedToNull' are shown below:
deepUndefinedToNull(prop);
*/
const deepUndefinedToNull = (obj) => {
if (obj === undefined) {
return null;
}
if (obj && (typeof obj === 'object')) {
// we are `deep` because we recursively study object types
const props = Object.getOwnPropertyNames(obj);
props.forEach(name => {
const prop = obj[name];
if (prop === undefined) {
delete obj[name];
//obj[name] = null;
} else {
deepUndefinedToNull(prop);
}
});
}
return obj;
};
|
bf712f9fe76a6eeeb69b15794f6333cb9c774f5e | 7,199 | ts | TypeScript | apps/api/src/helpers/BasicTypes.ts | Kurabu-chan/Kurabu | 7ccfa7260fca82b1ef3ffd692e407f75bf17adf3 | [
"BSD-3-Clause"
] | 3 | 2022-03-10T10:05:16.000Z | 2022-03-14T21:13:54.000Z | apps/api/src/helpers/BasicTypes.ts | Kurabu-chan/Kurabu | 7ccfa7260fca82b1ef3ffd692e407f75bf17adf3 | [
"BSD-3-Clause"
] | 38 | 2022-02-23T11:40:51.000Z | 2022-03-28T20:35:34.000Z | apps/api/src/helpers/BasicTypes.ts | rafaeltab/Kurabu | 7ccfa7260fca82b1ef3ffd692e407f75bf17adf3 | [
"BSD-3-Clause"
] | null | null | null | /* eslint-disable @typescript-eslint/naming-convention */
export type ResponseMessage = {
status: string;
message: any;
};
export type ErrorResponse = {
error: string;
message?: string;
};
export type Fields = {
id?: boolean;
title?: boolean;
main_picture?: boolean;
alternative_titles?: boolean;
start_date?: boolean;
end_date?: boolean;
synopsis?: boolean;
mean?: boolean;
rank?: boolean;
popularity?: boolean;
num_list_users?: boolean;
num_scoring_users?: boolean;
nsfw?: boolean;
created_at?: boolean;
updated_at?: boolean;
media_type?: boolean;
status?: boolean;
genres?: boolean;
my_list_status?: boolean | Fields; // different possible fields
num_episodes?: boolean;
start_season?: boolean;
broadcast?: boolean;
source?: boolean;
average_episode_duration?: boolean;
rating?: boolean;
pictures?: boolean;
background?: boolean;
related_anime?: boolean | Fields;
related_manga?: boolean | Fields;
recommendations?: boolean | Fields;
studios?: boolean;
statistics?: boolean;
videos?: boolean;
};
// eslint-disable-next-line @typescript-eslint/explicit-module-boundary-types
export function fieldsToString(fields: any): string {
// eslint-disable-next-line @typescript-eslint/no-unsafe-argument
const entries = Object.entries(fields);
let str = "";
for (const entry of entries) {
if (str.length > 0) {
str += ",";
}
str += entry[0];
if (entry[1] !== true && entry[1] !== false) {
str += `{${fieldsToString(entry[1] as any)}}`;
}
}
return str;
}
export function extractFields(str: string): {
fields: Fields;
remaining: string;
} {
let subject = str;
if (subject[0] === "{") {
subject = subject.substr(1, subject.length);
}
let currentObject = "";
const createdObj: any = {};
function addObject(stri: string, val: any) {
if (stri === "") return;
// eslint-disable-next-line @typescript-eslint/no-unsafe-assignment, @typescript-eslint/no-unsafe-member-access
createdObj[currentObject] = val;
currentObject = "";
}
function skipSubject() {
subject = subject.substr(1, subject.length);
}
while (subject.length > 0) {
const subjZero = subject[0];
if (subjZero === " ") {
skipSubject();
if (subject.length === 0) {
addObject(currentObject, true);
}
continue;
}
if (subjZero === "{") {
const res = extractFields(subject);
addObject(currentObject, res.fields);
subject = res.remaining;
continue;
}
if (subjZero === "}") {
addObject(currentObject, true);
skipSubject();
if (subject[0] === ",") skipSubject();
return {
// eslint-disable-next-line @typescript-eslint/no-unsafe-assignment
fields: createdObj,
remaining: subject,
};
}
if (subjZero === ",") {
addObject(currentObject, true);
skipSubject();
continue;
}
currentObject += subjZero;
skipSubject();
if (subject.length === 0) {
addObject(currentObject, true);
}
}
return {
// eslint-disable-next-line @typescript-eslint/no-unsafe-assignment
fields: createdObj,
remaining: "",
};
}
export function allFields(): Fields {
return {
alternative_titles: true,
average_episode_duration: true,
background: true,
broadcast: true,
created_at: true,
end_date: true,
genres: true,
id: true,
main_picture: true,
mean: true,
media_type: true,
my_list_status: true,
nsfw: true,
num_episodes: true,
num_list_users: true,
num_scoring_users: true,
pictures: true,
popularity: true,
rank: true,
rating: true,
recommendations: true,
related_anime: true,
related_manga: true,
source: true,
start_date: true,
start_season: true,
statistics: true,
status: true,
studios: true,
synopsis: true,
title: true,
updated_at: true,
};
}
type Relation = MediaNode & {
relation_type: string;
relation_type_formatted: string;
};
export type StatusNode = MediaNode & {
list_status: ListStatus;
};
export type Media = {
id: number;
title: string;
main_picture: Picture;
alternative_titles?: {
synonyms?: string[];
en?: string;
ja?: string;
};
start_date?: string;
end_date?: string;
synopsis?: string;
mean?: number;
rank?: number;
popularity?: number;
num_list_users?: number;
num_scoring_users?: number;
nsfw?: string;
created_at?: string;
updated_at?: string;
media_type?: string;
status?: string;
genres?: Genre[];
my_list_status?: ListStatus;
num_episodes?: number;
start_season?: Season;
broadcast?: {
day_of_the_week?: string;
start_time?: string;
};
source?: string;
average_episode_duration?: number;
rating?: string;
pictures?: Picture[];
background?: string;
related_anime?: Relation[];
related_manga?: Relation[];
recommendations?: (MediaNode & {
num_recommendations?: number;
})[];
studios?: Studio[];
statistics?: {
status?: {
watching?: string;
completed?: string;
on_hold?: string;
dropped?: string;
plan_to_watch?: string;
};
num_list_users?: number;
};
};
export type tokenResponse = {
token_type: "Bearer";
expires_in: number;
access_token: string;
refresh_token: string;
};
export type Picture = {
medium: string;
large: string;
};
export type Genre = {
id: number;
name: string;
};
export type ListStatus = {
status: "watching" | "completed" | "on_hold" | "dropped" | "plan_to_watch";
score: number;
num_episodes_watched: number;
is_rewatching: boolean;
updated_at: string;
};
export type ListPagination<T> = {
data: T[];
paging: {
next: string;
previous?: string | undefined;
};
};
export type RequestResponse<T> = {
response:
| {
response: T;
tokens: tokenResponse;
}
| ErrorResponse;
};
export type MediaNode = {
node: Media;
};
export type Season = {
year: number;
season: string;
};
export type Studio = {
id: number;
name: string;
};
// eslint-disable-next-line @typescript-eslint/explicit-module-boundary-types
export function isTokenResponse(obj: any): obj is tokenResponse {
return "tokenType" in obj;
}
// eslint-disable-next-line @typescript-eslint/explicit-module-boundary-types
export function isErrResp(obj: any): obj is ErrorResponse {
return "error" in obj;
}
| 23.680921 | 119 | 0.57633 | 263 | 7 | 0 | 6 | 7 | 90 | 4 | 7 | 91 | 15 | 1 | 15 | 1,811 | 0.007178 | 0.003865 | 0.049696 | 0.008283 | 0.000552 | 0.063636 | 0.827273 | 0.211713 | /* eslint-disable @typescript-eslint/naming-convention */
export type ResponseMessage = {
status;
message;
};
export type ErrorResponse = {
error;
message?;
};
export type Fields = {
id?;
title?;
main_picture?;
alternative_titles?;
start_date?;
end_date?;
synopsis?;
mean?;
rank?;
popularity?;
num_list_users?;
num_scoring_users?;
nsfw?;
created_at?;
updated_at?;
media_type?;
status?;
genres?;
my_list_status?; // different possible fields
num_episodes?;
start_season?;
broadcast?;
source?;
average_episode_duration?;
rating?;
pictures?;
background?;
related_anime?;
related_manga?;
recommendations?;
studios?;
statistics?;
videos?;
};
// eslint-disable-next-line @typescript-eslint/explicit-module-boundary-types
export /* Example usages of 'fieldsToString' are shown below:
fieldsToString(entry[1] as any);
*/
function fieldsToString(fields) {
// eslint-disable-next-line @typescript-eslint/no-unsafe-argument
const entries = Object.entries(fields);
let str = "";
for (const entry of entries) {
if (str.length > 0) {
str += ",";
}
str += entry[0];
if (entry[1] !== true && entry[1] !== false) {
str += `{${fieldsToString(entry[1] as any)}}`;
}
}
return str;
}
export /* Example usages of 'extractFields' are shown below:
extractFields(subject);
*/
function extractFields(str) {
let subject = str;
if (subject[0] === "{") {
subject = subject.substr(1, subject.length);
}
let currentObject = "";
const createdObj = {};
/* Example usages of 'addObject' are shown below:
addObject(currentObject, true);
addObject(currentObject, res.fields);
*/
function addObject(stri, val) {
if (stri === "") return;
// eslint-disable-next-line @typescript-eslint/no-unsafe-assignment, @typescript-eslint/no-unsafe-member-access
createdObj[currentObject] = val;
currentObject = "";
}
/* Example usages of 'skipSubject' are shown below:
skipSubject();
*/
function skipSubject() {
subject = subject.substr(1, subject.length);
}
while (subject.length > 0) {
const subjZero = subject[0];
if (subjZero === " ") {
skipSubject();
if (subject.length === 0) {
addObject(currentObject, true);
}
continue;
}
if (subjZero === "{") {
const res = extractFields(subject);
addObject(currentObject, res.fields);
subject = res.remaining;
continue;
}
if (subjZero === "}") {
addObject(currentObject, true);
skipSubject();
if (subject[0] === ",") skipSubject();
return {
// eslint-disable-next-line @typescript-eslint/no-unsafe-assignment
fields: createdObj,
remaining: subject,
};
}
if (subjZero === ",") {
addObject(currentObject, true);
skipSubject();
continue;
}
currentObject += subjZero;
skipSubject();
if (subject.length === 0) {
addObject(currentObject, true);
}
}
return {
// eslint-disable-next-line @typescript-eslint/no-unsafe-assignment
fields: createdObj,
remaining: "",
};
}
export function allFields() {
return {
alternative_titles: true,
average_episode_duration: true,
background: true,
broadcast: true,
created_at: true,
end_date: true,
genres: true,
id: true,
main_picture: true,
mean: true,
media_type: true,
my_list_status: true,
nsfw: true,
num_episodes: true,
num_list_users: true,
num_scoring_users: true,
pictures: true,
popularity: true,
rank: true,
rating: true,
recommendations: true,
related_anime: true,
related_manga: true,
source: true,
start_date: true,
start_season: true,
statistics: true,
status: true,
studios: true,
synopsis: true,
title: true,
updated_at: true,
};
}
type Relation = MediaNode & {
relation_type;
relation_type_formatted;
};
export type StatusNode = MediaNode & {
list_status;
};
export type Media = {
id;
title;
main_picture;
alternative_titles?;
start_date?;
end_date?;
synopsis?;
mean?;
rank?;
popularity?;
num_list_users?;
num_scoring_users?;
nsfw?;
created_at?;
updated_at?;
media_type?;
status?;
genres?;
my_list_status?;
num_episodes?;
start_season?;
broadcast?;
source?;
average_episode_duration?;
rating?;
pictures?;
background?;
related_anime?;
related_manga?;
recommendations?;
studios?;
statistics?;
};
export type tokenResponse = {
token_type;
expires_in;
access_token;
refresh_token;
};
export type Picture = {
medium;
large;
};
export type Genre = {
id;
name;
};
export type ListStatus = {
status;
score;
num_episodes_watched;
is_rewatching;
updated_at;
};
export type ListPagination<T> = {
data;
paging;
};
export type RequestResponse<T> = {
response;
};
export type MediaNode = {
node;
};
export type Season = {
year;
season;
};
export type Studio = {
id;
name;
};
// eslint-disable-next-line @typescript-eslint/explicit-module-boundary-types
export function isTokenResponse(obj): obj is tokenResponse {
return "tokenType" in obj;
}
// eslint-disable-next-line @typescript-eslint/explicit-module-boundary-types
export function isErrResp(obj): obj is ErrorResponse {
return "error" in obj;
}
|
bf991cf13e41beda6a1e948184ea7f39b759886d | 1,890 | ts | TypeScript | src/utils.ts | halodong/logo-canvas | fca50dd1465c90b10813a3fbca00a868e22eb03e | [
"MIT"
] | 1 | 2022-03-06T15:49:25.000Z | 2022-03-06T15:49:25.000Z | src/utils.ts | halodong/logo-canvas | fca50dd1465c90b10813a3fbca00a868e22eb03e | [
"MIT"
] | null | null | null | src/utils.ts | halodong/logo-canvas | fca50dd1465c90b10813a3fbca00a868e22eb03e | [
"MIT"
] | null | null | null | interface offsets {
vertical: number
horizontal: number
}
export function measureOffsets (
text: string,
fontFamily: string,
fontSize: number,
createCanvas: Function
): offsets {
const canvas = createCanvas()
const ctx = canvas.getContext('2d')
ctx.font = `${fontSize}px ${fontFamily}`
canvas.width = 2 * ctx.measureText(text).width
canvas.height = 2 * fontSize
ctx.font = `${fontSize}px ${fontFamily}`
canvas.width = 2 * ctx.measureText(text).width
canvas.height = 2 * fontSize
ctx.font = `${fontSize}px ${fontFamily}`
ctx.textBaseline = 'alphabetic'
ctx.textAlign = 'center'
ctx.fillStyle = 'white'
ctx.fillText(text, canvas.width / 2, canvas.height / 2)
const data = ctx.getImageData(0, 0, canvas.width, canvas.height).data
let textTop = 0
let textBottom = 0
for (let y = 0; y <= canvas.height; y++) {
for (let x = 0; x <= canvas.width; x++) {
const rIndex = 4 * (canvas.width * y + x)
const rValue = data[rIndex]
if (rValue === 255) {
if (textTop === 0) {
textTop = y
}
textBottom = y
break
}
}
}
const canvasHorizontalCenterLine = canvas.height / 2
const textHorizontalCenterLine = (textBottom - textTop) / 2 + textTop
let textLeft = 0
let textRight = 0
for (let x = 0; x <= canvas.width; x++) {
for (let y = 0; y <= canvas.height; y++) {
const rIndex = 4 * (canvas.width * y + x)
const rValue = data[rIndex]
if (rValue === 255) {
if (textLeft === 0) {
textLeft = x
}
textRight = x
break
}
}
}
const canvasVerticalCenterLine = canvas.width / 2
const textVerticalCenterLine = (textRight - textLeft) / 2 + textLeft
return {
vertical: canvasHorizontalCenterLine - textHorizontalCenterLine,
horizontal: canvasVerticalCenterLine - textVerticalCenterLine
}
}
| 26.25 | 71 | 0.61746 | 63 | 1 | 0 | 4 | 19 | 2 | 0 | 1 | 5 | 1 | 0 | 52 | 554 | 0.009025 | 0.034296 | 0.00361 | 0.001805 | 0 | 0.038462 | 0.192308 | 0.305481 | interface offsets {
vertical
horizontal
}
export function measureOffsets (
text,
fontFamily,
fontSize,
createCanvas
) {
const canvas = createCanvas()
const ctx = canvas.getContext('2d')
ctx.font = `${fontSize}px ${fontFamily}`
canvas.width = 2 * ctx.measureText(text).width
canvas.height = 2 * fontSize
ctx.font = `${fontSize}px ${fontFamily}`
canvas.width = 2 * ctx.measureText(text).width
canvas.height = 2 * fontSize
ctx.font = `${fontSize}px ${fontFamily}`
ctx.textBaseline = 'alphabetic'
ctx.textAlign = 'center'
ctx.fillStyle = 'white'
ctx.fillText(text, canvas.width / 2, canvas.height / 2)
const data = ctx.getImageData(0, 0, canvas.width, canvas.height).data
let textTop = 0
let textBottom = 0
for (let y = 0; y <= canvas.height; y++) {
for (let x = 0; x <= canvas.width; x++) {
const rIndex = 4 * (canvas.width * y + x)
const rValue = data[rIndex]
if (rValue === 255) {
if (textTop === 0) {
textTop = y
}
textBottom = y
break
}
}
}
const canvasHorizontalCenterLine = canvas.height / 2
const textHorizontalCenterLine = (textBottom - textTop) / 2 + textTop
let textLeft = 0
let textRight = 0
for (let x = 0; x <= canvas.width; x++) {
for (let y = 0; y <= canvas.height; y++) {
const rIndex = 4 * (canvas.width * y + x)
const rValue = data[rIndex]
if (rValue === 255) {
if (textLeft === 0) {
textLeft = x
}
textRight = x
break
}
}
}
const canvasVerticalCenterLine = canvas.width / 2
const textVerticalCenterLine = (textRight - textLeft) / 2 + textLeft
return {
vertical: canvasHorizontalCenterLine - textHorizontalCenterLine,
horizontal: canvasVerticalCenterLine - textVerticalCenterLine
}
}
|
bfe00a99383495a41ce88111c9a29c2cd34723e2 | 5,493 | ts | TypeScript | src/app/@core/infra/shared/forms/masks/persian-number.ts | vahid415/firstProject | e656591b066939b98c8bc6d3e8939fadb5904f99 | [
"MIT"
] | null | null | null | src/app/@core/infra/shared/forms/masks/persian-number.ts | vahid415/firstProject | e656591b066939b98c8bc6d3e8939fadb5904f99 | [
"MIT"
] | 1 | 2022-03-02T10:02:35.000Z | 2022-03-02T10:02:35.000Z | src/app/@core/infra/shared/forms/masks/persian-number.ts | vahid415/firstProject | e656591b066939b98c8bc6d3e8939fadb5904f99 | [
"MIT"
] | null | null | null | export class PersianNumber {
/**
*
* @type {string}
*/
delimiter = ' و ';
/**
*
* @type {string}
*/
zero = 'صفر';
/**
*
* @type {string}
*/
negative = 'منفی';
/**
*
* @type {*[]}
*/
letters = [['', 'یک', 'دو', 'سه', 'چهار', 'پنج', 'شش', 'هفت', 'هشت', 'نه'], ['ده', 'یازده', 'دوازده', 'سیزده', 'چهارده', 'پانزده', 'شانزده', 'هفده', 'هجده', 'نوزده', 'بیست'], ['', '', 'بیست', 'سی', 'چهل', 'پنجاه', 'شصت', 'هفتاد', 'هشتاد', 'نود'], ['', 'یکصد', 'دویست', 'سیصد', 'چهارصد', 'پانصد', 'ششصد', 'هفتصد', 'هشتصد', 'نهصد'], ['', ' هزار', ' میلیون', ' میلیارد', ' بیلیون', ' بیلیارد', ' تریلیون', ' تریلیارد', 'کوآدریلیون', ' کادریلیارد', ' کوینتیلیون', ' کوانتینیارد', ' سکستیلیون', ' سکستیلیارد', ' سپتیلیون', 'سپتیلیارد', ' اکتیلیون', ' اکتیلیارد', ' نانیلیون', ' نانیلیارد', ' دسیلیون', ' دسیلیارد']];
/**
* Decimal suffixes for decimal part
* @type {string[]}
*/
decimalSuffixes = ['', 'دهم', 'صدم', 'هزارم', 'دههزارم', 'صدهزارم', 'میلیونوم', 'دهمیلیونوم', 'صدمیلیونوم', 'میلیاردم', 'دهمیلیاردم', 'صدمیلیاردم'];
/**
* Clear number and split to 3 sections
* @param {*} num
*/
prepareNumber(num) {
let Out = num;
if (typeof Out === 'number') {
Out = Out.toString();
}
const NumberLength = Out.length % 3;
if (NumberLength === 1) {
Out = `00${Out}`;
} else if (NumberLength === 2) {
Out = `0${Out}`;
}
// Explode to array
return Out.replace(/\d{3}(?=\d)/g, '$&*')
.split('*');
}
threeNumbersToLetter(num) {
// return zero
if (parseInt(num, 0) === 0) {
return '';
}
const parsedInt = parseInt(num, 0);
if (parsedInt < 10) {
return this.letters[0][parsedInt];
}
if (parsedInt <= 20) {
return this.letters[1][parsedInt - 10];
}
if (parsedInt < 100) {
const one1 = parsedInt % 10;
const ten10 = (parsedInt - one1) / 10;
if (one1 > 0) {
return this.letters[2][ten10] + this.delimiter + this.letters[0][one1];
}
return this.letters[2][ten10];
}
const one = parsedInt % 10;
const hundreds = (parsedInt - (parsedInt % 100)) / 100;
const ten = (parsedInt - ((hundreds * 100) + one)) / 10;
const out = [this.letters[3][hundreds]];
const SecondPart = ((ten * 10) + one);
if (SecondPart > 0) {
if (SecondPart < 10) {
out.push(this.letters[0][SecondPart]);
} else if (SecondPart <= 20) {
out.push(this.letters[1][SecondPart - 10]);
} else {
out.push(this.letters[2][ten]);
if (one > 0) {
out.push(this.letters[0][one]);
}
}
}
return out.join(this.delimiter);
}
/**
* Convert Decimal part
* @param decimalPart
* @returns {string}
* @constructor
*/
convertDecimalPart(decimalPart) {
// Clear right zero
decimalPart = decimalPart.replace(/0*$/, "");
if (decimalPart === '') {
return '';
}
if (decimalPart.length > 11) {
decimalPart = decimalPart.substr(0, 11);
}
return ' ممیز ' + this.Num2persian(decimalPart) + ' ' + this.decimalSuffixes[decimalPart.length];
}
/**
* Main function
* @param input
* @returns {string}
* @constructor
*/
// Num2persian = (input) => {
Num2persian(input) {
// Clear Non digits
input = input.toString().replace(/[^0-9.]/g, '');
// return zero
if (isNaN(parseFloat(input))) {
return this.zero;
}
// Declare Parts
let decimalPart = '';
let integerPart = input;
const pointIndex = input.indexOf('.');
// Check for float numbers form string and split Int/Dec
if (pointIndex > -1) {
integerPart = input.substring(0, pointIndex);
decimalPart = input.substring(pointIndex + 1, input.length);
}
if (integerPart.length > 66) {
return 'خارج از محدوده';
}
// Split to sections
const slicedNumber = this.prepareNumber(integerPart);
// Fetch Sections and convert
const Output = [];
const SplitLength = slicedNumber.length;
for (let i = 0; i < SplitLength; i += 1) {
const SectionTitle = this.letters[4][SplitLength - (i + 1)];
const converted = this.threeNumbersToLetter(slicedNumber[i]);
if (converted !== '') {
Output.push(converted + SectionTitle);
}
}
// Convert Decimal part
if (decimalPart.length > 0) {
decimalPart = this.convertDecimalPart(decimalPart);
}
return Output.join(this.delimiter) + decimalPart;
}
formatSplitter(amount: string): string {
if (!amount) { return null; }
let rawVal: string = amount.toString();
rawVal = rawVal.replace(/,/g, '');
const dividedValueList: string[] = [];
while (rawVal.length > 0) {
const rawValueLength = rawVal.length;
const dividedValue = rawVal.substring(rawValueLength - 3);
dividedValueList.push(dividedValue);
rawVal = rawVal.substring(0, rawValueLength - 3);
}
let newValue = '';
for (let i: number = dividedValueList.length; i >= 0; i--) {
if (dividedValueList[i]) {
newValue = newValue.concat(dividedValueList[i]);
if (i !== 0) {
newValue = newValue.concat(',');
}
}
}
// remove delimiter from decimal number
// let newValue = newValue.split(".");
// if (newValue.length > 1) {
// newValue[1].replace(',', '');
// newValue = newValue[0] +"."+ newValue[1];
// }
return newValue;
}
}
| 27.465 | 613 | 0.552703 | 121 | 5 | 0 | 5 | 25 | 5 | 4 | 0 | 5 | 1 | 1 | 20.8 | 1,978 | 0.005056 | 0.012639 | 0.002528 | 0.000506 | 0.000506 | 0 | 0.125 | 0.224811 | export class PersianNumber {
/**
*
* @type {string}
*/
delimiter = ' و ';
/**
*
* @type {string}
*/
zero = 'صفر';
/**
*
* @type {string}
*/
negative = 'منفی';
/**
*
* @type {*[]}
*/
letters = [['', 'یک', 'دو', 'سه', 'چهار', 'پنج', 'شش', 'هفت', 'هشت', 'نه'], ['ده', 'یازده', 'دوازده', 'سیزده', 'چهارده', 'پانزده', 'شانزده', 'هفده', 'هجده', 'نوزده', 'بیست'], ['', '', 'بیست', 'سی', 'چهل', 'پنجاه', 'شصت', 'هفتاد', 'هشتاد', 'نود'], ['', 'یکصد', 'دویست', 'سیصد', 'چهارصد', 'پانصد', 'ششصد', 'هفتصد', 'هشتصد', 'نهصد'], ['', ' هزار', ' میلیون', ' میلیارد', ' بیلیون', ' بیلیارد', ' تریلیون', ' تریلیارد', 'کوآدریلیون', ' کادریلیارد', ' کوینتیلیون', ' کوانتینیارد', ' سکستیلیون', ' سکستیلیارد', ' سپتیلیون', 'سپتیلیارد', ' اکتیلیون', ' اکتیلیارد', ' نانیلیون', ' نانیلیارد', ' دسیلیون', ' دسیلیارد']];
/**
* Decimal suffixes for decimal part
* @type {string[]}
*/
decimalSuffixes = ['', 'دهم', 'صدم', 'هزارم', 'دههزارم', 'صدهزارم', 'میلیونوم', 'دهمیلیونوم', 'صدمیلیونوم', 'میلیاردم', 'دهمیلیاردم', 'صدمیلیاردم'];
/**
* Clear number and split to 3 sections
* @param {*} num
*/
prepareNumber(num) {
let Out = num;
if (typeof Out === 'number') {
Out = Out.toString();
}
const NumberLength = Out.length % 3;
if (NumberLength === 1) {
Out = `00${Out}`;
} else if (NumberLength === 2) {
Out = `0${Out}`;
}
// Explode to array
return Out.replace(/\d{3}(?=\d)/g, '$&*')
.split('*');
}
threeNumbersToLetter(num) {
// return zero
if (parseInt(num, 0) === 0) {
return '';
}
const parsedInt = parseInt(num, 0);
if (parsedInt < 10) {
return this.letters[0][parsedInt];
}
if (parsedInt <= 20) {
return this.letters[1][parsedInt - 10];
}
if (parsedInt < 100) {
const one1 = parsedInt % 10;
const ten10 = (parsedInt - one1) / 10;
if (one1 > 0) {
return this.letters[2][ten10] + this.delimiter + this.letters[0][one1];
}
return this.letters[2][ten10];
}
const one = parsedInt % 10;
const hundreds = (parsedInt - (parsedInt % 100)) / 100;
const ten = (parsedInt - ((hundreds * 100) + one)) / 10;
const out = [this.letters[3][hundreds]];
const SecondPart = ((ten * 10) + one);
if (SecondPart > 0) {
if (SecondPart < 10) {
out.push(this.letters[0][SecondPart]);
} else if (SecondPart <= 20) {
out.push(this.letters[1][SecondPart - 10]);
} else {
out.push(this.letters[2][ten]);
if (one > 0) {
out.push(this.letters[0][one]);
}
}
}
return out.join(this.delimiter);
}
/**
* Convert Decimal part
* @param decimalPart
* @returns {string}
* @constructor
*/
convertDecimalPart(decimalPart) {
// Clear right zero
decimalPart = decimalPart.replace(/0*$/, "");
if (decimalPart === '') {
return '';
}
if (decimalPart.length > 11) {
decimalPart = decimalPart.substr(0, 11);
}
return ' ممیز ' + this.Num2persian(decimalPart) + ' ' + this.decimalSuffixes[decimalPart.length];
}
/**
* Main function
* @param input
* @returns {string}
* @constructor
*/
// Num2persian = (input) => {
Num2persian(input) {
// Clear Non digits
input = input.toString().replace(/[^0-9.]/g, '');
// return zero
if (isNaN(parseFloat(input))) {
return this.zero;
}
// Declare Parts
let decimalPart = '';
let integerPart = input;
const pointIndex = input.indexOf('.');
// Check for float numbers form string and split Int/Dec
if (pointIndex > -1) {
integerPart = input.substring(0, pointIndex);
decimalPart = input.substring(pointIndex + 1, input.length);
}
if (integerPart.length > 66) {
return 'خارج از محدوده';
}
// Split to sections
const slicedNumber = this.prepareNumber(integerPart);
// Fetch Sections and convert
const Output = [];
const SplitLength = slicedNumber.length;
for (let i = 0; i < SplitLength; i += 1) {
const SectionTitle = this.letters[4][SplitLength - (i + 1)];
const converted = this.threeNumbersToLetter(slicedNumber[i]);
if (converted !== '') {
Output.push(converted + SectionTitle);
}
}
// Convert Decimal part
if (decimalPart.length > 0) {
decimalPart = this.convertDecimalPart(decimalPart);
}
return Output.join(this.delimiter) + decimalPart;
}
formatSplitter(amount) {
if (!amount) { return null; }
let rawVal = amount.toString();
rawVal = rawVal.replace(/,/g, '');
const dividedValueList = [];
while (rawVal.length > 0) {
const rawValueLength = rawVal.length;
const dividedValue = rawVal.substring(rawValueLength - 3);
dividedValueList.push(dividedValue);
rawVal = rawVal.substring(0, rawValueLength - 3);
}
let newValue = '';
for (let i = dividedValueList.length; i >= 0; i--) {
if (dividedValueList[i]) {
newValue = newValue.concat(dividedValueList[i]);
if (i !== 0) {
newValue = newValue.concat(',');
}
}
}
// remove delimiter from decimal number
// let newValue = newValue.split(".");
// if (newValue.length > 1) {
// newValue[1].replace(',', '');
// newValue = newValue[0] +"."+ newValue[1];
// }
return newValue;
}
}
|
8a13065db4f9051c06d4e7da23e5f8bf279c0242 | 1,783 | ts | TypeScript | modules/web-dapp/src/config/networks.ts | homiesglobal/homiesglobal | b60ef1bc6b588715e7da06892d4af5432f774570 | [
"MIT"
] | 1 | 2022-01-18T02:52:33.000Z | 2022-01-18T02:52:33.000Z | modules/web-dapp/src/config/networks.ts | homiesglobal/homiesglobal | b60ef1bc6b588715e7da06892d4af5432f774570 | [
"MIT"
] | 19 | 2022-01-06T20:39:55.000Z | 2022-03-26T16:32:56.000Z | modules/web-dapp/src/config/networks.ts | homiesglobal/homiesglobal | b60ef1bc6b588715e7da06892d4af5432f774570 | [
"MIT"
] | null | null | null | export interface NetworkParams {
chainId: number;
chainName: string;
nativeCurrency: {
name: string;
symbol: string;
decimals: number;
};
rpcUrls: string[];
blockExplorerUrls?: string[];
isTest: boolean;
}
export const BscMainnetParams: NetworkParams = {
chainId: 56,
chainName: "Binance Smart Chain",
nativeCurrency: {
name: "Binance Coin",
symbol: "BNB",
decimals: 18,
},
rpcUrls: ["https://bsc-dataseed.binance.org/"],
blockExplorerUrls: ["https://bscscan.com/"],
isTest: false,
};
export const BscTestnetParams: NetworkParams = {
chainId: 97,
chainName: "Binance Smart Chain Testnet",
nativeCurrency: {
name: "Binance Coin",
symbol: "BNB",
decimals: 18,
},
rpcUrls: ["https://data-seed-prebsc-1-s1.binance.org:8545/"],
blockExplorerUrls: ["https://testnet.bscscan.com/"],
isTest: true,
};
export const LocalNetworkParams: NetworkParams = {
chainId: 31337,
chainName: "Local Hardhat Network",
nativeCurrency: { decimals: 18, name: "Ethers", symbol: "ETH" },
rpcUrls: ["http://localhost:8545/"],
isTest: true,
};
export const NetworkByChainId = {
[BscMainnetParams.chainId]: BscMainnetParams,
[BscTestnetParams.chainId]: BscTestnetParams,
[LocalNetworkParams.chainId]: LocalNetworkParams,
};
type WalletAddChainParams = Omit<NetworkParams, "isTest" | "chainId"> & {
chainId: string;
};
// picks parameters required to add network to a wallet provider
export const networkToWalletAddChainParams = (
network: NetworkParams
): WalletAddChainParams => {
return {
chainId: `0x${network.chainId.toString(16)}`,
chainName: network.chainName,
nativeCurrency: network.nativeCurrency,
rpcUrls: network.rpcUrls,
blockExplorerUrls: network.blockExplorerUrls,
};
};
| 25.471429 | 73 | 0.69714 | 62 | 1 | 0 | 1 | 5 | 6 | 0 | 0 | 9 | 2 | 0 | 7 | 554 | 0.00361 | 0.009025 | 0.01083 | 0.00361 | 0 | 0 | 0.692308 | 0.212889 | export interface NetworkParams {
chainId;
chainName;
nativeCurrency;
rpcUrls;
blockExplorerUrls?;
isTest;
}
export const BscMainnetParams = {
chainId: 56,
chainName: "Binance Smart Chain",
nativeCurrency: {
name: "Binance Coin",
symbol: "BNB",
decimals: 18,
},
rpcUrls: ["https://bsc-dataseed.binance.org/"],
blockExplorerUrls: ["https://bscscan.com/"],
isTest: false,
};
export const BscTestnetParams = {
chainId: 97,
chainName: "Binance Smart Chain Testnet",
nativeCurrency: {
name: "Binance Coin",
symbol: "BNB",
decimals: 18,
},
rpcUrls: ["https://data-seed-prebsc-1-s1.binance.org:8545/"],
blockExplorerUrls: ["https://testnet.bscscan.com/"],
isTest: true,
};
export const LocalNetworkParams = {
chainId: 31337,
chainName: "Local Hardhat Network",
nativeCurrency: { decimals: 18, name: "Ethers", symbol: "ETH" },
rpcUrls: ["http://localhost:8545/"],
isTest: true,
};
export const NetworkByChainId = {
[BscMainnetParams.chainId]: BscMainnetParams,
[BscTestnetParams.chainId]: BscTestnetParams,
[LocalNetworkParams.chainId]: LocalNetworkParams,
};
type WalletAddChainParams = Omit<NetworkParams, "isTest" | "chainId"> & {
chainId;
};
// picks parameters required to add network to a wallet provider
export const networkToWalletAddChainParams = (
network
) => {
return {
chainId: `0x${network.chainId.toString(16)}`,
chainName: network.chainName,
nativeCurrency: network.nativeCurrency,
rpcUrls: network.rpcUrls,
blockExplorerUrls: network.blockExplorerUrls,
};
};
|
8aacc202dfbeb825f1c87f93c64528b1e9cea643 | 1,814 | ts | TypeScript | src/core/lib/utf8.ts | KristofJannes/owebsync-js | 5614314e46596dc94f4703ed596370a72dcaab87 | [
"CC0-1.0"
] | 3 | 2022-02-08T04:50:02.000Z | 2022-02-18T22:29:22.000Z | src/core/lib/utf8.ts | KristofJannes/owebsync-js | 5614314e46596dc94f4703ed596370a72dcaab87 | [
"CC0-1.0"
] | null | null | null | src/core/lib/utf8.ts | KristofJannes/owebsync-js | 5614314e46596dc94f4703ed596370a72dcaab87 | [
"CC0-1.0"
] | 2 | 2022-02-08T05:04:44.000Z | 2022-03-31T08:03:09.000Z | export function utf8Write(str: string): Uint8Array {
let p = 0;
let c1: number;
let c2: number;
const out: number[] = [];
for (let i = 0; i < str.length; ++i) {
c1 = str.charCodeAt(i);
if (c1 < 128) {
out[p++] = c1;
} else if (c1 < 2048) {
out[p++] = (c1 >> 6) | 192;
out[p++] = (c1 & 63) | 128;
} else if (
(c1 & 0xfc00) === 0xd800 &&
((c2 = str.charCodeAt(i + 1)) & 0xfc00) === 0xdc00
) {
c1 = 0x10000 + ((c1 & 0x03ff) << 10) + (c2 & 0x03ff);
++i;
out[p++] = (c1 >> 18) | 240;
out[p++] = ((c1 >> 12) & 63) | 128;
out[p++] = ((c1 >> 6) & 63) | 128;
out[p++] = (c1 & 63) | 128;
} else {
out[p++] = (c1 >> 12) | 224;
out[p++] = ((c1 >> 6) & 63) | 128;
out[p++] = (c1 & 63) | 128;
}
}
return new Uint8Array(out);
}
export function utf8Read(buf: Uint8Array): string {
let p = 0;
let parts: string[] | null = null;
const chunk: number[] = [];
let i = 0;
let t: number;
while (p < buf.byteLength) {
t = buf[p++];
if (t < 128) chunk[i++] = t;
else if (t > 191 && t < 224) chunk[i++] = ((t & 31) << 6) | (buf[p++] & 63);
else if (t > 239 && t < 365) {
t =
(((t & 7) << 18) |
((buf[p++] & 63) << 12) |
((buf[p++] & 63) << 6) |
(buf[p++] & 63)) -
0x10000;
chunk[i++] = 0xd800 + (t >> 10);
chunk[i++] = 0xdc00 + (t & 1023);
} else
chunk[i++] = ((t & 15) << 12) | ((buf[p++] & 63) << 6) | (buf[p++] & 63);
if (i > 8191) {
(parts || (parts = [])).push(String.fromCharCode(...chunk));
i = 0;
}
}
if (parts) {
if (i) {
parts.push(String.fromCharCode(...chunk.slice(0, i)));
}
return parts.join("");
}
return String.fromCharCode(...chunk.slice(0, i));
}
| 27.484848 | 80 | 0.422822 | 64 | 2 | 0 | 2 | 10 | 0 | 0 | 0 | 8 | 0 | 0 | 30 | 824 | 0.004854 | 0.012136 | 0 | 0 | 0 | 0 | 0.571429 | 0.220404 | export function utf8Write(str) {
let p = 0;
let c1;
let c2;
const out = [];
for (let i = 0; i < str.length; ++i) {
c1 = str.charCodeAt(i);
if (c1 < 128) {
out[p++] = c1;
} else if (c1 < 2048) {
out[p++] = (c1 >> 6) | 192;
out[p++] = (c1 & 63) | 128;
} else if (
(c1 & 0xfc00) === 0xd800 &&
((c2 = str.charCodeAt(i + 1)) & 0xfc00) === 0xdc00
) {
c1 = 0x10000 + ((c1 & 0x03ff) << 10) + (c2 & 0x03ff);
++i;
out[p++] = (c1 >> 18) | 240;
out[p++] = ((c1 >> 12) & 63) | 128;
out[p++] = ((c1 >> 6) & 63) | 128;
out[p++] = (c1 & 63) | 128;
} else {
out[p++] = (c1 >> 12) | 224;
out[p++] = ((c1 >> 6) & 63) | 128;
out[p++] = (c1 & 63) | 128;
}
}
return new Uint8Array(out);
}
export function utf8Read(buf) {
let p = 0;
let parts = null;
const chunk = [];
let i = 0;
let t;
while (p < buf.byteLength) {
t = buf[p++];
if (t < 128) chunk[i++] = t;
else if (t > 191 && t < 224) chunk[i++] = ((t & 31) << 6) | (buf[p++] & 63);
else if (t > 239 && t < 365) {
t =
(((t & 7) << 18) |
((buf[p++] & 63) << 12) |
((buf[p++] & 63) << 6) |
(buf[p++] & 63)) -
0x10000;
chunk[i++] = 0xd800 + (t >> 10);
chunk[i++] = 0xdc00 + (t & 1023);
} else
chunk[i++] = ((t & 15) << 12) | ((buf[p++] & 63) << 6) | (buf[p++] & 63);
if (i > 8191) {
(parts || (parts = [])).push(String.fromCharCode(...chunk));
i = 0;
}
}
if (parts) {
if (i) {
parts.push(String.fromCharCode(...chunk.slice(0, i)));
}
return parts.join("");
}
return String.fromCharCode(...chunk.slice(0, i));
}
|
8ab616f33f5bd10a91c24a82c6b27b64f543e801 | 3,977 | ts | TypeScript | src/util/selection.ts | ReactUnity/material | 321ab123fd62b0ada4817c58cc49eb7e35f38bf9 | [
"MIT"
] | null | null | null | src/util/selection.ts | ReactUnity/material | 321ab123fd62b0ada4817c58cc49eb7e35f38bf9 | [
"MIT"
] | 2 | 2022-03-06T16:57:01.000Z | 2022-03-07T19:09:43.000Z | src/util/selection.ts | ReactUnity/material | 321ab123fd62b0ada4817c58cc49eb7e35f38bf9 | [
"MIT"
] | null | null | null |
export interface SelectionElement {
get selected(): boolean;
set selected(val: boolean);
get value(): any;
addOnChange: (callback: () => void) => (() => void);
};
export class SelectionState<T = any, ElementType extends SelectionElement = SelectionElement> {
elements: { el: ElementType, listener: () => void }[] = [];
value: T | T[];
any: boolean;
all: boolean;
onChange: (val: T | T[], all: boolean, any: boolean) => void;
onUpdate: (state: this) => void;
constructor(
public readonly allowMultiple: boolean,
public readonly initialValue: any | any[],
) {
this.value = initialValue || (allowMultiple ? [] : undefined);
if (this.allowMultiple && !Array.isArray(this.value)) this.value = [this.value];
}
private changed(sender?: ElementType): T | T[] {
if (this.allowMultiple) {
let all = true;
let any = false;
const res = [];
for (let index = 0; index < this.elements.length; index++) {
const element = this.elements[index];
if (element.el.selected) {
res.push(element.el.value);
any = true;
}
else all = false;
}
this.value = res;
this.all = all;
this.any = any;
return;
} else {
this.all = false;
let firstChecked = sender;
if (!firstChecked) {
for (let index = 0; index < this.elements.length; index++) {
const element = this.elements[index];
if (element.el.selected) {
firstChecked = element.el;
break;
}
}
}
if (!firstChecked) {
this.value = undefined;
this.any = false;
return;
}
if (!firstChecked.selected) firstChecked.selected = true;
for (let index = 0; index < this.elements.length; index++) {
const element = this.elements[index];
if (element.el !== firstChecked) element.el.selected = false;
}
this.value = firstChecked.value;
this.any = true;
}
}
triggerChange() {
this.onChange?.(this.value, this.all, this.any);
}
triggerUpdate() {
this.onUpdate?.(this);
}
register(el: ElementType) {
const listener = el.addOnChange(() => {
this.changed(el);
this.triggerChange();
this.triggerUpdate();
});
this.elements.push({ el, listener });
if (this.allowMultiple && Array.isArray(this.value)) el.selected = this.value.includes(el.value);
else el.selected = this.value === el.value;
if (this.allowMultiple) {
if (this.all && !el.selected) {
this.all = false;
this.triggerChange();
}
if (!this.any && el.selected) {
this.any = true;
this.triggerChange();
}
}
this.triggerUpdate();
}
unregister(el: ElementType) {
const ind = this.elements.findIndex(x => x.el === el);
if (ind >= 0) {
const item = this.elements[ind];
this.elements.splice(ind, 1);
if (item.listener) item.listener();
}
this.triggerUpdate();
}
setAll(checked?: boolean) {
if (!this.allowMultiple && checked) throw new Error('Multiple values cannot be selected for radio groups');
checked = !!checked;
this.all = checked;
this.any = checked;
const values = [];
for (let index = 0; index < this.elements.length; index++) {
const element = this.elements[index];
element.el.selected = checked;
}
this.value = this.allowMultiple ? values : undefined;
this.all = checked;
this.any = checked;
this.triggerChange();
this.triggerUpdate();
}
getSelectedElements(): ElementType[] {
const res: ElementType[] = [];
for (let index = 0; index < this.elements.length; index++) {
const { el } = this.elements[index];
const isSelected = this.allowMultiple && Array.isArray(this.value) ? this.value.includes(el.value) : this.value === el.value;
if (isSelected) res.push(el);
}
return res;
}
}
| 25.993464 | 131 | 0.582097 | 125 | 10 | 3 | 8 | 20 | 7 | 3 | 4 | 13 | 2 | 0 | 9.6 | 1,052 | 0.01711 | 0.019011 | 0.006654 | 0.001901 | 0 | 0.083333 | 0.270833 | 0.274364 |
export interface SelectionElement {
get selected();
set selected(val);
get value();
addOnChange;
};
export class SelectionState<T = any, ElementType extends SelectionElement = SelectionElement> {
elements = [];
value;
any;
all;
onChange;
onUpdate;
constructor(
public readonly allowMultiple,
public readonly initialValue,
) {
this.value = initialValue || (allowMultiple ? [] : undefined);
if (this.allowMultiple && !Array.isArray(this.value)) this.value = [this.value];
}
private changed(sender?) {
if (this.allowMultiple) {
let all = true;
let any = false;
const res = [];
for (let index = 0; index < this.elements.length; index++) {
const element = this.elements[index];
if (element.el.selected) {
res.push(element.el.value);
any = true;
}
else all = false;
}
this.value = res;
this.all = all;
this.any = any;
return;
} else {
this.all = false;
let firstChecked = sender;
if (!firstChecked) {
for (let index = 0; index < this.elements.length; index++) {
const element = this.elements[index];
if (element.el.selected) {
firstChecked = element.el;
break;
}
}
}
if (!firstChecked) {
this.value = undefined;
this.any = false;
return;
}
if (!firstChecked.selected) firstChecked.selected = true;
for (let index = 0; index < this.elements.length; index++) {
const element = this.elements[index];
if (element.el !== firstChecked) element.el.selected = false;
}
this.value = firstChecked.value;
this.any = true;
}
}
triggerChange() {
this.onChange?.(this.value, this.all, this.any);
}
triggerUpdate() {
this.onUpdate?.(this);
}
register(el) {
const listener = el.addOnChange(() => {
this.changed(el);
this.triggerChange();
this.triggerUpdate();
});
this.elements.push({ el, listener });
if (this.allowMultiple && Array.isArray(this.value)) el.selected = this.value.includes(el.value);
else el.selected = this.value === el.value;
if (this.allowMultiple) {
if (this.all && !el.selected) {
this.all = false;
this.triggerChange();
}
if (!this.any && el.selected) {
this.any = true;
this.triggerChange();
}
}
this.triggerUpdate();
}
unregister(el) {
const ind = this.elements.findIndex(x => x.el === el);
if (ind >= 0) {
const item = this.elements[ind];
this.elements.splice(ind, 1);
if (item.listener) item.listener();
}
this.triggerUpdate();
}
setAll(checked?) {
if (!this.allowMultiple && checked) throw new Error('Multiple values cannot be selected for radio groups');
checked = !!checked;
this.all = checked;
this.any = checked;
const values = [];
for (let index = 0; index < this.elements.length; index++) {
const element = this.elements[index];
element.el.selected = checked;
}
this.value = this.allowMultiple ? values : undefined;
this.all = checked;
this.any = checked;
this.triggerChange();
this.triggerUpdate();
}
getSelectedElements() {
const res = [];
for (let index = 0; index < this.elements.length; index++) {
const { el } = this.elements[index];
const isSelected = this.allowMultiple && Array.isArray(this.value) ? this.value.includes(el.value) : this.value === el.value;
if (isSelected) res.push(el);
}
return res;
}
}
|
8ad64254a9da769112fd8532d303d5ec9fec6e0f | 15,500 | ts | TypeScript | src/bigint.ts | ammgws/base28 | 8e305223953cc30e20a958e09d0cbeca7a0fcbbf | [
"MIT"
] | null | null | null | src/bigint.ts | ammgws/base28 | 8e305223953cc30e20a958e09d0cbeca7a0fcbbf | [
"MIT"
] | 1 | 2022-01-19T00:08:09.000Z | 2022-01-19T00:08:09.000Z | src/bigint.ts | ammgws/base28 | 8e305223953cc30e20a958e09d0cbeca7a0fcbbf | [
"MIT"
] | 1 | 2022-01-18T23:48:46.000Z | 2022-01-18T23:48:46.000Z | // Copyright 2018 Google Inc.
//
// Licensed under the Apache License, Version 2.0 (the “License”);
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
// <https://apache.org/licenses/LICENSE-2.0>.
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an “AS IS” BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
export function BigInt(arg: number): JSBI {
return __oneDigit(arg, false)
}
// Equivalent of "Number(my_bigint)" in the native implementation.
// TODO: add more tests
export function toNumber(x: JSBI): number {
const xLength = x.length
if (xLength === 0) return 0
if (xLength === 1) {
const value = x.__unsignedDigit(0)
return x.sign ? -value : value
}
const xMsd = x.__digit(xLength - 1)
const msdLeadingZeros = __clz30(xMsd)
const xBitLength = xLength * 30 - msdLeadingZeros
if (xBitLength > 1024) return x.sign ? -Infinity : Infinity
let exponent = xBitLength - 1
let currentDigit = xMsd
let digitIndex = xLength - 1
const shift = msdLeadingZeros + 3
let mantissaHigh = shift === 32 ? 0 : currentDigit << shift
mantissaHigh >>>= 12
const mantissaHighBitsUnset = shift - 12
let mantissaLow = shift >= 12 ? 0 : currentDigit << (20 + shift)
let mantissaLowBitsUnset = 20 + shift
if (mantissaHighBitsUnset > 0 && digitIndex > 0) {
digitIndex--
currentDigit = x.__digit(digitIndex)
mantissaHigh |= currentDigit >>> (30 - mantissaHighBitsUnset)
mantissaLow = currentDigit << (mantissaHighBitsUnset + 2)
mantissaLowBitsUnset = mantissaHighBitsUnset + 2
}
while (mantissaLowBitsUnset > 0 && digitIndex > 0) {
digitIndex--
currentDigit = x.__digit(digitIndex)
if (mantissaLowBitsUnset >= 30) {
mantissaLow |= currentDigit << (mantissaLowBitsUnset - 30)
} else {
mantissaLow |= currentDigit >>> (30 - mantissaLowBitsUnset)
}
mantissaLowBitsUnset -= 30
}
const rounding = __decideRounding(
x,
mantissaLowBitsUnset,
digitIndex,
currentDigit,
)
if (rounding === 1 || (rounding === 0 && (mantissaLow & 1) === 1)) {
mantissaLow = (mantissaLow + 1) >>> 0
if (mantissaLow === 0) {
// Incrementing mantissaLow overflowed.
mantissaHigh++
if (mantissaHigh >>> 20 !== 0) {
// Incrementing mantissaHigh overflowed.
mantissaHigh = 0
exponent++
if (exponent > 1023) {
// Incrementing the exponent overflowed.
return x.sign ? -Infinity : Infinity
}
}
}
}
const signBit = x.sign ? 1 << 31 : 0
exponent = (exponent + 0x3ff) << 20
__kBitConversionInts[1] = signBit | exponent | mantissaHigh
__kBitConversionInts[0] = mantissaLow
return __kBitConversionDouble[0]
}
// Operations.
export function multiply(x: JSBI, y: JSBI): JSBI {
if (x.length === 0) return x
if (y.length === 0) return y
let resultLength = x.length + y.length
if (x.__clzmsd() + y.__clzmsd() >= 30) {
resultLength--
}
const result = new JSBI(resultLength, x.sign !== y.sign)
result.__initializeDigits()
for (let i = 0; i < x.length; i++) {
__multiplyAccumulate(y, x.__digit(i), result, i)
}
return result.__trim()
}
export function remainder(x: JSBI, y: JSBI): JSBI {
if (y.length === 0) throw new RangeError('Division by zero')
if (__absoluteCompare(x, y) < 0) return x
const divisor = y.__unsignedDigit(0)
if (y.length === 1 && divisor <= 0x7fff) {
if (divisor === 1) return __zero()
const remainderDigit = __absoluteModSmall(x, divisor)
if (remainderDigit === 0) return __zero()
return __oneDigit(remainderDigit, x.sign)
}
const remainder = __absoluteDivLarge(x, y, false, true)
remainder.sign = x.sign
return remainder.__trim()
}
//---
class JSBI extends Array {
constructor(length: number, public sign: boolean) {
super(length)
// Explicitly set the prototype as per
// https://github.com/Microsoft/TypeScript-wiki/blob/main/Breaking-Changes.md#extending-built-ins-like-error-array-and-map-may-no-longer-work
Object.setPrototypeOf(this, JSBI.prototype)
}
__trim(): this {
let newLength = this.length
let last = this[newLength - 1]
while (last === 0) {
newLength--
last = this[newLength - 1]
this.pop()
}
if (newLength === 0) this.sign = false
return this
}
__initializeDigits(): void {
for (let i = 0; i < this.length; i++) {
this[i] = 0
}
}
__clzmsd(): number {
return __clz30(this.__digit(this.length - 1))
}
// TODO: work on full digits, like __inplaceSub?
__inplaceAdd(summand: JSBI, startIndex: number, halfDigits: number): number {
let carry = 0
for (let i = 0; i < halfDigits; i++) {
const sum =
this.__halfDigit(startIndex + i) + summand.__halfDigit(i) + carry
carry = sum >>> 15
this.__setHalfDigit(startIndex + i, sum & 0x7fff)
}
return carry
}
__inplaceSub(
subtrahend: JSBI,
startIndex: number,
halfDigits: number,
): number {
const fullSteps = (halfDigits - 1) >>> 1
let borrow = 0
if (startIndex & 1) {
// this: [..][..][..]
// subtr.: [..][..]
startIndex >>= 1
let current = this.__digit(startIndex)
let r0 = current & 0x7fff
let i = 0
for (; i < fullSteps; i++) {
const sub = subtrahend.__digit(i)
const r15 = (current >>> 15) - (sub & 0x7fff) - borrow
borrow = (r15 >>> 15) & 1
this.__setDigit(startIndex + i, ((r15 & 0x7fff) << 15) | (r0 & 0x7fff))
current = this.__digit(startIndex + i + 1)
r0 = (current & 0x7fff) - (sub >>> 15) - borrow
borrow = (r0 >>> 15) & 1
}
// Unrolling the last iteration gives a 5% performance benefit!
const sub = subtrahend.__digit(i)
const r15 = (current >>> 15) - (sub & 0x7fff) - borrow
borrow = (r15 >>> 15) & 1
this.__setDigit(startIndex + i, ((r15 & 0x7fff) << 15) | (r0 & 0x7fff))
const subTop = sub >>> 15
if (startIndex + i + 1 >= this.length) {
throw new RangeError('out of bounds')
}
if ((halfDigits & 1) === 0) {
current = this.__digit(startIndex + i + 1)
r0 = (current & 0x7fff) - subTop - borrow
borrow = (r0 >>> 15) & 1
this.__setDigit(
startIndex + subtrahend.length,
(current & 0x3fff8000) | (r0 & 0x7fff),
)
}
} else {
startIndex >>= 1
let i = 0
for (; i < subtrahend.length - 1; i++) {
const current = this.__digit(startIndex + i)
const sub = subtrahend.__digit(i)
const r0 = (current & 0x7fff) - (sub & 0x7fff) - borrow
borrow = (r0 >>> 15) & 1
const r15 = (current >>> 15) - (sub >>> 15) - borrow
borrow = (r15 >>> 15) & 1
this.__setDigit(startIndex + i, ((r15 & 0x7fff) << 15) | (r0 & 0x7fff))
}
const current = this.__digit(startIndex + i)
const sub = subtrahend.__digit(i)
const r0 = (current & 0x7fff) - (sub & 0x7fff) - borrow
borrow = (r0 >>> 15) & 1
let r15 = 0
if ((halfDigits & 1) === 0) {
r15 = (current >>> 15) - (sub >>> 15) - borrow
borrow = (r15 >>> 15) & 1
}
this.__setDigit(startIndex + i, ((r15 & 0x7fff) << 15) | (r0 & 0x7fff))
}
return borrow
}
__inplaceRightShift(shift: number): void {
if (shift === 0) return
let carry = this.__digit(0) >>> shift
const last = this.length - 1
for (let i = 0; i < last; i++) {
const d = this.__digit(i + 1)
this.__setDigit(i, ((d << (30 - shift)) & 0x3fffffff) | carry)
carry = d >>> shift
}
this.__setDigit(last, carry)
}
// Digit helpers.
__digit(i: number): number {
return this[i]
}
__unsignedDigit(i: number): number {
return this[i] >>> 0
}
__setDigit(i: number, digit: number): void {
this[i] = digit | 0
}
__halfDigitLength(): number {
const len = this.length
if (this.__unsignedDigit(len - 1) <= 0x7fff) return len * 2 - 1
return len * 2
}
__halfDigit(i: number): number {
return (this[i >>> 1] >>> ((i & 1) * 15)) & 0x7fff
}
__setHalfDigit(i: number, value: number): void {
const digitIndex = i >>> 1
const previous = this.__digit(digitIndex)
const updated =
i & 1
? (previous & 0x7fff) | (value << 15)
: (previous & 0x3fff8000) | (value & 0x7fff)
this.__setDigit(digitIndex, updated)
}
}
function __zero(): JSBI {
return new JSBI(0, false)
}
function __oneDigit(value: number, sign: boolean): JSBI {
const result = new JSBI(1, sign)
result.__setDigit(0, value)
return result
}
function __decideRounding(
x: JSBI,
mantissaBitsUnset: number,
digitIndex: number,
currentDigit: number,
): 1 | 0 | -1 {
if (mantissaBitsUnset > 0) return -1
let topUnconsumedBit
if (mantissaBitsUnset < 0) {
topUnconsumedBit = -mantissaBitsUnset - 1
} else {
// {currentDigit} fit the mantissa exactly; look at the next digit.
if (digitIndex === 0) return -1
digitIndex--
currentDigit = x.__digit(digitIndex)
topUnconsumedBit = 29
}
// If the most significant remaining bit is 0, round down.
let mask = 1 << topUnconsumedBit
if ((currentDigit & mask) === 0) return -1
// If any other remaining bit is set, round up.
mask -= 1
if ((currentDigit & mask) !== 0) return 1
while (digitIndex > 0) {
digitIndex--
if (x.__digit(digitIndex) !== 0) return 1
}
return 0
}
function __absoluteCompare(x: JSBI, y: JSBI) {
const diff = x.length - y.length
if (diff !== 0) return diff
let i = x.length - 1
while (i >= 0 && x.__digit(i) === y.__digit(i)) i--
if (i < 0) return 0
return x.__unsignedDigit(i) > y.__unsignedDigit(i) ? 1 : -1
}
function __multiplyAccumulate(
multiplicand: JSBI,
multiplier: number,
accumulator: JSBI,
accumulatorIndex: number,
): void {
if (multiplier === 0) return
const m2Low = multiplier & 0x7fff
const m2High = multiplier >>> 15
let carry = 0
let high = 0
for (let i = 0; i < multiplicand.length; i++, accumulatorIndex++) {
let acc = accumulator.__digit(accumulatorIndex)
const m1 = multiplicand.__digit(i)
const m1Low = m1 & 0x7fff
const m1High = m1 >>> 15
const rLow = Math.imul(m1Low, m2Low)
const rMid1 = Math.imul(m1Low, m2High)
const rMid2 = Math.imul(m1High, m2Low)
const rHigh = Math.imul(m1High, m2High)
acc += high + rLow + carry
carry = acc >>> 30
acc &= 0x3fffffff
acc += ((rMid1 & 0x7fff) << 15) + ((rMid2 & 0x7fff) << 15)
carry += acc >>> 30
high = rHigh + (rMid1 >>> 15) + (rMid2 >>> 15)
accumulator.__setDigit(accumulatorIndex, acc & 0x3fffffff)
}
for (; carry !== 0 || high !== 0; accumulatorIndex++) {
let acc = accumulator.__digit(accumulatorIndex)
acc += carry + high
high = 0
carry = acc >>> 30
accumulator.__setDigit(accumulatorIndex, acc & 0x3fffffff)
}
}
function __internalMultiplyAdd(
source: JSBI,
factor: number,
summand: number,
n: number,
result: JSBI,
): void {
let carry = summand
let high = 0
for (let i = 0; i < n; i++) {
const digit = source.__digit(i)
const rx = Math.imul(digit & 0x7fff, factor)
const ry = Math.imul(digit >>> 15, factor)
const r = rx + ((ry & 0x7fff) << 15) + high + carry
carry = r >>> 30
high = ry >>> 15
result.__setDigit(i, r & 0x3fffffff)
}
if (result.length > n) {
result.__setDigit(n++, carry + high)
while (n < result.length) {
result.__setDigit(n++, 0)
}
} else {
if (carry + high !== 0) throw new Error('implementation bug')
}
}
function __absoluteModSmall(x: JSBI, divisor: number): number {
let remainder = 0
for (let i = x.length * 2 - 1; i >= 0; i--) {
const input = ((remainder << 15) | x.__halfDigit(i)) >>> 0
remainder = input % divisor | 0
}
return remainder
}
function __absoluteDivLarge(
dividend: JSBI,
divisor: JSBI,
wantQuotient: false,
wantRemainder: false,
): undefined
function __absoluteDivLarge(
dividend: JSBI,
divisor: JSBI,
wantQuotient: true,
wantRemainder: true,
): { quotient: JSBI; remainder: JSBI }
function __absoluteDivLarge(
dividend: JSBI,
divisor: JSBI,
wantQuotient: boolean,
wantRemainder: boolean,
): JSBI
function __absoluteDivLarge(
dividend: JSBI,
divisor: JSBI,
wantQuotient: boolean,
wantRemainder: boolean,
): { quotient: JSBI; remainder: JSBI } | JSBI | undefined {
const n = divisor.__halfDigitLength()
const n2 = divisor.length
const m = dividend.__halfDigitLength() - n
let q = null
if (wantQuotient) {
q = new JSBI((m + 2) >>> 1, false)
q.__initializeDigits()
}
const qhatv = new JSBI((n + 2) >>> 1, false)
qhatv.__initializeDigits()
// D1.
const shift = __clz15(divisor.__halfDigit(n - 1))
if (shift > 0) {
divisor = __specialLeftShift(divisor, shift, 0 /* add no digits*/)
}
const u = __specialLeftShift(dividend, shift, 1 /* add one digit */)
// D2.
const vn1 = divisor.__halfDigit(n - 1)
let halfDigitBuffer = 0
for (let j = m; j >= 0; j--) {
// D3.
let qhat = 0x7fff
const ujn = u.__halfDigit(j + n)
if (ujn !== vn1) {
const input = ((ujn << 15) | u.__halfDigit(j + n - 1)) >>> 0
qhat = (input / vn1) | 0
let rhat = input % vn1 | 0
const vn2 = divisor.__halfDigit(n - 2)
const ujn2 = u.__halfDigit(j + n - 2)
while (Math.imul(qhat, vn2) >>> 0 > ((rhat << 16) | ujn2) >>> 0) {
qhat--
rhat += vn1
if (rhat > 0x7fff) break
}
}
// D4.
__internalMultiplyAdd(divisor, qhat, 0, n2, qhatv)
let c = u.__inplaceSub(qhatv, j, n + 1)
if (c !== 0) {
c = u.__inplaceAdd(divisor, j, n)
u.__setHalfDigit(j + n, (u.__halfDigit(j + n) + c) & 0x7fff)
qhat--
}
if (wantQuotient) {
if (j & 1) {
halfDigitBuffer = qhat << 15
} else {
// TODO make this statically determinable
;(q as JSBI).__setDigit(j >>> 1, halfDigitBuffer | qhat)
}
}
}
if (wantRemainder) {
u.__inplaceRightShift(shift)
if (wantQuotient) {
return { quotient: q as JSBI, remainder: u }
}
return u
}
if (wantQuotient) return q as JSBI
// TODO find a way to make this statically unreachable?
throw new Error('unreachable')
}
function __clz15(value: number): number {
return __clz30(value) - 15
}
function __specialLeftShift(x: JSBI, shift: number, addDigit: 0 | 1): JSBI {
const n = x.length
const resultLength = n + addDigit
const result = new JSBI(resultLength, false)
if (shift === 0) {
for (let i = 0; i < n; i++) result.__setDigit(i, x.__digit(i))
if (addDigit > 0) result.__setDigit(n, 0)
return result
}
let carry = 0
for (let i = 0; i < n; i++) {
const d = x.__digit(i)
result.__setDigit(i, ((d << shift) & 0x3fffffff) | carry)
carry = d >>> (30 - shift)
}
if (addDigit > 0) {
result.__setDigit(n, carry)
}
return result
}
function __clz30(x: number): number {
return Math.clz32(x) - 2
}
const __kBitConversionBuffer = /*#__PURE__*/ new ArrayBuffer(8)
const __kBitConversionDouble = /*#__PURE__*/ new Float64Array(
__kBitConversionBuffer,
)
const __kBitConversionInts = /*#__PURE__*/ new Int32Array(
__kBitConversionBuffer,
)
| 30.03876 | 145 | 0.610129 | 455 | 28 | 3 | 62 | 110 | 0 | 23 | 0 | 50 | 1 | 3 | 12.392857 | 5,182 | 0.017368 | 0.021227 | 0 | 0.000193 | 0.000579 | 0 | 0.246305 | 0.285851 | // Copyright 2018 Google Inc.
//
// Licensed under the Apache License, Version 2.0 (the “License”);
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
// <https://apache.org/licenses/LICENSE-2.0>.
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an “AS IS” BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
export function BigInt(arg) {
return __oneDigit(arg, false)
}
// Equivalent of "Number(my_bigint)" in the native implementation.
// TODO: add more tests
export function toNumber(x) {
const xLength = x.length
if (xLength === 0) return 0
if (xLength === 1) {
const value = x.__unsignedDigit(0)
return x.sign ? -value : value
}
const xMsd = x.__digit(xLength - 1)
const msdLeadingZeros = __clz30(xMsd)
const xBitLength = xLength * 30 - msdLeadingZeros
if (xBitLength > 1024) return x.sign ? -Infinity : Infinity
let exponent = xBitLength - 1
let currentDigit = xMsd
let digitIndex = xLength - 1
const shift = msdLeadingZeros + 3
let mantissaHigh = shift === 32 ? 0 : currentDigit << shift
mantissaHigh >>>= 12
const mantissaHighBitsUnset = shift - 12
let mantissaLow = shift >= 12 ? 0 : currentDigit << (20 + shift)
let mantissaLowBitsUnset = 20 + shift
if (mantissaHighBitsUnset > 0 && digitIndex > 0) {
digitIndex--
currentDigit = x.__digit(digitIndex)
mantissaHigh |= currentDigit >>> (30 - mantissaHighBitsUnset)
mantissaLow = currentDigit << (mantissaHighBitsUnset + 2)
mantissaLowBitsUnset = mantissaHighBitsUnset + 2
}
while (mantissaLowBitsUnset > 0 && digitIndex > 0) {
digitIndex--
currentDigit = x.__digit(digitIndex)
if (mantissaLowBitsUnset >= 30) {
mantissaLow |= currentDigit << (mantissaLowBitsUnset - 30)
} else {
mantissaLow |= currentDigit >>> (30 - mantissaLowBitsUnset)
}
mantissaLowBitsUnset -= 30
}
const rounding = __decideRounding(
x,
mantissaLowBitsUnset,
digitIndex,
currentDigit,
)
if (rounding === 1 || (rounding === 0 && (mantissaLow & 1) === 1)) {
mantissaLow = (mantissaLow + 1) >>> 0
if (mantissaLow === 0) {
// Incrementing mantissaLow overflowed.
mantissaHigh++
if (mantissaHigh >>> 20 !== 0) {
// Incrementing mantissaHigh overflowed.
mantissaHigh = 0
exponent++
if (exponent > 1023) {
// Incrementing the exponent overflowed.
return x.sign ? -Infinity : Infinity
}
}
}
}
const signBit = x.sign ? 1 << 31 : 0
exponent = (exponent + 0x3ff) << 20
__kBitConversionInts[1] = signBit | exponent | mantissaHigh
__kBitConversionInts[0] = mantissaLow
return __kBitConversionDouble[0]
}
// Operations.
export function multiply(x, y) {
if (x.length === 0) return x
if (y.length === 0) return y
let resultLength = x.length + y.length
if (x.__clzmsd() + y.__clzmsd() >= 30) {
resultLength--
}
const result = new JSBI(resultLength, x.sign !== y.sign)
result.__initializeDigits()
for (let i = 0; i < x.length; i++) {
__multiplyAccumulate(y, x.__digit(i), result, i)
}
return result.__trim()
}
export /* Example usages of 'remainder' are shown below:
var remainder = __absoluteDivLarge(x, y, false, true);
remainder.sign = x.sign;
remainder.__trim();
var remainder = 0;
remainder << 15;
remainder = input % divisor | 0;
return remainder;
;
*/
function remainder(x, y) {
if (y.length === 0) throw new RangeError('Division by zero')
if (__absoluteCompare(x, y) < 0) return x
const divisor = y.__unsignedDigit(0)
if (y.length === 1 && divisor <= 0x7fff) {
if (divisor === 1) return __zero()
const remainderDigit = __absoluteModSmall(x, divisor)
if (remainderDigit === 0) return __zero()
return __oneDigit(remainderDigit, x.sign)
}
const remainder = __absoluteDivLarge(x, y, false, true)
remainder.sign = x.sign
return remainder.__trim()
}
//---
class JSBI extends Array {
constructor(length, public sign) {
super(length)
// Explicitly set the prototype as per
// https://github.com/Microsoft/TypeScript-wiki/blob/main/Breaking-Changes.md#extending-built-ins-like-error-array-and-map-may-no-longer-work
Object.setPrototypeOf(this, JSBI.prototype)
}
__trim() {
let newLength = this.length
let last = this[newLength - 1]
while (last === 0) {
newLength--
last = this[newLength - 1]
this.pop()
}
if (newLength === 0) this.sign = false
return this
}
__initializeDigits() {
for (let i = 0; i < this.length; i++) {
this[i] = 0
}
}
__clzmsd() {
return __clz30(this.__digit(this.length - 1))
}
// TODO: work on full digits, like __inplaceSub?
__inplaceAdd(summand, startIndex, halfDigits) {
let carry = 0
for (let i = 0; i < halfDigits; i++) {
const sum =
this.__halfDigit(startIndex + i) + summand.__halfDigit(i) + carry
carry = sum >>> 15
this.__setHalfDigit(startIndex + i, sum & 0x7fff)
}
return carry
}
__inplaceSub(
subtrahend,
startIndex,
halfDigits,
) {
const fullSteps = (halfDigits - 1) >>> 1
let borrow = 0
if (startIndex & 1) {
// this: [..][..][..]
// subtr.: [..][..]
startIndex >>= 1
let current = this.__digit(startIndex)
let r0 = current & 0x7fff
let i = 0
for (; i < fullSteps; i++) {
const sub = subtrahend.__digit(i)
const r15 = (current >>> 15) - (sub & 0x7fff) - borrow
borrow = (r15 >>> 15) & 1
this.__setDigit(startIndex + i, ((r15 & 0x7fff) << 15) | (r0 & 0x7fff))
current = this.__digit(startIndex + i + 1)
r0 = (current & 0x7fff) - (sub >>> 15) - borrow
borrow = (r0 >>> 15) & 1
}
// Unrolling the last iteration gives a 5% performance benefit!
const sub = subtrahend.__digit(i)
const r15 = (current >>> 15) - (sub & 0x7fff) - borrow
borrow = (r15 >>> 15) & 1
this.__setDigit(startIndex + i, ((r15 & 0x7fff) << 15) | (r0 & 0x7fff))
const subTop = sub >>> 15
if (startIndex + i + 1 >= this.length) {
throw new RangeError('out of bounds')
}
if ((halfDigits & 1) === 0) {
current = this.__digit(startIndex + i + 1)
r0 = (current & 0x7fff) - subTop - borrow
borrow = (r0 >>> 15) & 1
this.__setDigit(
startIndex + subtrahend.length,
(current & 0x3fff8000) | (r0 & 0x7fff),
)
}
} else {
startIndex >>= 1
let i = 0
for (; i < subtrahend.length - 1; i++) {
const current = this.__digit(startIndex + i)
const sub = subtrahend.__digit(i)
const r0 = (current & 0x7fff) - (sub & 0x7fff) - borrow
borrow = (r0 >>> 15) & 1
const r15 = (current >>> 15) - (sub >>> 15) - borrow
borrow = (r15 >>> 15) & 1
this.__setDigit(startIndex + i, ((r15 & 0x7fff) << 15) | (r0 & 0x7fff))
}
const current = this.__digit(startIndex + i)
const sub = subtrahend.__digit(i)
const r0 = (current & 0x7fff) - (sub & 0x7fff) - borrow
borrow = (r0 >>> 15) & 1
let r15 = 0
if ((halfDigits & 1) === 0) {
r15 = (current >>> 15) - (sub >>> 15) - borrow
borrow = (r15 >>> 15) & 1
}
this.__setDigit(startIndex + i, ((r15 & 0x7fff) << 15) | (r0 & 0x7fff))
}
return borrow
}
__inplaceRightShift(shift) {
if (shift === 0) return
let carry = this.__digit(0) >>> shift
const last = this.length - 1
for (let i = 0; i < last; i++) {
const d = this.__digit(i + 1)
this.__setDigit(i, ((d << (30 - shift)) & 0x3fffffff) | carry)
carry = d >>> shift
}
this.__setDigit(last, carry)
}
// Digit helpers.
__digit(i) {
return this[i]
}
__unsignedDigit(i) {
return this[i] >>> 0
}
__setDigit(i, digit) {
this[i] = digit | 0
}
__halfDigitLength() {
const len = this.length
if (this.__unsignedDigit(len - 1) <= 0x7fff) return len * 2 - 1
return len * 2
}
__halfDigit(i) {
return (this[i >>> 1] >>> ((i & 1) * 15)) & 0x7fff
}
__setHalfDigit(i, value) {
const digitIndex = i >>> 1
const previous = this.__digit(digitIndex)
const updated =
i & 1
? (previous & 0x7fff) | (value << 15)
: (previous & 0x3fff8000) | (value & 0x7fff)
this.__setDigit(digitIndex, updated)
}
}
/* Example usages of '__zero' are shown below:
__zero();
*/
function __zero() {
return new JSBI(0, false)
}
/* Example usages of '__oneDigit' are shown below:
__oneDigit(arg, false);
__oneDigit(remainderDigit, x.sign);
*/
function __oneDigit(value, sign) {
const result = new JSBI(1, sign)
result.__setDigit(0, value)
return result
}
/* Example usages of '__decideRounding' are shown below:
__decideRounding(x, mantissaLowBitsUnset, digitIndex, currentDigit);
*/
function __decideRounding(
x,
mantissaBitsUnset,
digitIndex,
currentDigit,
) {
if (mantissaBitsUnset > 0) return -1
let topUnconsumedBit
if (mantissaBitsUnset < 0) {
topUnconsumedBit = -mantissaBitsUnset - 1
} else {
// {currentDigit} fit the mantissa exactly; look at the next digit.
if (digitIndex === 0) return -1
digitIndex--
currentDigit = x.__digit(digitIndex)
topUnconsumedBit = 29
}
// If the most significant remaining bit is 0, round down.
let mask = 1 << topUnconsumedBit
if ((currentDigit & mask) === 0) return -1
// If any other remaining bit is set, round up.
mask -= 1
if ((currentDigit & mask) !== 0) return 1
while (digitIndex > 0) {
digitIndex--
if (x.__digit(digitIndex) !== 0) return 1
}
return 0
}
/* Example usages of '__absoluteCompare' are shown below:
__absoluteCompare(x, y) < 0;
*/
function __absoluteCompare(x, y) {
const diff = x.length - y.length
if (diff !== 0) return diff
let i = x.length - 1
while (i >= 0 && x.__digit(i) === y.__digit(i)) i--
if (i < 0) return 0
return x.__unsignedDigit(i) > y.__unsignedDigit(i) ? 1 : -1
}
/* Example usages of '__multiplyAccumulate' are shown below:
__multiplyAccumulate(y, x.__digit(i), result, i);
*/
function __multiplyAccumulate(
multiplicand,
multiplier,
accumulator,
accumulatorIndex,
) {
if (multiplier === 0) return
const m2Low = multiplier & 0x7fff
const m2High = multiplier >>> 15
let carry = 0
let high = 0
for (let i = 0; i < multiplicand.length; i++, accumulatorIndex++) {
let acc = accumulator.__digit(accumulatorIndex)
const m1 = multiplicand.__digit(i)
const m1Low = m1 & 0x7fff
const m1High = m1 >>> 15
const rLow = Math.imul(m1Low, m2Low)
const rMid1 = Math.imul(m1Low, m2High)
const rMid2 = Math.imul(m1High, m2Low)
const rHigh = Math.imul(m1High, m2High)
acc += high + rLow + carry
carry = acc >>> 30
acc &= 0x3fffffff
acc += ((rMid1 & 0x7fff) << 15) + ((rMid2 & 0x7fff) << 15)
carry += acc >>> 30
high = rHigh + (rMid1 >>> 15) + (rMid2 >>> 15)
accumulator.__setDigit(accumulatorIndex, acc & 0x3fffffff)
}
for (; carry !== 0 || high !== 0; accumulatorIndex++) {
let acc = accumulator.__digit(accumulatorIndex)
acc += carry + high
high = 0
carry = acc >>> 30
accumulator.__setDigit(accumulatorIndex, acc & 0x3fffffff)
}
}
/* Example usages of '__internalMultiplyAdd' are shown below:
// D4.
__internalMultiplyAdd(divisor, qhat, 0, n2, qhatv);
*/
function __internalMultiplyAdd(
source,
factor,
summand,
n,
result,
) {
let carry = summand
let high = 0
for (let i = 0; i < n; i++) {
const digit = source.__digit(i)
const rx = Math.imul(digit & 0x7fff, factor)
const ry = Math.imul(digit >>> 15, factor)
const r = rx + ((ry & 0x7fff) << 15) + high + carry
carry = r >>> 30
high = ry >>> 15
result.__setDigit(i, r & 0x3fffffff)
}
if (result.length > n) {
result.__setDigit(n++, carry + high)
while (n < result.length) {
result.__setDigit(n++, 0)
}
} else {
if (carry + high !== 0) throw new Error('implementation bug')
}
}
/* Example usages of '__absoluteModSmall' are shown below:
__absoluteModSmall(x, divisor);
*/
function __absoluteModSmall(x, divisor) {
let remainder = 0
for (let i = x.length * 2 - 1; i >= 0; i--) {
const input = ((remainder << 15) | x.__halfDigit(i)) >>> 0
remainder = input % divisor | 0
}
return remainder
}
function __absoluteDivLarge(
dividend,
divisor,
wantQuotient,
wantRemainder,
)
function __absoluteDivLarge(
dividend,
divisor,
wantQuotient,
wantRemainder,
)
function __absoluteDivLarge(
dividend,
divisor,
wantQuotient,
wantRemainder,
)
/* Example usages of '__absoluteDivLarge' are shown below:
__absoluteDivLarge(x, y, false, true);
*/
function __absoluteDivLarge(
dividend,
divisor,
wantQuotient,
wantRemainder,
) {
const n = divisor.__halfDigitLength()
const n2 = divisor.length
const m = dividend.__halfDigitLength() - n
let q = null
if (wantQuotient) {
q = new JSBI((m + 2) >>> 1, false)
q.__initializeDigits()
}
const qhatv = new JSBI((n + 2) >>> 1, false)
qhatv.__initializeDigits()
// D1.
const shift = __clz15(divisor.__halfDigit(n - 1))
if (shift > 0) {
divisor = __specialLeftShift(divisor, shift, 0 /* add no digits*/)
}
const u = __specialLeftShift(dividend, shift, 1 /* add one digit */)
// D2.
const vn1 = divisor.__halfDigit(n - 1)
let halfDigitBuffer = 0
for (let j = m; j >= 0; j--) {
// D3.
let qhat = 0x7fff
const ujn = u.__halfDigit(j + n)
if (ujn !== vn1) {
const input = ((ujn << 15) | u.__halfDigit(j + n - 1)) >>> 0
qhat = (input / vn1) | 0
let rhat = input % vn1 | 0
const vn2 = divisor.__halfDigit(n - 2)
const ujn2 = u.__halfDigit(j + n - 2)
while (Math.imul(qhat, vn2) >>> 0 > ((rhat << 16) | ujn2) >>> 0) {
qhat--
rhat += vn1
if (rhat > 0x7fff) break
}
}
// D4.
__internalMultiplyAdd(divisor, qhat, 0, n2, qhatv)
let c = u.__inplaceSub(qhatv, j, n + 1)
if (c !== 0) {
c = u.__inplaceAdd(divisor, j, n)
u.__setHalfDigit(j + n, (u.__halfDigit(j + n) + c) & 0x7fff)
qhat--
}
if (wantQuotient) {
if (j & 1) {
halfDigitBuffer = qhat << 15
} else {
// TODO make this statically determinable
;(q as JSBI).__setDigit(j >>> 1, halfDigitBuffer | qhat)
}
}
}
if (wantRemainder) {
u.__inplaceRightShift(shift)
if (wantQuotient) {
return { quotient: q as JSBI, remainder: u }
}
return u
}
if (wantQuotient) return q as JSBI
// TODO find a way to make this statically unreachable?
throw new Error('unreachable')
}
/* Example usages of '__clz15' are shown below:
__clz15(divisor.__halfDigit(n - 1));
*/
function __clz15(value) {
return __clz30(value) - 15
}
/* Example usages of '__specialLeftShift' are shown below:
divisor = __specialLeftShift(divisor, shift, 0 add no digits);
__specialLeftShift(dividend, shift, 1 add one digit );
*/
function __specialLeftShift(x, shift, addDigit) {
const n = x.length
const resultLength = n + addDigit
const result = new JSBI(resultLength, false)
if (shift === 0) {
for (let i = 0; i < n; i++) result.__setDigit(i, x.__digit(i))
if (addDigit > 0) result.__setDigit(n, 0)
return result
}
let carry = 0
for (let i = 0; i < n; i++) {
const d = x.__digit(i)
result.__setDigit(i, ((d << shift) & 0x3fffffff) | carry)
carry = d >>> (30 - shift)
}
if (addDigit > 0) {
result.__setDigit(n, carry)
}
return result
}
/* Example usages of '__clz30' are shown below:
__clz30(xMsd);
__clz30(this.__digit(this.length - 1));
__clz30(value) - 15;
*/
function __clz30(x) {
return Math.clz32(x) - 2
}
const __kBitConversionBuffer = /*#__PURE__*/ new ArrayBuffer(8)
const __kBitConversionDouble = /*#__PURE__*/ new Float64Array(
__kBitConversionBuffer,
)
const __kBitConversionInts = /*#__PURE__*/ new Int32Array(
__kBitConversionBuffer,
)
|
3e5bf378149f759dc9a3ce50ed8873fbe379b393 | 5,928 | ts | TypeScript | packages/relayer/src/errors.ts | pokt-foundation/pocket-js-slim | aac01db6204f1b234144801f63614f63ce850de9 | [
"MIT"
] | 1 | 2022-02-03T00:11:08.000Z | 2022-02-03T00:11:08.000Z | packages/relayer/src/errors.ts | pokt-foundation/pocket-js-slim | aac01db6204f1b234144801f63614f63ce850de9 | [
"MIT"
] | 17 | 2022-02-24T18:38:06.000Z | 2022-03-30T20:31:41.000Z | packages/relayer/src/errors.ts | pokt-foundation/pocket-js-slim | aac01db6204f1b234144801f63614f63ce850de9 | [
"MIT"
] | null | null | null | export class ServiceNodeNotInSessionError extends Error {
constructor(message: string, ...params: any[]) {
super(...params)
this.message = message
this.name = 'ServiceNodeNotInSessionError'
}
}
export class EmptyKeyManagerError extends Error {
constructor(message: string, ...params: any[]) {
super(...params)
this.message = message
this.name = 'EmptyKeyManagerError'
}
}
export class NoServiceNodeError extends Error {
constructor(message: string, ...params: any[]) {
super(...params)
this.message = message
this.name = 'NoServiceNodeError'
}
}
export enum PocketCoreErrorCodes {
AppNotFoundError = 45,
DuplicateProofError = 37,
EmptyPayloadDataError = 25,
EvidenceSealedError = 90,
HTTPExecutionError = 28,
InvalidBlockHeightError = 60,
InvalidSessionError = 14,
OutOfSyncRequestError = 75,
OverServiceError = 71,
RequestHashError = 74,
UnsupportedBlockchainError = 76,
}
export class PocketCoreError extends Error {
code: number
message: string
constructor(code: number, message: string, ...params: any[]) {
super(...params)
this.code = code
this.message = message
}
}
export class EmptyPayloadDataError extends PocketCoreError {
constructor(code: number, message: string, ...params: any[]) {
super(code, message, ...params)
this.name = 'EmptyPayloadError'
}
}
export class RequestHashError extends PocketCoreError {
constructor(code: number, message: string, ...params: any[]) {
super(code, message, ...params)
this.name = 'RequestHashError'
}
}
export class UnsupportedBlockchainError extends PocketCoreError {
constructor(code: number, message: string, ...params: any[]) {
super(code, message, ...params)
this.name = 'UnsupportedBlockchainError'
}
}
export class InvalidBlockHeightError extends PocketCoreError {
constructor(code: number, message: string, ...params: any[]) {
super(code, message, ...params)
this.name = 'InvalidBlockHeightError'
}
}
export class InvalidSessionError extends PocketCoreError {
constructor(code: number, message: string, ...params: any[]) {
super(code, message, ...params)
this.name = 'InvalidSessionError'
}
}
export class AppNotFoundError extends PocketCoreError {
constructor(code: number, message: string, ...params: any[]) {
super(code, message, ...params)
this.name = 'AppNotFoundError'
}
}
export class EvidenceSealedError extends PocketCoreError {
constructor(code: number, message: string, ...params: any[]) {
super(code, message, ...params)
this.name = 'EvidenceSealedError'
}
}
export class DuplicateProofError extends PocketCoreError {
constructor(code: number, message: string, ...params: any[]) {
super(code, message, ...params)
this.name = 'DuplicateProofError'
}
}
export class OutOfSyncRequestError extends PocketCoreError {
constructor(code: number, message: string, ...params: any[]) {
super(code, message, ...params)
this.name = 'OutOfSyncRequestError'
}
}
export class OverServiceError extends PocketCoreError {
constructor(code: number, message: string, ...params: any[]) {
super(code, message, ...params)
this.name = 'OverServiceError'
}
}
export class HTTPExecutionError extends PocketCoreError {
constructor(code: number, message: string, ...params: any[]) {
super(code, message, ...params)
this.name = 'HTTPExecutionError'
}
}
export function validateRelayResponse(relayResponse: any) {
if ('response' in relayResponse && 'signature' in relayResponse) {
return relayResponse.response
}
// probably an unhandled error
if (!('response' in relayResponse) && !('error' in relayResponse)) {
return relayResponse
}
switch (relayResponse.error.code) {
case PocketCoreErrorCodes.AppNotFoundError:
throw new AppNotFoundError(
PocketCoreErrorCodes.AppNotFoundError,
relayResponse.error.message ?? ''
)
case PocketCoreErrorCodes.DuplicateProofError:
throw new DuplicateProofError(
PocketCoreErrorCodes.DuplicateProofError,
relayResponse.error.message
)
case PocketCoreErrorCodes.EmptyPayloadDataError:
throw new EmptyPayloadDataError(
PocketCoreErrorCodes.EmptyPayloadDataError,
relayResponse.error.message
)
case PocketCoreErrorCodes.EvidenceSealedError:
throw new EvidenceSealedError(
PocketCoreErrorCodes.EvidenceSealedError,
relayResponse.error.message
)
case PocketCoreErrorCodes.InvalidBlockHeightError:
throw new InvalidBlockHeightError(
PocketCoreErrorCodes.InvalidBlockHeightError,
relayResponse.error.message
)
case PocketCoreErrorCodes.OutOfSyncRequestError:
throw new OutOfSyncRequestError(
PocketCoreErrorCodes.OutOfSyncRequestError,
relayResponse.error.message
)
case PocketCoreErrorCodes.OverServiceError:
throw new OverServiceError(
PocketCoreErrorCodes.OverServiceError,
relayResponse.error.message
)
case PocketCoreErrorCodes.RequestHashError:
throw new RequestHashError(
PocketCoreErrorCodes.RequestHashError,
relayResponse.error.message
)
case PocketCoreErrorCodes.UnsupportedBlockchainError:
throw new UnsupportedBlockchainError(
PocketCoreErrorCodes.UnsupportedBlockchainError,
relayResponse.error.message
)
case PocketCoreErrorCodes.HTTPExecutionError:
throw new HTTPExecutionError(
PocketCoreErrorCodes.HTTPExecutionError,
relayResponse.error.message
)
case PocketCoreErrorCodes.InvalidSessionError:
throw new InvalidSessionError(
PocketCoreErrorCodes.InvalidSessionError,
relayResponse.error.message
)
default:
throw new PocketCoreError(
relayResponse.error.code,
relayResponse.error.message ?? ''
)
}
}
| 29.64 | 70 | 0.712045 | 179 | 16 | 0 | 43 | 0 | 2 | 0 | 16 | 29 | 15 | 0 | 6.375 | 1,449 | 0.040718 | 0 | 0.00138 | 0.010352 | 0 | 0.262295 | 0.47541 | 0.277247 | export class ServiceNodeNotInSessionError extends Error {
constructor(message, ...params) {
super(...params)
this.message = message
this.name = 'ServiceNodeNotInSessionError'
}
}
export class EmptyKeyManagerError extends Error {
constructor(message, ...params) {
super(...params)
this.message = message
this.name = 'EmptyKeyManagerError'
}
}
export class NoServiceNodeError extends Error {
constructor(message, ...params) {
super(...params)
this.message = message
this.name = 'NoServiceNodeError'
}
}
export enum PocketCoreErrorCodes {
AppNotFoundError = 45,
DuplicateProofError = 37,
EmptyPayloadDataError = 25,
EvidenceSealedError = 90,
HTTPExecutionError = 28,
InvalidBlockHeightError = 60,
InvalidSessionError = 14,
OutOfSyncRequestError = 75,
OverServiceError = 71,
RequestHashError = 74,
UnsupportedBlockchainError = 76,
}
export class PocketCoreError extends Error {
code
message
constructor(code, message, ...params) {
super(...params)
this.code = code
this.message = message
}
}
export class EmptyPayloadDataError extends PocketCoreError {
constructor(code, message, ...params) {
super(code, message, ...params)
this.name = 'EmptyPayloadError'
}
}
export class RequestHashError extends PocketCoreError {
constructor(code, message, ...params) {
super(code, message, ...params)
this.name = 'RequestHashError'
}
}
export class UnsupportedBlockchainError extends PocketCoreError {
constructor(code, message, ...params) {
super(code, message, ...params)
this.name = 'UnsupportedBlockchainError'
}
}
export class InvalidBlockHeightError extends PocketCoreError {
constructor(code, message, ...params) {
super(code, message, ...params)
this.name = 'InvalidBlockHeightError'
}
}
export class InvalidSessionError extends PocketCoreError {
constructor(code, message, ...params) {
super(code, message, ...params)
this.name = 'InvalidSessionError'
}
}
export class AppNotFoundError extends PocketCoreError {
constructor(code, message, ...params) {
super(code, message, ...params)
this.name = 'AppNotFoundError'
}
}
export class EvidenceSealedError extends PocketCoreError {
constructor(code, message, ...params) {
super(code, message, ...params)
this.name = 'EvidenceSealedError'
}
}
export class DuplicateProofError extends PocketCoreError {
constructor(code, message, ...params) {
super(code, message, ...params)
this.name = 'DuplicateProofError'
}
}
export class OutOfSyncRequestError extends PocketCoreError {
constructor(code, message, ...params) {
super(code, message, ...params)
this.name = 'OutOfSyncRequestError'
}
}
export class OverServiceError extends PocketCoreError {
constructor(code, message, ...params) {
super(code, message, ...params)
this.name = 'OverServiceError'
}
}
export class HTTPExecutionError extends PocketCoreError {
constructor(code, message, ...params) {
super(code, message, ...params)
this.name = 'HTTPExecutionError'
}
}
export function validateRelayResponse(relayResponse) {
if ('response' in relayResponse && 'signature' in relayResponse) {
return relayResponse.response
}
// probably an unhandled error
if (!('response' in relayResponse) && !('error' in relayResponse)) {
return relayResponse
}
switch (relayResponse.error.code) {
case PocketCoreErrorCodes.AppNotFoundError:
throw new AppNotFoundError(
PocketCoreErrorCodes.AppNotFoundError,
relayResponse.error.message ?? ''
)
case PocketCoreErrorCodes.DuplicateProofError:
throw new DuplicateProofError(
PocketCoreErrorCodes.DuplicateProofError,
relayResponse.error.message
)
case PocketCoreErrorCodes.EmptyPayloadDataError:
throw new EmptyPayloadDataError(
PocketCoreErrorCodes.EmptyPayloadDataError,
relayResponse.error.message
)
case PocketCoreErrorCodes.EvidenceSealedError:
throw new EvidenceSealedError(
PocketCoreErrorCodes.EvidenceSealedError,
relayResponse.error.message
)
case PocketCoreErrorCodes.InvalidBlockHeightError:
throw new InvalidBlockHeightError(
PocketCoreErrorCodes.InvalidBlockHeightError,
relayResponse.error.message
)
case PocketCoreErrorCodes.OutOfSyncRequestError:
throw new OutOfSyncRequestError(
PocketCoreErrorCodes.OutOfSyncRequestError,
relayResponse.error.message
)
case PocketCoreErrorCodes.OverServiceError:
throw new OverServiceError(
PocketCoreErrorCodes.OverServiceError,
relayResponse.error.message
)
case PocketCoreErrorCodes.RequestHashError:
throw new RequestHashError(
PocketCoreErrorCodes.RequestHashError,
relayResponse.error.message
)
case PocketCoreErrorCodes.UnsupportedBlockchainError:
throw new UnsupportedBlockchainError(
PocketCoreErrorCodes.UnsupportedBlockchainError,
relayResponse.error.message
)
case PocketCoreErrorCodes.HTTPExecutionError:
throw new HTTPExecutionError(
PocketCoreErrorCodes.HTTPExecutionError,
relayResponse.error.message
)
case PocketCoreErrorCodes.InvalidSessionError:
throw new InvalidSessionError(
PocketCoreErrorCodes.InvalidSessionError,
relayResponse.error.message
)
default:
throw new PocketCoreError(
relayResponse.error.code,
relayResponse.error.message ?? ''
)
}
}
|
3ebef66f9a10d6d90633f541a4566149e3e767e5 | 1,576 | ts | TypeScript | src/utils/time.ts | simonostendorf/ultimateboteu | 6922778e586c45c9283347d5b05ed6ab4ce3901c | [
"MIT"
] | null | null | null | src/utils/time.ts | simonostendorf/ultimateboteu | 6922778e586c45c9283347d5b05ed6ab4ce3901c | [
"MIT"
] | 10 | 2022-02-08T23:40:09.000Z | 2022-03-29T05:30:51.000Z | src/utils/time.ts | simonostendorf/ultimateboteu | 6922778e586c45c9283347d5b05ed6ab4ce3901c | [
"MIT"
] | 1 | 2022-02-08T23:09:18.000Z | 2022-02-08T23:09:18.000Z | let startTime = 0;
export function millisToString(millis: number, printMillis: boolean): string {
const days = Math.floor(millis / 86400000);
millis %= 86400000;
const hours = Math.floor(millis / 3600000);
millis %= 3600000;
const minutes = Math.floor(millis / 60000);
millis %= 60000;
const seconds = Math.floor(millis / 1000);
millis %= 1000;
let output = '';
let inserted = false;
if (days > 0) {
output += days + ' Tag';
if (days > 1) {
output += 'e';
}
inserted = true;
}
if (hours > 0) {
if (inserted) {
inserted = false;
output += ' ';
}
output += hours + ' Stunde';
if (hours > 1) {
output += 'n';
}
inserted = true;
}
if (minutes > 0) {
if (inserted) {
inserted = false;
output += ' ';
}
output += minutes + ' Minute';
if (minutes > 1) {
output += 'n';
}
inserted = true;
}
if (seconds > 0) {
if (inserted) {
inserted = false;
output += ' ';
}
output += seconds + ' Sekunde';
if (seconds > 1) {
output += 'n';
}
inserted = true;
}
if (printMillis) {
if (millis > 0) {
if (inserted) {
inserted = false;
output += ' ';
}
output += millis + ' Millisekunde';
if (millis > 1) {
output += 'n';
}
}
}
return output;
}
export function setStartTime() {
startTime = Date.now();
}
export function getStartTime(): number {
return startTime;
}
export function getUptime(): number {
return Date.now() - startTime;
} | 18.987952 | 78 | 0.521574 | 75 | 4 | 0 | 2 | 7 | 0 | 0 | 0 | 5 | 0 | 0 | 16.5 | 500 | 0.012 | 0.014 | 0 | 0 | 0 | 0 | 0.384615 | 0.2434 | let startTime = 0;
export function millisToString(millis, printMillis) {
const days = Math.floor(millis / 86400000);
millis %= 86400000;
const hours = Math.floor(millis / 3600000);
millis %= 3600000;
const minutes = Math.floor(millis / 60000);
millis %= 60000;
const seconds = Math.floor(millis / 1000);
millis %= 1000;
let output = '';
let inserted = false;
if (days > 0) {
output += days + ' Tag';
if (days > 1) {
output += 'e';
}
inserted = true;
}
if (hours > 0) {
if (inserted) {
inserted = false;
output += ' ';
}
output += hours + ' Stunde';
if (hours > 1) {
output += 'n';
}
inserted = true;
}
if (minutes > 0) {
if (inserted) {
inserted = false;
output += ' ';
}
output += minutes + ' Minute';
if (minutes > 1) {
output += 'n';
}
inserted = true;
}
if (seconds > 0) {
if (inserted) {
inserted = false;
output += ' ';
}
output += seconds + ' Sekunde';
if (seconds > 1) {
output += 'n';
}
inserted = true;
}
if (printMillis) {
if (millis > 0) {
if (inserted) {
inserted = false;
output += ' ';
}
output += millis + ' Millisekunde';
if (millis > 1) {
output += 'n';
}
}
}
return output;
}
export function setStartTime() {
startTime = Date.now();
}
export function getStartTime() {
return startTime;
}
export function getUptime() {
return Date.now() - startTime;
} |
241328cdeb997b32e1bc6ca0ce95d2a9da574bad | 3,001 | ts | TypeScript | src/plugins/dexie/query/pouchdb-find-query-planer/main-utils.ts | bitsnaps/rxdb | f21ccf71d71096a8ded237fcc619c4de2ae44995 | [
"Apache-2.0"
] | 1 | 2022-02-28T00:33:02.000Z | 2022-02-28T00:33:02.000Z | src/plugins/dexie/query/pouchdb-find-query-planer/main-utils.ts | bitsnaps/rxdb | f21ccf71d71096a8ded237fcc619c4de2ae44995 | [
"Apache-2.0"
] | null | null | null | src/plugins/dexie/query/pouchdb-find-query-planer/main-utils.ts | bitsnaps/rxdb | f21ccf71d71096a8ded237fcc619c4de2ae44995 | [
"Apache-2.0"
] | null | null | null |
function getArguments(fun: any) {
return function () {
const len = arguments.length;
const args = new Array(len);
let i = -1;
while (++i < len) {
args[i] = arguments[i];
}
const ret = fun.call(undefined, args);
return ret;
};
}
export const flatten = getArguments(function (args: any) {
let res: any[] = [];
for (let i = 0, len = args.length; i < len; i++) {
const subArr: any = args[i] as any;
if (Array.isArray(subArr)) {
res = res.concat(flatten.apply(null, subArr as any));
} else {
res.push(subArr);
}
}
return res;
});
export function mergeObjects(arr: any[]) {
let res = {};
for (let i = 0, len = arr.length; i < len; i++) {
res = Object.assign(res, arr[i]);
}
return res;
}
// e.g. ['a'], ['a', 'b'] is true, but ['b'], ['a', 'b'] is false
export function oneArrayIsSubArrayOfOther(left: any, right: any) {
for (let i = 0, len = Math.min(left.length, right.length); i < len; i++) {
if (left[i] !== right[i]) {
return false;
}
}
return true;
}
// e.g.['a', 'b', 'c'], ['a', 'b'] is false
export function oneArrayIsStrictSubArrayOfOther(left: any, right: any) {
if (left.length > right.length) {
return false;
}
return oneArrayIsSubArrayOfOther(left, right);
}
// same as above, but treat the left array as an unordered set
// e.g. ['b', 'a'], ['a', 'b', 'c'] is true, but ['c'], ['a', 'b', 'c'] is false
export function oneSetIsSubArrayOfOther(left: any, right: any) {
left = left.slice();
for (let i = 0, len = right.length; i < len; i++) {
const field = right[i];
if (!left.length) {
break;
}
const leftIdx = left.indexOf(field);
if (leftIdx === -1) {
return false;
} else {
left.splice(leftIdx, 1);
}
}
return true;
}
export function arrayToObject(arr: any[]) {
const res: any = {};
for (let i = 0, len = arr.length; i < len; i++) {
res[arr[i]] = true;
}
return res;
}
export function max(arr: any[], fun: Function) {
let max = null;
let maxScore = -1;
for (let i = 0, len = arr.length; i < len; i++) {
const element = arr[i];
const score = fun(element);
if (score > maxScore) {
maxScore = score;
max = element;
}
}
return max;
}
export function arrayEquals(arr1: any[], arr2: any[]) {
if (arr1.length !== arr2.length) {
return false;
}
for (let i = 0, len = arr1.length; i < len; i++) {
if (arr1[i] !== arr2[i]) {
return false;
}
}
return true;
}
export function uniq(arr: any[]) {
const obj: any = {};
for (let i = 0; i < arr.length; i++) {
obj['$' + arr[i]] = true;
}
return Object.keys(obj).map(function (key) {
return key.substring(1);
});
}
| 25.432203 | 80 | 0.505498 | 101 | 12 | 0 | 16 | 31 | 0 | 2 | 21 | 0 | 0 | 2 | 7.5 | 931 | 0.030075 | 0.033298 | 0 | 0 | 0.002148 | 0.355932 | 0 | 0.343756 |
/* Example usages of 'getArguments' are shown below:
getArguments(function (args) {
let res = [];
for (let i = 0, len = args.length; i < len; i++) {
const subArr = args[i] as any;
if (Array.isArray(subArr)) {
res = res.concat(flatten.apply(null, subArr as any));
}
else {
res.push(subArr);
}
}
return res;
});
*/
function getArguments(fun) {
return function () {
const len = arguments.length;
const args = new Array(len);
let i = -1;
while (++i < len) {
args[i] = arguments[i];
}
const ret = fun.call(undefined, args);
return ret;
};
}
export const flatten = getArguments(function (args) {
let res = [];
for (let i = 0, len = args.length; i < len; i++) {
const subArr = args[i] as any;
if (Array.isArray(subArr)) {
res = res.concat(flatten.apply(null, subArr as any));
} else {
res.push(subArr);
}
}
return res;
});
export function mergeObjects(arr) {
let res = {};
for (let i = 0, len = arr.length; i < len; i++) {
res = Object.assign(res, arr[i]);
}
return res;
}
// e.g. ['a'], ['a', 'b'] is true, but ['b'], ['a', 'b'] is false
export /* Example usages of 'oneArrayIsSubArrayOfOther' are shown below:
oneArrayIsSubArrayOfOther(left, right);
*/
function oneArrayIsSubArrayOfOther(left, right) {
for (let i = 0, len = Math.min(left.length, right.length); i < len; i++) {
if (left[i] !== right[i]) {
return false;
}
}
return true;
}
// e.g.['a', 'b', 'c'], ['a', 'b'] is false
export function oneArrayIsStrictSubArrayOfOther(left, right) {
if (left.length > right.length) {
return false;
}
return oneArrayIsSubArrayOfOther(left, right);
}
// same as above, but treat the left array as an unordered set
// e.g. ['b', 'a'], ['a', 'b', 'c'] is true, but ['c'], ['a', 'b', 'c'] is false
export function oneSetIsSubArrayOfOther(left, right) {
left = left.slice();
for (let i = 0, len = right.length; i < len; i++) {
const field = right[i];
if (!left.length) {
break;
}
const leftIdx = left.indexOf(field);
if (leftIdx === -1) {
return false;
} else {
left.splice(leftIdx, 1);
}
}
return true;
}
export function arrayToObject(arr) {
const res = {};
for (let i = 0, len = arr.length; i < len; i++) {
res[arr[i]] = true;
}
return res;
}
export /* Example usages of 'max' are shown below:
var max = null;
max = element;
return max;
*/
function max(arr, fun) {
let max = null;
let maxScore = -1;
for (let i = 0, len = arr.length; i < len; i++) {
const element = arr[i];
const score = fun(element);
if (score > maxScore) {
maxScore = score;
max = element;
}
}
return max;
}
export function arrayEquals(arr1, arr2) {
if (arr1.length !== arr2.length) {
return false;
}
for (let i = 0, len = arr1.length; i < len; i++) {
if (arr1[i] !== arr2[i]) {
return false;
}
}
return true;
}
export function uniq(arr) {
const obj = {};
for (let i = 0; i < arr.length; i++) {
obj['$' + arr[i]] = true;
}
return Object.keys(obj).map(function (key) {
return key.substring(1);
});
}
|
2462b9dd6f4fcdf37c2d9579f271624075475620 | 3,492 | ts | TypeScript | packages/generate-password/index.ts | ZxBing0066/zlib | 56fbf1c8e2dbc878d2e0b3ac1234afdc41fdfd79 | [
"MIT"
] | 4 | 2022-01-10T02:34:14.000Z | 2022-01-14T02:59:17.000Z | packages/generate-password/index.ts | ZxBing0066/zlib | 56fbf1c8e2dbc878d2e0b3ac1234afdc41fdfd79 | [
"MIT"
] | 1 | 2022-03-10T07:45:07.000Z | 2022-03-12T01:50:50.000Z | packages/generate-password/index.ts | ZxBing0066/zlib | 56fbf1c8e2dbc878d2e0b3ac1234afdc41fdfd79 | [
"MIT"
] | null | null | null | // exclude `l`, `o`
const DefaultLowerCaseChars = 'abcdefghijkmnpqrstuvwxyz';
// exclude 'I', 'O'
const DefaultUpperCaseChars = 'ABCDEFGHJKLMNPQRSTUVWXYZ';
// exclude '1'
const DefaultDigits = '23456789';
// symbols
const DefaultSymbols = '-_.:!';
// sequences of '-' or '_' will change to long strokes in many fonts, that will make the password difficult to read
const isDifficultToRead = (password: string) => /[_]{2}|[\-]{2}/.test(password);
const randomIndex = (max: number) => Math.floor(Math.random() * max);
const randomPick = (collection: string | string[]) => collection[randomIndex(collection.length)];
const shuffle = (passwordChars: string[], l = passwordChars.length, remainingTimes = 0) => {
const r = passwordChars.length;
for (let i = 0; i < l; i++) {
const randomI = randomIndex(r);
const tmp = passwordChars[i];
passwordChars[i] = passwordChars[randomI];
passwordChars[randomI] = tmp;
}
if (remainingTimes > 0) shuffle(passwordChars, l, remainingTimes - 1);
};
const passwordGenerate = ({
length: passwordLength = 15,
symbols: Symbols,
digits: Digits = DefaultDigits,
lowerCaseChars: LowerCaseChars = DefaultLowerCaseChars,
upperCaseChars: UpperCaseChars = DefaultUpperCaseChars,
customChars: CustomChars,
shuffleTimes = 1
}: {
/** length of the password, pass a [min, max] as length range */
length?: number | [number, number];
/** custom your symbol collection */
symbols?: string | true;
/** custom your digit collection */
digits?: string;
/** custom your lowercase char collection */
lowerCaseChars?: string;
/** custom your uppercase char collection */
upperCaseChars?: string;
/** add your own char collection */
customChars?: string;
/** the number of do shuffle */
shuffleTimes?: number;
} = {}) => {
if (Array.isArray(passwordLength)) {
const [min, max] = passwordLength;
if (!min || !max || max < min || min < 5 || max > 99)
throw new Error(`Invalid passwordLength: ${JSON.stringify(passwordLength)}`);
passwordLength = min + randomIndex(max - min + 1);
}
if (passwordLength < 5 || passwordLength > 99) throw new Error(`Invalid passwordLength: ${passwordLength}`);
if (Symbols === true) Symbols = DefaultSymbols;
const passwordChars = [];
const allCollections: string[] = [];
[LowerCaseChars, UpperCaseChars, Digits, Symbols, CustomChars].forEach(
collection => collection?.length && allCollections.push(collection)
);
if (!allCollections.length) throw new Error(`Invalid options without any char for generate password`);
const al = allCollections.length;
for (let i = 0; i < al; i++) {
passwordChars.push(randomPick(allCollections[i]));
}
const restCount = passwordLength - passwordChars.length;
const fullCollection = allCollections.join('');
for (let i = 0; i < restCount; i++) {
passwordChars.push(randomPick(fullCollection));
}
shuffle(passwordChars, al);
if (shuffleTimes > 0) shuffle(passwordChars, passwordLength, shuffleTimes - 1);
const needCheckReadAbility = fullCollection.indexOf('_') >= 0 || fullCollection.indexOf('-') >= 0;
let remainingAttempts = 5;
while (needCheckReadAbility && isDifficultToRead(passwordChars.join('')) && remainingAttempts--) {
shuffle(passwordChars);
}
return passwordChars.join('');
};
export default passwordGenerate;
| 37.956522 | 115 | 0.662944 | 67 | 6 | 0 | 8 | 23 | 0 | 4 | 0 | 15 | 0 | 0 | 7.166667 | 886 | 0.015801 | 0.025959 | 0 | 0 | 0 | 0 | 0.405405 | 0.292335 | // exclude `l`, `o`
const DefaultLowerCaseChars = 'abcdefghijkmnpqrstuvwxyz';
// exclude 'I', 'O'
const DefaultUpperCaseChars = 'ABCDEFGHJKLMNPQRSTUVWXYZ';
// exclude '1'
const DefaultDigits = '23456789';
// symbols
const DefaultSymbols = '-_.:!';
// sequences of '-' or '_' will change to long strokes in many fonts, that will make the password difficult to read
/* Example usages of 'isDifficultToRead' are shown below:
needCheckReadAbility && isDifficultToRead(passwordChars.join('')) && remainingAttempts--;
*/
const isDifficultToRead = (password) => /[_]{2}|[\-]{2}/.test(password);
/* Example usages of 'randomIndex' are shown below:
collection[randomIndex(collection.length)];
randomIndex(r);
passwordLength = min + randomIndex(max - min + 1);
*/
const randomIndex = (max) => Math.floor(Math.random() * max);
/* Example usages of 'randomPick' are shown below:
passwordChars.push(randomPick(allCollections[i]));
passwordChars.push(randomPick(fullCollection));
*/
const randomPick = (collection) => collection[randomIndex(collection.length)];
/* Example usages of 'shuffle' are shown below:
shuffle(passwordChars, l, remainingTimes - 1);
shuffle(passwordChars, al);
shuffle(passwordChars, passwordLength, shuffleTimes - 1);
shuffle(passwordChars);
*/
const shuffle = (passwordChars, l = passwordChars.length, remainingTimes = 0) => {
const r = passwordChars.length;
for (let i = 0; i < l; i++) {
const randomI = randomIndex(r);
const tmp = passwordChars[i];
passwordChars[i] = passwordChars[randomI];
passwordChars[randomI] = tmp;
}
if (remainingTimes > 0) shuffle(passwordChars, l, remainingTimes - 1);
};
/* Example usages of 'passwordGenerate' are shown below:
;
*/
const passwordGenerate = ({
length: passwordLength = 15,
symbols: Symbols,
digits: Digits = DefaultDigits,
lowerCaseChars: LowerCaseChars = DefaultLowerCaseChars,
upperCaseChars: UpperCaseChars = DefaultUpperCaseChars,
customChars: CustomChars,
shuffleTimes = 1
} = {}) => {
if (Array.isArray(passwordLength)) {
const [min, max] = passwordLength;
if (!min || !max || max < min || min < 5 || max > 99)
throw new Error(`Invalid passwordLength: ${JSON.stringify(passwordLength)}`);
passwordLength = min + randomIndex(max - min + 1);
}
if (passwordLength < 5 || passwordLength > 99) throw new Error(`Invalid passwordLength: ${passwordLength}`);
if (Symbols === true) Symbols = DefaultSymbols;
const passwordChars = [];
const allCollections = [];
[LowerCaseChars, UpperCaseChars, Digits, Symbols, CustomChars].forEach(
collection => collection?.length && allCollections.push(collection)
);
if (!allCollections.length) throw new Error(`Invalid options without any char for generate password`);
const al = allCollections.length;
for (let i = 0; i < al; i++) {
passwordChars.push(randomPick(allCollections[i]));
}
const restCount = passwordLength - passwordChars.length;
const fullCollection = allCollections.join('');
for (let i = 0; i < restCount; i++) {
passwordChars.push(randomPick(fullCollection));
}
shuffle(passwordChars, al);
if (shuffleTimes > 0) shuffle(passwordChars, passwordLength, shuffleTimes - 1);
const needCheckReadAbility = fullCollection.indexOf('_') >= 0 || fullCollection.indexOf('-') >= 0;
let remainingAttempts = 5;
while (needCheckReadAbility && isDifficultToRead(passwordChars.join('')) && remainingAttempts--) {
shuffle(passwordChars);
}
return passwordChars.join('');
};
export default passwordGenerate;
|
24c8679a54aa8d683698c7b4de74d262fde12731 | 2,553 | ts | TypeScript | src/shared/provider/response-provider.ts | arifwidianto08/ngulik-nestjs-graphql | 1068f1ee454ee34ba12e43f0e90d519507c81928 | [
"MIT"
] | 1 | 2022-03-13T17:06:27.000Z | 2022-03-13T17:06:27.000Z | src/shared/provider/response-provider.ts | arifwidianto08/ngulik-nestjs-graphql | 1068f1ee454ee34ba12e43f0e90d519507c81928 | [
"MIT"
] | null | null | null | src/shared/provider/response-provider.ts | arifwidianto08/ngulik-nestjs-graphql | 1068f1ee454ee34ba12e43f0e90d519507c81928 | [
"MIT"
] | null | null | null | // eslint-disable-next-line @typescript-eslint/ban-types
export interface CustomResponse<T = {}> {
data: T;
meta: {
message?: string;
statusCode?: number;
page?: number | string;
perPage?: number | string;
totalPage?: number | string;
totalData?: number | string;
isEmailChanged?: boolean;
isPhoneNumberChanged?: boolean;
};
}
export class OkResponse<T> implements CustomResponse<T> {
meta: {
message: string;
statusCode: number;
page?: number | string;
perPage?: number | string;
totalPage?: number | string;
totalData?: number | string;
};
data: T;
constructor(data: T, meta?: CustomResponse<T>["meta"], statusCode?: number) {
this.data = data;
if (Array.isArray(data)) {
this.meta = {
...meta,
message:
(meta && meta.message) || "Data successfully retrieved/transmitted!",
statusCode: 200,
totalData: (meta && meta.totalData) || 0,
page: (meta && Number(meta.page)) || 1,
perPage: (meta && Number(meta.perPage)) || 10,
totalPage: Math.ceil(
((meta && Number(meta.totalData)) || 1) /
(meta && meta.perPage ? Number(meta.perPage) : 10),
),
};
} else {
this.meta = {
...meta,
message:
(meta && meta.message) || "Data successfully retrieved/transmitted!",
statusCode: statusCode || 200,
};
}
}
}
export class CreateDataResponse<T> implements CustomResponse<T> {
meta: {
message?: string;
statusCode?: number;
} = {};
data: T;
constructor(data: T, meta?: CustomResponse<T>["meta"], statusCode?: number) {
this.data = data;
this.meta = {
...meta,
message: (meta && meta.message) || "Data successfully created!",
statusCode: statusCode || 201,
};
}
}
export class UpdateDataResponse<T> implements CustomResponse<T> {
meta: {
message: string;
statusCode: number;
};
data: T;
constructor(data: T, meta?: CustomResponse<T>["meta"], statusCode?: number) {
this.data = data;
this.meta = {
...meta,
message: (meta && meta.message) || "Data successfully updated!",
statusCode: statusCode || 200,
};
}
}
export class DeleteDataResponse<T> implements CustomResponse<T> {
meta: {
message: string;
statusCode?: number;
page?: number | string;
perPage?: number | string;
totalPage?: number | string;
totalData?: number | string;
};
data: T;
constructor(data: T, meta?: CustomResponse<T>["meta"], statusCode?: number) {
this.data = data;
this.meta = {
...meta,
message: (meta && meta.message) || "Data successfully deleted!",
statusCode: statusCode || 200,
};
}
}
| 24.314286 | 78 | 0.633373 | 98 | 4 | 0 | 12 | 0 | 10 | 0 | 0 | 40 | 5 | 0 | 10.25 | 838 | 0.019093 | 0 | 0.011933 | 0.005967 | 0 | 0 | 1.538462 | 0.222373 | // eslint-disable-next-line @typescript-eslint/ban-types
export interface CustomResponse<T = {}> {
data;
meta;
}
export class OkResponse<T> implements CustomResponse<T> {
meta;
data;
constructor(data, meta?, statusCode?) {
this.data = data;
if (Array.isArray(data)) {
this.meta = {
...meta,
message:
(meta && meta.message) || "Data successfully retrieved/transmitted!",
statusCode: 200,
totalData: (meta && meta.totalData) || 0,
page: (meta && Number(meta.page)) || 1,
perPage: (meta && Number(meta.perPage)) || 10,
totalPage: Math.ceil(
((meta && Number(meta.totalData)) || 1) /
(meta && meta.perPage ? Number(meta.perPage) : 10),
),
};
} else {
this.meta = {
...meta,
message:
(meta && meta.message) || "Data successfully retrieved/transmitted!",
statusCode: statusCode || 200,
};
}
}
}
export class CreateDataResponse<T> implements CustomResponse<T> {
meta = {};
data;
constructor(data, meta?, statusCode?) {
this.data = data;
this.meta = {
...meta,
message: (meta && meta.message) || "Data successfully created!",
statusCode: statusCode || 201,
};
}
}
export class UpdateDataResponse<T> implements CustomResponse<T> {
meta;
data;
constructor(data, meta?, statusCode?) {
this.data = data;
this.meta = {
...meta,
message: (meta && meta.message) || "Data successfully updated!",
statusCode: statusCode || 200,
};
}
}
export class DeleteDataResponse<T> implements CustomResponse<T> {
meta;
data;
constructor(data, meta?, statusCode?) {
this.data = data;
this.meta = {
...meta,
message: (meta && meta.message) || "Data successfully deleted!",
statusCode: statusCode || 200,
};
}
}
|
24eda59054d0e1ab1fda5ee0f622980b57fd60ec | 1,319 | ts | TypeScript | src/index.ts | barelyhuman/availability-bitmap | 2e7a6efc68b48f1cbd883da4d9336c78f938c931 | [
"MIT"
] | null | null | null | src/index.ts | barelyhuman/availability-bitmap | 2e7a6efc68b48f1cbd883da4d9336c78f938c931 | [
"MIT"
] | 1 | 2022-03-13T16:05:04.000Z | 2022-03-13T16:05:04.000Z | src/index.ts | barelyhuman/availability-bitmap | 2e7a6efc68b48f1cbd883da4d9336c78f938c931 | [
"MIT"
] | null | null | null | function _minOfDay(date: Date) {
const d = new Date(date);
const hour = d.getHours();
const min = d.getMinutes();
const minOfDay = hour * 60 + min;
return minOfDay;
}
function _timeFromMinOfDay(minOfDay: number) {
const hour = Math.floor((minOfDay - 0) / 60);
const min = minOfDay % 60;
return new Date(new Date().setHours(hour, min));
}
function blockTime(start: Date, end: Date) {
const ctx = this || {};
const startMap = _minOfDay(new Date(start));
const endMap = _minOfDay(new Date(end));
for (let i = startMap; i < endMap; i += 1) {
if (ctx.__rmap[i] === 1) {
return false;
}
ctx.__rmap[i] = 1;
}
return true;
}
function nextAvailableFrom(date: Date, minCount: number) {
const ctx = this || {};
const startMap = _minOfDay(date);
let count = 0;
let point = 0;
for (let i = startMap; i < ctx.__rmap.length; i++) {
if (ctx.__rmap[i] === 1) {
count = 0;
continue;
}
if (!point) {
point = i;
}
count += 1;
}
if (count < minCount) {
return {
from: null,
availableFor: null,
};
}
return {
from: _timeFromMinOfDay(point),
availableFor: count,
};
}
export function createAvailabilityMinuteRange() {
return {
__rmap: new Array(1440),
blockTime,
nextAvailableFrom,
};
}
| 20.292308 | 58 | 0.592873 | 57 | 5 | 0 | 6 | 15 | 0 | 2 | 0 | 2 | 0 | 0 | 9.4 | 436 | 0.025229 | 0.034404 | 0 | 0 | 0 | 0 | 0.076923 | 0.341922 | /* Example usages of '_minOfDay' are shown below:
_minOfDay(new Date(start));
_minOfDay(new Date(end));
_minOfDay(date);
*/
function _minOfDay(date) {
const d = new Date(date);
const hour = d.getHours();
const min = d.getMinutes();
const minOfDay = hour * 60 + min;
return minOfDay;
}
/* Example usages of '_timeFromMinOfDay' are shown below:
_timeFromMinOfDay(point);
*/
function _timeFromMinOfDay(minOfDay) {
const hour = Math.floor((minOfDay - 0) / 60);
const min = minOfDay % 60;
return new Date(new Date().setHours(hour, min));
}
/* Example usages of 'blockTime' are shown below:
;
*/
function blockTime(start, end) {
const ctx = this || {};
const startMap = _minOfDay(new Date(start));
const endMap = _minOfDay(new Date(end));
for (let i = startMap; i < endMap; i += 1) {
if (ctx.__rmap[i] === 1) {
return false;
}
ctx.__rmap[i] = 1;
}
return true;
}
/* Example usages of 'nextAvailableFrom' are shown below:
;
*/
function nextAvailableFrom(date, minCount) {
const ctx = this || {};
const startMap = _minOfDay(date);
let count = 0;
let point = 0;
for (let i = startMap; i < ctx.__rmap.length; i++) {
if (ctx.__rmap[i] === 1) {
count = 0;
continue;
}
if (!point) {
point = i;
}
count += 1;
}
if (count < minCount) {
return {
from: null,
availableFor: null,
};
}
return {
from: _timeFromMinOfDay(point),
availableFor: count,
};
}
export function createAvailabilityMinuteRange() {
return {
__rmap: new Array(1440),
blockTime,
nextAvailableFrom,
};
}
|
24fa47d90e6fa0733f366a7bb236d2fb374abbc5 | 2,844 | ts | TypeScript | problemset/longest-increasing-path-in-a-matrix/index.ts | OUDUIDUI/leet-code | 50e61ce16d1c419ccefc075ae9ead721cdd1cdbb | [
"MIT"
] | 6 | 2022-01-17T03:19:56.000Z | 2022-01-17T05:45:39.000Z | problemset/longest-increasing-path-in-a-matrix/index.ts | OUDUIDUI/leet-code | 50e61ce16d1c419ccefc075ae9ead721cdd1cdbb | [
"MIT"
] | null | null | null | problemset/longest-increasing-path-in-a-matrix/index.ts | OUDUIDUI/leet-code | 50e61ce16d1c419ccefc075ae9ead721cdd1cdbb | [
"MIT"
] | null | null | null | /**
* 记忆化深度优先搜索
* @desc 时间复杂度 O(MN) 空间复杂度 O(MN)
* @param matrix
* @returns
*/
export function longestIncreasingPath(matrix: number[][]): number {
if (matrix.length === 0 || matrix[0].length === 0) return 0
const dirs = [[1, 0], [-1, 0], [0, 1], [0, -1]]
const m = matrix.length
const n = matrix[0].length
const memo = new Array(m).fill([]).map(() => new Array(n).fill(0))
let ans = 0
for (let i = 0; i < m; i++) {
for (let j = 0; j < n; j++)
ans = Math.max(ans, dfs(matrix, i, j, m, n, memo))
}
return ans
function dfs(
matrix: number[][],
row: number,
col: number,
m: number,
n: number,
memo: number[][],
): number {
if (memo[row][col] === 0) {
memo[row][col]++
for (const dir of dirs) {
const newRow = row + dir[0]
const newCol = col + dir[1]
if (
newRow >= 0
&& newRow < m
&& newCol >= 0
&& newCol < n
&& matrix[newRow][newCol] > matrix[row][col]
) {
// 保存到达该位置的最长递增路径长度
memo[row][col] = Math.max(
memo[row][col],
dfs(matrix, newRow, newCol, m, n, memo) + 1,
)
}
}
}
return memo[row][col]
}
}
/**
* 拓扑排序
* @desc 时间复杂度 O(MN) 空间复杂度 O(MN)
* @param matrix
* @returns
*/
export function longestIncreasingPath2(matrix: number[][]): number {
if (matrix.length === 0 || matrix[0].length === 0) return 0
const dirs = [[1, 0], [-1, 0], [0, 1], [0, -1]]
const m = matrix.length
const n = matrix[0].length
// 记录每个单元格周围有几个比自己大的单元格
const outdegrees = new Array(m).fill([]).map(() => new Array(n).fill(0))
for (let i = 0; i < m; i++) {
for (let j = 0; j < n; j++) {
for (const dir of dirs) {
const newRow = i + dir[0]
const newCol = j + dir[1]
if (
newRow >= 0
&& newRow < m
&& newCol >= 0
&& newCol < n
&& matrix[newRow][newCol] > matrix[i][j]
)
outdegrees[i][j]++
}
}
}
// 将出度为0的单元格放入队列中
const queue: [number, number][] = []
for (let i = 0; i < m; i++) {
for (let j = 0; j < n; j++) {
if (outdegrees[i][j] === 0)
queue.unshift([i, j])
}
}
let ans = 0
while (queue.length) {
ans++
const size = queue.length
for (let i = 0; i < size; i++) {
const [row, col] = queue.pop()!
for (const dir of dirs) {
const newRow = row + dir[0]
const newCol = col + dir[1]
if (
newRow >= 0
&& newRow < m
&& newCol >= 0
&& newCol < n
&& matrix[newRow][newCol] < matrix[row][col]
) {
outdegrees[newRow][newCol]--
if (outdegrees[newRow][newCol] === 0)
queue.unshift([newRow, newCol])
}
}
}
}
return ans
}
| 23.121951 | 74 | 0.471167 | 96 | 5 | 0 | 8 | 26 | 0 | 1 | 0 | 13 | 0 | 0 | 22.8 | 999 | 0.013013 | 0.026026 | 0 | 0 | 0 | 0 | 0.333333 | 0.285424 | /**
* 记忆化深度优先搜索
* @desc 时间复杂度 O(MN) 空间复杂度 O(MN)
* @param matrix
* @returns
*/
export function longestIncreasingPath(matrix) {
if (matrix.length === 0 || matrix[0].length === 0) return 0
const dirs = [[1, 0], [-1, 0], [0, 1], [0, -1]]
const m = matrix.length
const n = matrix[0].length
const memo = new Array(m).fill([]).map(() => new Array(n).fill(0))
let ans = 0
for (let i = 0; i < m; i++) {
for (let j = 0; j < n; j++)
ans = Math.max(ans, dfs(matrix, i, j, m, n, memo))
}
return ans
/* Example usages of 'dfs' are shown below:
ans = Math.max(ans, dfs(matrix, i, j, m, n, memo));
// 保存到达该位置的最长递增路径长度
memo[row][col] = Math.max(memo[row][col], dfs(matrix, newRow, newCol, m, n, memo) + 1);
*/
function dfs(
matrix,
row,
col,
m,
n,
memo,
) {
if (memo[row][col] === 0) {
memo[row][col]++
for (const dir of dirs) {
const newRow = row + dir[0]
const newCol = col + dir[1]
if (
newRow >= 0
&& newRow < m
&& newCol >= 0
&& newCol < n
&& matrix[newRow][newCol] > matrix[row][col]
) {
// 保存到达该位置的最长递增路径长度
memo[row][col] = Math.max(
memo[row][col],
dfs(matrix, newRow, newCol, m, n, memo) + 1,
)
}
}
}
return memo[row][col]
}
}
/**
* 拓扑排序
* @desc 时间复杂度 O(MN) 空间复杂度 O(MN)
* @param matrix
* @returns
*/
export function longestIncreasingPath2(matrix) {
if (matrix.length === 0 || matrix[0].length === 0) return 0
const dirs = [[1, 0], [-1, 0], [0, 1], [0, -1]]
const m = matrix.length
const n = matrix[0].length
// 记录每个单元格周围有几个比自己大的单元格
const outdegrees = new Array(m).fill([]).map(() => new Array(n).fill(0))
for (let i = 0; i < m; i++) {
for (let j = 0; j < n; j++) {
for (const dir of dirs) {
const newRow = i + dir[0]
const newCol = j + dir[1]
if (
newRow >= 0
&& newRow < m
&& newCol >= 0
&& newCol < n
&& matrix[newRow][newCol] > matrix[i][j]
)
outdegrees[i][j]++
}
}
}
// 将出度为0的单元格放入队列中
const queue = []
for (let i = 0; i < m; i++) {
for (let j = 0; j < n; j++) {
if (outdegrees[i][j] === 0)
queue.unshift([i, j])
}
}
let ans = 0
while (queue.length) {
ans++
const size = queue.length
for (let i = 0; i < size; i++) {
const [row, col] = queue.pop()!
for (const dir of dirs) {
const newRow = row + dir[0]
const newCol = col + dir[1]
if (
newRow >= 0
&& newRow < m
&& newCol >= 0
&& newCol < n
&& matrix[newRow][newCol] < matrix[row][col]
) {
outdegrees[newRow][newCol]--
if (outdegrees[newRow][newCol] === 0)
queue.unshift([newRow, newCol])
}
}
}
}
return ans
}
|
6d273bc6aa44f539110cfec2b0110ff2723ccfd0 | 2,452 | tsx | TypeScript | src/redux/modules/transactions.tsx | lanterndevs/Lantern-Client | 22ca1cbd4dfde1378342c1d841683cb3bbf2988b | [
"MIT"
] | 3 | 2022-01-18T21:06:47.000Z | 2022-01-18T21:49:31.000Z | src/redux/modules/transactions.tsx | lanterndevs/Lantern-Client | 22ca1cbd4dfde1378342c1d841683cb3bbf2988b | [
"MIT"
] | 46 | 2022-01-19T01:01:15.000Z | 2022-03-29T20:03:37.000Z | src/redux/modules/transactions.tsx | lanterndevs/Lantern-Client | 22ca1cbd4dfde1378342c1d841683cb3bbf2988b | [
"MIT"
] | null | null | null | export function typedAction<T extends string>(type: T): { type: T };
export function typedAction<T extends string, P extends any>(
type: T,
payload: P
): { type: T; payload: P };
export function typedAction(type: string, payload?: any) {
return { type, payload };
}
type Transaction = {
transactionID: string;
accountID: string;
amount: number;
categories: string;
date: Date;
details: string;
name: string;
currency: string;
};
type TransactionState = {
transactions: Transaction[] | null;
total_transactions: Number;
loading: boolean;
timestamp: Number;
};
const initialState: TransactionState = {
transactions: [],
total_transactions: 0,
loading: true,
timestamp: Date.now()
};
export const saveTransactions = (transactions: Transaction[]) => {
return typedAction('saveTransactions', transactions);
};
export const saveTotalTransactions = (total_transactions: Number) => {
return typedAction('saveTotalTransactions', total_transactions);
};
export const setTransactionLoading = (loading: boolean) => {
return typedAction('setTransactionLoading', loading);
};
export const setTransactionTimestamp = (timestamp: Number) => {
return typedAction('setTransactionTimestamp', timestamp);
};
type TransactionAction = ReturnType<
| typeof saveTransactions
| typeof saveTotalTransactions
| typeof setTransactionLoading
| typeof setTransactionTimestamp
>;
export function transactionReducer(
state = initialState,
action: TransactionAction
): TransactionState {
switch (action.type) {
case 'saveTransactions':
return {
transactions: action.payload,
total_transactions: state.total_transactions,
loading: state.loading,
timestamp: state.timestamp
};
case 'saveTotalTransactions':
return {
transactions: state.transactions,
total_transactions: action.payload,
loading: state.loading,
timestamp: state.timestamp
};
case 'setTransactionLoading':
return {
transactions: state.transactions,
total_transactions: state.total_transactions,
loading: action.payload,
timestamp: state.timestamp
};
case 'setTransactionTimestamp':
return {
transactions: state.transactions,
total_transactions: state.total_transactions,
loading: state.loading,
timestamp: action.payload
};
default:
return state;
}
}
| 25.810526 | 70 | 0.696982 | 85 | 6 | 2 | 11 | 5 | 12 | 1 | 2 | 12 | 3 | 0 | 6.166667 | 549 | 0.030965 | 0.009107 | 0.021858 | 0.005464 | 0 | 0.055556 | 0.333333 | 0.280017 | export function typedAction<T extends string>(type);
export function typedAction<T extends string, P extends any>(
type,
payload
);
export /* Example usages of 'typedAction' are shown below:
typedAction('saveTransactions', transactions);
typedAction('saveTotalTransactions', total_transactions);
typedAction('setTransactionLoading', loading);
typedAction('setTransactionTimestamp', timestamp);
*/
function typedAction(type, payload?) {
return { type, payload };
}
type Transaction = {
transactionID;
accountID;
amount;
categories;
date;
details;
name;
currency;
};
type TransactionState = {
transactions;
total_transactions;
loading;
timestamp;
};
const initialState = {
transactions: [],
total_transactions: 0,
loading: true,
timestamp: Date.now()
};
export /* Example usages of 'saveTransactions' are shown below:
;
*/
const saveTransactions = (transactions) => {
return typedAction('saveTransactions', transactions);
};
export /* Example usages of 'saveTotalTransactions' are shown below:
;
*/
const saveTotalTransactions = (total_transactions) => {
return typedAction('saveTotalTransactions', total_transactions);
};
export /* Example usages of 'setTransactionLoading' are shown below:
;
*/
const setTransactionLoading = (loading) => {
return typedAction('setTransactionLoading', loading);
};
export /* Example usages of 'setTransactionTimestamp' are shown below:
;
*/
const setTransactionTimestamp = (timestamp) => {
return typedAction('setTransactionTimestamp', timestamp);
};
type TransactionAction = ReturnType<
| typeof saveTransactions
| typeof saveTotalTransactions
| typeof setTransactionLoading
| typeof setTransactionTimestamp
>;
export function transactionReducer(
state = initialState,
action
) {
switch (action.type) {
case 'saveTransactions':
return {
transactions: action.payload,
total_transactions: state.total_transactions,
loading: state.loading,
timestamp: state.timestamp
};
case 'saveTotalTransactions':
return {
transactions: state.transactions,
total_transactions: action.payload,
loading: state.loading,
timestamp: state.timestamp
};
case 'setTransactionLoading':
return {
transactions: state.transactions,
total_transactions: state.total_transactions,
loading: action.payload,
timestamp: state.timestamp
};
case 'setTransactionTimestamp':
return {
transactions: state.transactions,
total_transactions: state.total_transactions,
loading: state.loading,
timestamp: action.payload
};
default:
return state;
}
}
|
6d3f0413b1a66fe24a0b6c6ea641bb910749e550 | 4,003 | tsx | TypeScript | frontend/app/src/components/highlightjs-turtle.tsx | MaastrichtU-IDS/knowledge-collaboratory | d1e9bd7595c944c0a936bdcce4a145c0a19e8d7f | [
"MIT"
] | 1 | 2022-03-05T17:35:03.000Z | 2022-03-05T17:35:03.000Z | frontend/app/src/components/highlightjs-turtle.tsx | MaastrichtU-IDS/knowledge-collaboratory | d1e9bd7595c944c0a936bdcce4a145c0a19e8d7f | [
"MIT"
] | null | null | null | frontend/app/src/components/highlightjs-turtle.tsx | MaastrichtU-IDS/knowledge-collaboratory | d1e9bd7595c944c0a936bdcce4a145c0a19e8d7f | [
"MIT"
] | null | null | null | /*
Language: Turtle
Author: Redmer KRONEMEIJER <[email protected]>
Contributors: Mark ELLIS <[email protected]>, Vladimir ALEXIEV <[email protected]>
*/
// var module = module ? module : {}; // shim for browser use
// function hljsDefineTurtle(hljs) {
export default function (hljs: any) {
var KEYWORDS = {
keyword: 'BASE|10 PREFIX|10 @base|10 @prefix|10',
literal: 'true|0 false|0',
built_in: 'a|0'
};
var IRI_LITERAL = {// https://www.w3.org/TR/turtle/#grammar-production-IRIREF
className: 'literal',
relevance: 1, // XML tags look also like relative IRIs
begin: /</,
end: />/,
illegal: /[^\x00-\x20<>"{}|^`]/, // TODO: https://www.w3.org/TR/turtle/#grammar-production-UCHAR
};
// https://www.w3.org/TR/turtle/#terminals
var PN_CHARS_BASE = 'A-Za-z\u00C0-\u00D6\u00D8-\u00F6\u00F8-\u02FF\u0370-\u037D\u037F-\u1FFF\u200C-\u200D\u2070-\u218F\u2C00-\u2FEF\u3001-\uD7FF\uF900-\uFDCF\uFDF0-\uFFFD\u10000-\uEFFFF';
var PN_CHARS_U = PN_CHARS_BASE + '_';
var PN_CHARS = '-' + PN_CHARS_U + '0-9\u00B7\u0300-\u036F\u203F-\u2040';
var BLANK_NODE_LABEL = '_:[' + PN_CHARS_U + '0-9]([' + PN_CHARS + '.]*[' + PN_CHARS + '])?';
var PN_PREFIX = '[' + PN_CHARS_BASE + ']([' + PN_CHARS + '.]*[' + PN_CHARS + '])?';
var PERCENT = '%[0-9A-Fa-f][0-9A-Fa-f]';
var PN_LOCAL_ESC = '\\\\[_~.!$&\'()*+,;=/?#@%-]';
var PLX = PERCENT + '|' + PN_LOCAL_ESC;
var PNAME_NS = '(' + PN_PREFIX + ')?:';
var PN_LOCAL = '([' + PN_CHARS_U + ':0-9]|' + PLX + ')([' + PN_CHARS + '.:]|' + PLX + ')*([' + PN_CHARS + ':]|' + PLX + ')?';
var PNAME_LN = PNAME_NS + PN_LOCAL;
var PNAME_NS_or_LN = PNAME_NS + '(' + PN_LOCAL + ')?';
var PNAME = {
begin: PNAME_NS_or_LN,
relevance: 0,
className: 'symbol',
};
var BLANK_NODE = {
begin: BLANK_NODE_LABEL,
relevance: 10,
className: 'template-variable',
};
var LANGTAG = {
begin: /@[a-zA-Z]+([a-zA-Z0-9-]+)*/,
className: 'type',
relevance: 5, // also catches objectivec keywords like: @protocol, @optional
};
var DATATYPE = {
begin: '\\^\\^' + PNAME_LN,
className: 'type',
relevance: 10,
};
var TRIPLE_APOS_STRING = {
begin: /'''/,
end: /'''/,
className: 'string',
relevance: 0,
};
var TRIPLE_QUOTE_STRING = {
begin: /"""/,
end: /"""/,
className: 'string',
relevance: 0,
};
var APOS_STRING_LITERAL = JSON.parse(JSON.stringify(hljs.APOS_STRING_MODE));
APOS_STRING_LITERAL.relevance = 0;
var QUOTE_STRING_LITERAL = JSON.parse(JSON.stringify(hljs.QUOTE_STRING_MODE));
QUOTE_STRING_LITERAL.relevance = 0;
var NUMBER = JSON.parse(JSON.stringify(hljs.C_NUMBER_MODE));
NUMBER.relevance = 0;
return {
name: "Turtle",
case_insensitive: true, // however `true` and `@prefix` are oblig. cased thus
keywords: KEYWORDS,
aliases: ['turtle', 'ttl', 'n3'],
contains: [
LANGTAG,
DATATYPE,
IRI_LITERAL,
BLANK_NODE,
PNAME,
TRIPLE_APOS_STRING, TRIPLE_QUOTE_STRING, // order matters
APOS_STRING_LITERAL, QUOTE_STRING_LITERAL,
NUMBER,
hljs.HASH_COMMENT_MODE,
],
exports: {
LANGTAG: LANGTAG,
DATATYPE: DATATYPE,
IRI_LITERAL: IRI_LITERAL,
BLANK_NODE: BLANK_NODE,
PNAME: PNAME,
TRIPLE_APOS_STRING: TRIPLE_APOS_STRING,
TRIPLE_QUOTE_STRING: TRIPLE_QUOTE_STRING,
APOS_STRING_LITERAL: APOS_STRING_LITERAL,
QUOTE_STRING_LITERAL: QUOTE_STRING_LITERAL,
NUMBER: NUMBER,
KEYWORDS: KEYWORDS,
}
};
}
// module.exports = function (hljs) {
// hljs.registerLanguage('turtle', hljsDefineTurtle);
// };
// module.exports.definer = hljsDefineTurtle;
| 32.544715 | 191 | 0.572321 | 94 | 1 | 0 | 1 | 23 | 0 | 0 | 1 | 0 | 0 | 0 | 92 | 1,436 | 0.001393 | 0.016017 | 0 | 0 | 0 | 0.04 | 0 | 0.225372 | /*
Language: Turtle
Author: Redmer KRONEMEIJER <[email protected]>
Contributors: Mark ELLIS <[email protected]>, Vladimir ALEXIEV <[email protected]>
*/
// var module = module ? module : {}; // shim for browser use
// function hljsDefineTurtle(hljs) {
export default function (hljs) {
var KEYWORDS = {
keyword: 'BASE|10 PREFIX|10 @base|10 @prefix|10',
literal: 'true|0 false|0',
built_in: 'a|0'
};
var IRI_LITERAL = {// https://www.w3.org/TR/turtle/#grammar-production-IRIREF
className: 'literal',
relevance: 1, // XML tags look also like relative IRIs
begin: /</,
end: />/,
illegal: /[^\x00-\x20<>"{}|^`]/, // TODO: https://www.w3.org/TR/turtle/#grammar-production-UCHAR
};
// https://www.w3.org/TR/turtle/#terminals
var PN_CHARS_BASE = 'A-Za-z\u00C0-\u00D6\u00D8-\u00F6\u00F8-\u02FF\u0370-\u037D\u037F-\u1FFF\u200C-\u200D\u2070-\u218F\u2C00-\u2FEF\u3001-\uD7FF\uF900-\uFDCF\uFDF0-\uFFFD\u10000-\uEFFFF';
var PN_CHARS_U = PN_CHARS_BASE + '_';
var PN_CHARS = '-' + PN_CHARS_U + '0-9\u00B7\u0300-\u036F\u203F-\u2040';
var BLANK_NODE_LABEL = '_:[' + PN_CHARS_U + '0-9]([' + PN_CHARS + '.]*[' + PN_CHARS + '])?';
var PN_PREFIX = '[' + PN_CHARS_BASE + ']([' + PN_CHARS + '.]*[' + PN_CHARS + '])?';
var PERCENT = '%[0-9A-Fa-f][0-9A-Fa-f]';
var PN_LOCAL_ESC = '\\\\[_~.!$&\'()*+,;=/?#@%-]';
var PLX = PERCENT + '|' + PN_LOCAL_ESC;
var PNAME_NS = '(' + PN_PREFIX + ')?:';
var PN_LOCAL = '([' + PN_CHARS_U + ':0-9]|' + PLX + ')([' + PN_CHARS + '.:]|' + PLX + ')*([' + PN_CHARS + ':]|' + PLX + ')?';
var PNAME_LN = PNAME_NS + PN_LOCAL;
var PNAME_NS_or_LN = PNAME_NS + '(' + PN_LOCAL + ')?';
var PNAME = {
begin: PNAME_NS_or_LN,
relevance: 0,
className: 'symbol',
};
var BLANK_NODE = {
begin: BLANK_NODE_LABEL,
relevance: 10,
className: 'template-variable',
};
var LANGTAG = {
begin: /@[a-zA-Z]+([a-zA-Z0-9-]+)*/,
className: 'type',
relevance: 5, // also catches objectivec keywords like: @protocol, @optional
};
var DATATYPE = {
begin: '\\^\\^' + PNAME_LN,
className: 'type',
relevance: 10,
};
var TRIPLE_APOS_STRING = {
begin: /'''/,
end: /'''/,
className: 'string',
relevance: 0,
};
var TRIPLE_QUOTE_STRING = {
begin: /"""/,
end: /"""/,
className: 'string',
relevance: 0,
};
var APOS_STRING_LITERAL = JSON.parse(JSON.stringify(hljs.APOS_STRING_MODE));
APOS_STRING_LITERAL.relevance = 0;
var QUOTE_STRING_LITERAL = JSON.parse(JSON.stringify(hljs.QUOTE_STRING_MODE));
QUOTE_STRING_LITERAL.relevance = 0;
var NUMBER = JSON.parse(JSON.stringify(hljs.C_NUMBER_MODE));
NUMBER.relevance = 0;
return {
name: "Turtle",
case_insensitive: true, // however `true` and `@prefix` are oblig. cased thus
keywords: KEYWORDS,
aliases: ['turtle', 'ttl', 'n3'],
contains: [
LANGTAG,
DATATYPE,
IRI_LITERAL,
BLANK_NODE,
PNAME,
TRIPLE_APOS_STRING, TRIPLE_QUOTE_STRING, // order matters
APOS_STRING_LITERAL, QUOTE_STRING_LITERAL,
NUMBER,
hljs.HASH_COMMENT_MODE,
],
exports: {
LANGTAG: LANGTAG,
DATATYPE: DATATYPE,
IRI_LITERAL: IRI_LITERAL,
BLANK_NODE: BLANK_NODE,
PNAME: PNAME,
TRIPLE_APOS_STRING: TRIPLE_APOS_STRING,
TRIPLE_QUOTE_STRING: TRIPLE_QUOTE_STRING,
APOS_STRING_LITERAL: APOS_STRING_LITERAL,
QUOTE_STRING_LITERAL: QUOTE_STRING_LITERAL,
NUMBER: NUMBER,
KEYWORDS: KEYWORDS,
}
};
}
// module.exports = function (hljs) {
// hljs.registerLanguage('turtle', hljsDefineTurtle);
// };
// module.exports.definer = hljsDefineTurtle;
|
6d441b29fca0323dd6b2933cf3ef36e507748d2d | 4,184 | ts | TypeScript | gomoku-core/src/utils/GomokuCore.ts | toytag/Gomoku | 7e86e83d93ed51d7c78a4f618d249de342137ee2 | [
"MIT"
] | 1 | 2022-01-22T20:42:44.000Z | 2022-01-22T20:42:44.000Z | gomoku-core/src/utils/GomokuCore.ts | toytag/Gomoku | 7e86e83d93ed51d7c78a4f618d249de342137ee2 | [
"MIT"
] | null | null | null | gomoku-core/src/utils/GomokuCore.ts | toytag/Gomoku | 7e86e83d93ed51d7c78a4f618d249de342137ee2 | [
"MIT"
] | null | null | null | /* eslint-disable max-classes-per-file */
export type Move = readonly [number, number];
export enum Piece {
EMPTY = 0,
BLACK = 1,
WHITE = 2,
BOARDER = 3,
}
export class Board {
static readonly SIZE = 15;
private data: Uint8Array;
constructor() {
this.data = new Uint8Array(Board.SIZE * Board.SIZE);
}
get(row: number, col: number): Piece {
if (row < 0 || row >= Board.SIZE || col < 0 || col >= Board.SIZE) {
return Piece.BOARDER;
}
return this.data[row * Board.SIZE + col];
}
set(row: number, col: number, piece: Piece): void {
if (row < 0 || row >= Board.SIZE || col < 0 || col >= Board.SIZE) {
return;
}
this.data[row * Board.SIZE + col] = piece;
}
}
export default class GomokuCore {
private board: Board;
private history: Move[];
private winner: Piece;
constructor() {
this.board = new Board();
this.history = [];
this.winner = Piece.EMPTY;
}
static fromHistory(history: readonly Move[]): GomokuCore {
const board = new GomokuCore();
for (let i = 0; i < history.length - 1; i += 1) {
// board.move(history[i][0], history[i][1]);
board.setBoardAt(history[i][0], history[i][1], board.getCurrentPlayer());
board.pushMove(history[i][0], history[i][1]);
}
board.move(history[history.length - 1][0], history[history.length - 1][1]);
return board;
}
getBoardAt(row: number, col: number): Piece {
return this.board.get(row, col);
}
private setBoardAt(row: number, col: number, piece: Piece): void {
this.board.set(row, col, piece);
}
getCurrentPlayer(): Piece {
return this.history.length % 2 === 0 ? Piece.BLACK : Piece.WHITE;
}
getLastMove(): Move | null {
if (this.history.length === 0) {
return null;
}
return this.history[this.history.length - 1];
}
private pushMove(row: number, col: number): void {
this.history.push([row, col]);
}
private popMove(): Move | null {
const last = this.history.pop();
if (last) return last;
return null;
}
getWinner(): Piece {
return this.winner;
}
private checkWinner(row: number, col: number, piece: Piece): void {
// check horizontal
for (let k = -5; k < 5; k += 1) {
if (this.getBoardAt(row, col + k) === piece) {
const start = k;
while (this.getBoardAt(row, col + k + 1) === piece) k += 1;
const end = k;
if (end - start + 1 >= 5) {
this.winner = piece;
return;
}
}
}
// check vertical
for (let k = -5; k < 5; k += 1) {
if (this.getBoardAt(row + k, col) === piece) {
const start = k;
while (this.getBoardAt(row + k + 1, col) === piece) k += 1;
const end = k;
if (end - start + 1 >= 5) {
this.winner = piece;
return;
}
}
}
// check diagonal
for (let k = -5; k < 5; k += 1) {
if (this.getBoardAt(row + k, col + k) === piece) {
const start = k;
while (this.getBoardAt(row + k + 1, col + k + 1) === piece) k += 1;
const end = k;
if (end - start + 1 >= 5) {
this.winner = piece;
return;
}
}
}
// check anti-diagonal
for (let k = -5; k < 5; k += 1) {
if (this.getBoardAt(row + k, col - k) === piece) {
const start = k;
while (this.getBoardAt(row + k + 1, col - k - 1) === piece) k += 1;
const end = k;
if (end - start + 1 >= 5) {
this.winner = piece;
return;
}
}
}
}
move(row: number, col: number): Piece | null {
const piece = this.getCurrentPlayer();
if (this.getBoardAt(row, col) === Piece.EMPTY) {
this.setBoardAt(row, col, piece);
this.pushMove(row, col);
this.checkWinner(row, col, piece);
return piece;
}
return null;
}
withdraw(): Move | null {
const lastMove = this.popMove();
if (lastMove)
this.setBoardAt(lastMove[0], lastMove[1], Piece.EMPTY);
this.winner = Piece.EMPTY;
return lastMove;
}
reset(): void {
this.board = new Board();
this.history = [];
this.winner = Piece.EMPTY;
}
}
| 24.904762 | 79 | 0.539675 | 139 | 16 | 0 | 18 | 17 | 5 | 9 | 0 | 21 | 3 | 0 | 5.6875 | 1,316 | 0.025836 | 0.012918 | 0.003799 | 0.00228 | 0 | 0 | 0.375 | 0.278196 | /* eslint-disable max-classes-per-file */
export type Move = readonly [number, number];
export enum Piece {
EMPTY = 0,
BLACK = 1,
WHITE = 2,
BOARDER = 3,
}
export class Board {
static readonly SIZE = 15;
private data;
constructor() {
this.data = new Uint8Array(Board.SIZE * Board.SIZE);
}
get(row, col) {
if (row < 0 || row >= Board.SIZE || col < 0 || col >= Board.SIZE) {
return Piece.BOARDER;
}
return this.data[row * Board.SIZE + col];
}
set(row, col, piece) {
if (row < 0 || row >= Board.SIZE || col < 0 || col >= Board.SIZE) {
return;
}
this.data[row * Board.SIZE + col] = piece;
}
}
export default class GomokuCore {
private board;
private history;
private winner;
constructor() {
this.board = new Board();
this.history = [];
this.winner = Piece.EMPTY;
}
static fromHistory(history) {
const board = new GomokuCore();
for (let i = 0; i < history.length - 1; i += 1) {
// board.move(history[i][0], history[i][1]);
board.setBoardAt(history[i][0], history[i][1], board.getCurrentPlayer());
board.pushMove(history[i][0], history[i][1]);
}
board.move(history[history.length - 1][0], history[history.length - 1][1]);
return board;
}
getBoardAt(row, col) {
return this.board.get(row, col);
}
private setBoardAt(row, col, piece) {
this.board.set(row, col, piece);
}
getCurrentPlayer() {
return this.history.length % 2 === 0 ? Piece.BLACK : Piece.WHITE;
}
getLastMove() {
if (this.history.length === 0) {
return null;
}
return this.history[this.history.length - 1];
}
private pushMove(row, col) {
this.history.push([row, col]);
}
private popMove() {
const last = this.history.pop();
if (last) return last;
return null;
}
getWinner() {
return this.winner;
}
private checkWinner(row, col, piece) {
// check horizontal
for (let k = -5; k < 5; k += 1) {
if (this.getBoardAt(row, col + k) === piece) {
const start = k;
while (this.getBoardAt(row, col + k + 1) === piece) k += 1;
const end = k;
if (end - start + 1 >= 5) {
this.winner = piece;
return;
}
}
}
// check vertical
for (let k = -5; k < 5; k += 1) {
if (this.getBoardAt(row + k, col) === piece) {
const start = k;
while (this.getBoardAt(row + k + 1, col) === piece) k += 1;
const end = k;
if (end - start + 1 >= 5) {
this.winner = piece;
return;
}
}
}
// check diagonal
for (let k = -5; k < 5; k += 1) {
if (this.getBoardAt(row + k, col + k) === piece) {
const start = k;
while (this.getBoardAt(row + k + 1, col + k + 1) === piece) k += 1;
const end = k;
if (end - start + 1 >= 5) {
this.winner = piece;
return;
}
}
}
// check anti-diagonal
for (let k = -5; k < 5; k += 1) {
if (this.getBoardAt(row + k, col - k) === piece) {
const start = k;
while (this.getBoardAt(row + k + 1, col - k - 1) === piece) k += 1;
const end = k;
if (end - start + 1 >= 5) {
this.winner = piece;
return;
}
}
}
}
move(row, col) {
const piece = this.getCurrentPlayer();
if (this.getBoardAt(row, col) === Piece.EMPTY) {
this.setBoardAt(row, col, piece);
this.pushMove(row, col);
this.checkWinner(row, col, piece);
return piece;
}
return null;
}
withdraw() {
const lastMove = this.popMove();
if (lastMove)
this.setBoardAt(lastMove[0], lastMove[1], Piece.EMPTY);
this.winner = Piece.EMPTY;
return lastMove;
}
reset() {
this.board = new Board();
this.history = [];
this.winner = Piece.EMPTY;
}
}
|
d30569b5b9e9e95f1258d43da01c74424100d670 | 4,742 | ts | TypeScript | frontend/src/utils/compoundApyHelpers.ts | 007blockchaindeveloper/GuitarUI | a486157c7f65d7157b64034ac27511938407db22 | [
"MIT"
] | 14 | 2022-01-13T05:11:54.000Z | 2022-03-23T03:27:28.000Z | frontend/src/utils/compoundApyHelpers.ts | 007blockchaindeveloper/GuitarUI | a486157c7f65d7157b64034ac27511938407db22 | [
"MIT"
] | 2 | 2022-02-11T03:32:35.000Z | 2022-03-02T04:36:51.000Z | frontend/src/utils/compoundApyHelpers.ts | 007blockchaindeveloper/GuitarUI | a486157c7f65d7157b64034ac27511938407db22 | [
"MIT"
] | 10 | 2022-02-09T15:14:52.000Z | 2022-03-21T18:43:12.000Z | // 1 day, 7 days, 30 days, 1 year, 5 years
const DAYS_TO_CALCULATE_AGAINST = [1, 7, 30, 365, 1825]
/**
*
* @param principalInUSD - amount user wants to invest in USD
* @param apr - farm or pool apr as percentage. If its farm APR its only cake rewards APR without LP rewards APR
* @param earningTokenPrice - price of reward token
* @param compoundFrequency - how many compounds per 1 day, e.g. 1 = one per day, 0.142857142 - once per week
* @param performanceFee - performance fee as percentage
* @returns an array of token values earned as interest, with each element representing interest earned over a different period of time (DAYS_TO_CALCULATE_AGAINST)
*/
export const getInterestBreakdown = ({
principalInUSD,
apr,
earningTokenPrice,
compoundFrequency = 1,
performanceFee = 0,
}: {
principalInUSD: number
apr: number
earningTokenPrice: number
compoundFrequency?: number
performanceFee?: number
}) => {
// Everything here is worked out relative to a year, with the asset compounding at the compoundFrequency rate. 1 = once per day
const timesCompounded = 365 * compoundFrequency
// We use decimal values rather than % in the math for both APY and the number of days being calculates as a proportion of the year
const aprAsDecimal = apr / 100
// special handling for tokens like tBTC or BIFI where the daily token rewards for $1000 dollars will be less than 0.001 of that token
// and also cause rounding errors
const isHighValueToken = Math.round(earningTokenPrice / 1000) > 0
const roundingDecimalsNew = isHighValueToken ? 5 : 3
return DAYS_TO_CALCULATE_AGAINST.map((days) => {
const daysAsDecimalOfYear = days / 365
// Calculate the starting TOKEN balance with a dollar balance of principalInUSD.
const principal = principalInUSD / earningTokenPrice
let interestEarned = principal * aprAsDecimal * (days / 365)
if (timesCompounded !== 0) {
// This is a translation of the typical mathematical compounding APY formula. Details here: https://www.calculatorsoup.com/calculators/financial/compound-interest-calculator.php
const accruedAmount = principal * (1 + aprAsDecimal / timesCompounded) ** (timesCompounded * daysAsDecimalOfYear)
// To get the TOKEN amount earned, deduct the amount after compounding (accruedAmount) from the starting TOKEN balance (principal)
interestEarned = accruedAmount - principal
if (performanceFee) {
const performanceFeeAsDecimal = performanceFee / 100
const performanceFeeAsAmount = interestEarned * performanceFeeAsDecimal
interestEarned -= performanceFeeAsAmount
}
}
return parseFloat(interestEarned.toFixed(roundingDecimalsNew))
})
}
/**
* @param interest how much USD amount you aim to make
* @param apr APR of farm/pool
* @param compoundingFrequency how many compounds per 1 day, e.g. 1 = one per day, 0.142857142 - once per week
* @returns an array of principal values needed to reach target interest, with each element representing principal needed for a different period of time (DAYS_TO_CALCULATE_AGAINST)
*/
export const getPrincipalForInterest = (
interest: number,
apr: number,
compoundingFrequency: number,
performanceFee = 0,
) => {
return DAYS_TO_CALCULATE_AGAINST.map((days) => {
const apyAsDecimal = getApy(apr, compoundingFrequency, days, performanceFee)
// console.log('inside', interest, apyAsDecimal)
// const apyAsBN = new BigNumber(apyAsDecimal).decimalPlaces(6, BigNumber.ROUND_DOWN).toNumber()
return parseFloat((interest / apyAsDecimal).toFixed(2))
})
}
/**
* Given APR returns APY
* @param apr APR as percentage
* @param compoundFrequency how many compounds per day
* @param days if other than 365 adjusts (A)PY for period less than a year
* @param performanceFee performance fee as percentage
* @returns APY as decimal
*/
export const getApy = (apr: number, compoundFrequency = 1, days = 365, performanceFee = 0) => {
const daysAsDecimalOfYear = days / 365
const aprAsDecimal = apr / 100
const timesCompounded = 365 * compoundFrequency
let apyAsDecimal = (apr / 100) * daysAsDecimalOfYear
if (timesCompounded > 0) {
apyAsDecimal = (1 + aprAsDecimal / timesCompounded) ** (timesCompounded * daysAsDecimalOfYear) - 1
}
if (performanceFee) {
const performanceFeeAsDecimal = performanceFee / 100
const takenAsPerformanceFee = apyAsDecimal * performanceFeeAsDecimal
apyAsDecimal -= takenAsPerformanceFee
}
return apyAsDecimal
}
export const getRoi = ({ amountEarned, amountInvested }: { amountEarned: number; amountInvested: number }) => {
if (amountInvested === 0) {
return 0
}
const percentage = (amountEarned / amountInvested) * 100
return percentage
}
| 44.317757 | 183 | 0.738929 | 67 | 6 | 0 | 12 | 23 | 0 | 1 | 0 | 11 | 0 | 0 | 9.333333 | 1,359 | 0.013245 | 0.016924 | 0 | 0 | 0 | 0 | 0.268293 | 0.256242 | // 1 day, 7 days, 30 days, 1 year, 5 years
const DAYS_TO_CALCULATE_AGAINST = [1, 7, 30, 365, 1825]
/**
*
* @param principalInUSD - amount user wants to invest in USD
* @param apr - farm or pool apr as percentage. If its farm APR its only cake rewards APR without LP rewards APR
* @param earningTokenPrice - price of reward token
* @param compoundFrequency - how many compounds per 1 day, e.g. 1 = one per day, 0.142857142 - once per week
* @param performanceFee - performance fee as percentage
* @returns an array of token values earned as interest, with each element representing interest earned over a different period of time (DAYS_TO_CALCULATE_AGAINST)
*/
export const getInterestBreakdown = ({
principalInUSD,
apr,
earningTokenPrice,
compoundFrequency = 1,
performanceFee = 0,
}) => {
// Everything here is worked out relative to a year, with the asset compounding at the compoundFrequency rate. 1 = once per day
const timesCompounded = 365 * compoundFrequency
// We use decimal values rather than % in the math for both APY and the number of days being calculates as a proportion of the year
const aprAsDecimal = apr / 100
// special handling for tokens like tBTC or BIFI where the daily token rewards for $1000 dollars will be less than 0.001 of that token
// and also cause rounding errors
const isHighValueToken = Math.round(earningTokenPrice / 1000) > 0
const roundingDecimalsNew = isHighValueToken ? 5 : 3
return DAYS_TO_CALCULATE_AGAINST.map((days) => {
const daysAsDecimalOfYear = days / 365
// Calculate the starting TOKEN balance with a dollar balance of principalInUSD.
const principal = principalInUSD / earningTokenPrice
let interestEarned = principal * aprAsDecimal * (days / 365)
if (timesCompounded !== 0) {
// This is a translation of the typical mathematical compounding APY formula. Details here: https://www.calculatorsoup.com/calculators/financial/compound-interest-calculator.php
const accruedAmount = principal * (1 + aprAsDecimal / timesCompounded) ** (timesCompounded * daysAsDecimalOfYear)
// To get the TOKEN amount earned, deduct the amount after compounding (accruedAmount) from the starting TOKEN balance (principal)
interestEarned = accruedAmount - principal
if (performanceFee) {
const performanceFeeAsDecimal = performanceFee / 100
const performanceFeeAsAmount = interestEarned * performanceFeeAsDecimal
interestEarned -= performanceFeeAsAmount
}
}
return parseFloat(interestEarned.toFixed(roundingDecimalsNew))
})
}
/**
* @param interest how much USD amount you aim to make
* @param apr APR of farm/pool
* @param compoundingFrequency how many compounds per 1 day, e.g. 1 = one per day, 0.142857142 - once per week
* @returns an array of principal values needed to reach target interest, with each element representing principal needed for a different period of time (DAYS_TO_CALCULATE_AGAINST)
*/
export const getPrincipalForInterest = (
interest,
apr,
compoundingFrequency,
performanceFee = 0,
) => {
return DAYS_TO_CALCULATE_AGAINST.map((days) => {
const apyAsDecimal = getApy(apr, compoundingFrequency, days, performanceFee)
// console.log('inside', interest, apyAsDecimal)
// const apyAsBN = new BigNumber(apyAsDecimal).decimalPlaces(6, BigNumber.ROUND_DOWN).toNumber()
return parseFloat((interest / apyAsDecimal).toFixed(2))
})
}
/**
* Given APR returns APY
* @param apr APR as percentage
* @param compoundFrequency how many compounds per day
* @param days if other than 365 adjusts (A)PY for period less than a year
* @param performanceFee performance fee as percentage
* @returns APY as decimal
*/
export /* Example usages of 'getApy' are shown below:
getApy(apr, compoundingFrequency, days, performanceFee);
*/
const getApy = (apr, compoundFrequency = 1, days = 365, performanceFee = 0) => {
const daysAsDecimalOfYear = days / 365
const aprAsDecimal = apr / 100
const timesCompounded = 365 * compoundFrequency
let apyAsDecimal = (apr / 100) * daysAsDecimalOfYear
if (timesCompounded > 0) {
apyAsDecimal = (1 + aprAsDecimal / timesCompounded) ** (timesCompounded * daysAsDecimalOfYear) - 1
}
if (performanceFee) {
const performanceFeeAsDecimal = performanceFee / 100
const takenAsPerformanceFee = apyAsDecimal * performanceFeeAsDecimal
apyAsDecimal -= takenAsPerformanceFee
}
return apyAsDecimal
}
export const getRoi = ({ amountEarned, amountInvested }) => {
if (amountInvested === 0) {
return 0
}
const percentage = (amountEarned / amountInvested) * 100
return percentage
}
|
54882c1b4f5afd785ff8918678f1ada0fdf4020a | 2,132 | ts | TypeScript | frontend/src/app/models/product.model.ts | AleksaDursun/stolarija | 99d7299f276b5da83a1a5b2e551b3204615e19c2 | [
"BSD-3-Clause"
] | null | null | null | frontend/src/app/models/product.model.ts | AleksaDursun/stolarija | 99d7299f276b5da83a1a5b2e551b3204615e19c2 | [
"BSD-3-Clause"
] | 1 | 2022-03-02T11:34:26.000Z | 2022-03-02T11:34:26.000Z | frontend/src/app/models/product.model.ts | AleksaDursun/stolarija | 99d7299f276b5da83a1a5b2e551b3204615e19c2 | [
"BSD-3-Clause"
] | null | null | null | // Product Tag
export type ProductTags = 'nike' | 'puma' | 'lifestyle' | 'caprese';
// Product Colors
export type ProductColor = 'white' | 'black' | 'red' | 'green' | 'purple' | 'yellow' | 'blue' | 'gray' | 'orange' | 'pink';
export class Product {
id?: number;
name?: string;
price?: number;
quantity?: number;
type?: string;
// tslint:disable-next-line:variable-name
discount_price?: number;
discount?: number;
pictures?: string;
// tslint:disable-next-line:variable-name
image_url?: string;
state?: string;
// tslint:disable-next-line:variable-name
is_used?: boolean;
// tslint:disable-next-line:variable-name
short_description?: string;
description?: string;
stock?: number;
newPro?: boolean;
brand?: string;
sale?: boolean;
category?: string;
tags?: ProductTags[];
colors?: ProductColor[];
constructor(
id?: number,
name?: string,
price?: number,
quantity?: number,
// tslint:disable-next-line:variable-name
discount_price?: number,
discount?: number,
pictures?: string,
type?: string,
// tslint:disable-next-line:variable-name
short_description?: string,
description?: string,
// tslint:disable-next-line:variable-name
is_used?: boolean,
stock?: number,
state?: string,
newPro?: boolean,
brand?: string,
sale?: boolean,
category?: string,
tags?: ProductTags[],
colors?: ProductColor[]
) {
this.id = id;
this.name = name;
this.price = price;
this.quantity = quantity;
this.type = type;
this.is_used = is_used;
this.discount_price = discount_price;
this.discount = discount;
this.pictures = pictures;
this.short_description = short_description;
this.description = description;
this.stock = stock;
this.newPro = newPro;
this.brand = brand;
this.sale = sale;
this.category = category;
this.tags = tags;
this.colors = colors;
this.state = state;
}
}
// Color Filter
export interface ColorFilter {
color?: ProductColor;
}
| 25.082353 | 124 | 0.620544 | 68 | 1 | 0 | 19 | 0 | 21 | 0 | 0 | 35 | 4 | 0 | 19 | 581 | 0.034423 | 0 | 0.036145 | 0.006885 | 0 | 0 | 0.853659 | 0.260662 | // Product Tag
export type ProductTags = 'nike' | 'puma' | 'lifestyle' | 'caprese';
// Product Colors
export type ProductColor = 'white' | 'black' | 'red' | 'green' | 'purple' | 'yellow' | 'blue' | 'gray' | 'orange' | 'pink';
export class Product {
id?;
name?;
price?;
quantity?;
type?;
// tslint:disable-next-line:variable-name
discount_price?;
discount?;
pictures?;
// tslint:disable-next-line:variable-name
image_url?;
state?;
// tslint:disable-next-line:variable-name
is_used?;
// tslint:disable-next-line:variable-name
short_description?;
description?;
stock?;
newPro?;
brand?;
sale?;
category?;
tags?;
colors?;
constructor(
id?,
name?,
price?,
quantity?,
// tslint:disable-next-line:variable-name
discount_price?,
discount?,
pictures?,
type?,
// tslint:disable-next-line:variable-name
short_description?,
description?,
// tslint:disable-next-line:variable-name
is_used?,
stock?,
state?,
newPro?,
brand?,
sale?,
category?,
tags?,
colors?
) {
this.id = id;
this.name = name;
this.price = price;
this.quantity = quantity;
this.type = type;
this.is_used = is_used;
this.discount_price = discount_price;
this.discount = discount;
this.pictures = pictures;
this.short_description = short_description;
this.description = description;
this.stock = stock;
this.newPro = newPro;
this.brand = brand;
this.sale = sale;
this.category = category;
this.tags = tags;
this.colors = colors;
this.state = state;
}
}
// Color Filter
export interface ColorFilter {
color?;
}
|
250d2eff77d5bfc161e6d92496979d25640720a5 | 5,173 | ts | TypeScript | Code/Websites/DanpheEMR/wwwroot/DanpheApp/src/app/core/dyn-templates/shared/dnamic-template-models.ts | MenkaChaugule/hospital-management-emr | 6c9afb0cda5ca4f8ea726e083f57b7a16a35a58d | [
"MIT"
] | 1 | 2022-03-03T09:53:27.000Z | 2022-03-03T09:53:27.000Z | Code/Websites/DanpheEMR/wwwroot/DanpheApp/src/app/core/dyn-templates/shared/dnamic-template-models.ts | MenkaChaugule/hospital-management-emr | 6c9afb0cda5ca4f8ea726e083f57b7a16a35a58d | [
"MIT"
] | null | null | null | Code/Websites/DanpheEMR/wwwroot/DanpheApp/src/app/core/dyn-templates/shared/dnamic-template-models.ts | MenkaChaugule/hospital-management-emr | 6c9afb0cda5ca4f8ea726e083f57b7a16a35a58d | [
"MIT"
] | 3 | 2022-02-01T03:55:18.000Z | 2022-02-02T07:31:08.000Z | //export class QtnOptionMap {
// public QuestionId: number;
// public OptionId: number;
// public IsDefault: boolean = false;
// public ShowChildOnSelect: boolean = false;
//}
export class SelectedAnswer {
public TemplateId: number = null;
public QnairId: number = null;
public QuestionId: number = null;
public Answer: string = null;
public IsActive: boolean = true;
}
export class Template {
public TemplateId: number = 0;
public Code: string = null;
public Text: string = null;
public ModuleName: string = null;
public Qnairs: Array<Questionnaire> = null;
constructor() {
}
}
export class Questionnaire {
public QnairId: number = 0;
public Text: string = null;
public TemplateId: number = 0;
//to set the display position of this Section inside the Template.
public DisplaySeq: number = 0;
public ChildQuestions: Array<Question> = new Array<Question>();
}
export class Option {
public OptionId: number = 0;
public QuestionId: number = 0;
public Text: string = null;
public IsDefault: boolean = false;
public ShowChildOnSelect: boolean = false;
public IsSelected: boolean = false;
public IsActive: boolean = true;
//to track whether this Entity (option) is unchanged, modified, added, deleted.
//default value is unchanged
public EntityState: string = "unchanged";
constructor() {
}
}
export class Question {
public QuestionId: number = 0;
public QnairId: number = 0;
public TemplateId: number = 0;
public ParentQtnId: number = null;
public Text: string = null;
public Type: string = null;
public ShowChilds: boolean = false;//whether or not to show childquestions (default-false)
public ShowAnswers: boolean = true;//this is required when Textbox needs to be shown/hidden based on Plus or Minus sign (sud:2July'18)
//to set the display position of this question inside the questionnaire.
public DisplaySeq: number = 0;
public QtnHRCLevel: number = 0;//this gives hierarchy level of this question.
public ChildQtnAlignment: string = "vertical";
public Options: Array<Option> = null;
public SelectedAnswer: string = null;
public ChildQuestions: Array<Question> = new Array<Question>();
constructor() {
this.Type = "text";//default type is text
this.Options = new Array<Option>();
}
public static GetSelectedAns(qtn: Question): Array<SelectedAnswer> {
let selAnswers: Array<SelectedAnswer> = [];
let ansText = null;
if (qtn.SelectedAnswer) {
switch (qtn.Type) {
case "table":
ansText = JSON.stringify(qtn.SelectedAnswer);
break;
case "search-tbx":
let selAns: any = qtn.SelectedAnswer;
//when we assign selected value to the searchbox, the 'value' property is not set initially.
ansText = selAns.value ? selAns.value : selAns;
break;
default:
ansText = qtn.SelectedAnswer;
break;
}
//ansText = qtn.Type != "table" ? qtn.SelectedAnswer : JSON.stringify(qtn.SelectedAnswer);
selAnswers.push({ QuestionId: qtn.QuestionId, TemplateId: qtn.TemplateId, Answer: ansText, QnairId: qtn.QnairId, IsActive: true });
}
return selAnswers;
}
//set selected answer to this question.//need to change this from checkbox list.
public static SetSelectedAnswer(qtn: Question, selAns: SelectedAnswer) {
if (qtn) {
qtn.SelectedAnswer = selAns.Answer;
//for textbox, if there's some answer already filled, show the textbox, else it'll remain hidden and only open on click of plus button
if (qtn.Type == "text" && qtn.SelectedAnswer) {
qtn.ShowAnswers = true;
}
if (qtn.Options) {
let selOpt = qtn.Options.find(o => o.Text == selAns.Answer);
if (selOpt) {
selOpt.IsSelected = true;
if (selOpt.ShowChildOnSelect) {
qtn.ShowChilds = true;
}
else {
qtn.ShowChilds = false;
}
}
}
}
}
//set selected answer to this question.
public static ResetAnswers(qtn: Question) {
if (qtn) {
qtn.ShowChilds = false;
qtn.SelectedAnswer = null;
if (qtn.Options) {
qtn.Options.forEach(opt => {
opt.IsSelected = false;
});
//let selOpt = qtn.Options.find(o => o.Text == selAns.Answer);
//if (selOpt) {
// selOpt.IsSelected = true;
// if (selOpt.ShowChildOnSelect) {
// qtn.ShowChilds = true;
// }
// else {
// qtn.ShowChilds = false;
// }
//}
}
}
}
}
| 34.486667 | 146 | 0.570269 | 106 | 8 | 0 | 6 | 4 | 37 | 0 | 1 | 33 | 5 | 0 | 6.125 | 1,259 | 0.01112 | 0.003177 | 0.029388 | 0.003971 | 0 | 0.018182 | 0.6 | 0.211765 | //export class QtnOptionMap {
// public QuestionId: number;
// public OptionId: number;
// public IsDefault: boolean = false;
// public ShowChildOnSelect: boolean = false;
//}
export class SelectedAnswer {
public TemplateId = null;
public QnairId = null;
public QuestionId = null;
public Answer = null;
public IsActive = true;
}
export class Template {
public TemplateId = 0;
public Code = null;
public Text = null;
public ModuleName = null;
public Qnairs = null;
constructor() {
}
}
export class Questionnaire {
public QnairId = 0;
public Text = null;
public TemplateId = 0;
//to set the display position of this Section inside the Template.
public DisplaySeq = 0;
public ChildQuestions = new Array<Question>();
}
export class Option {
public OptionId = 0;
public QuestionId = 0;
public Text = null;
public IsDefault = false;
public ShowChildOnSelect = false;
public IsSelected = false;
public IsActive = true;
//to track whether this Entity (option) is unchanged, modified, added, deleted.
//default value is unchanged
public EntityState = "unchanged";
constructor() {
}
}
export class Question {
public QuestionId = 0;
public QnairId = 0;
public TemplateId = 0;
public ParentQtnId = null;
public Text = null;
public Type = null;
public ShowChilds = false;//whether or not to show childquestions (default-false)
public ShowAnswers = true;//this is required when Textbox needs to be shown/hidden based on Plus or Minus sign (sud:2July'18)
//to set the display position of this question inside the questionnaire.
public DisplaySeq = 0;
public QtnHRCLevel = 0;//this gives hierarchy level of this question.
public ChildQtnAlignment = "vertical";
public Options = null;
public SelectedAnswer = null;
public ChildQuestions = new Array<Question>();
constructor() {
this.Type = "text";//default type is text
this.Options = new Array<Option>();
}
public static GetSelectedAns(qtn) {
let selAnswers = [];
let ansText = null;
if (qtn.SelectedAnswer) {
switch (qtn.Type) {
case "table":
ansText = JSON.stringify(qtn.SelectedAnswer);
break;
case "search-tbx":
let selAns = qtn.SelectedAnswer;
//when we assign selected value to the searchbox, the 'value' property is not set initially.
ansText = selAns.value ? selAns.value : selAns;
break;
default:
ansText = qtn.SelectedAnswer;
break;
}
//ansText = qtn.Type != "table" ? qtn.SelectedAnswer : JSON.stringify(qtn.SelectedAnswer);
selAnswers.push({ QuestionId: qtn.QuestionId, TemplateId: qtn.TemplateId, Answer: ansText, QnairId: qtn.QnairId, IsActive: true });
}
return selAnswers;
}
//set selected answer to this question.//need to change this from checkbox list.
public static SetSelectedAnswer(qtn, selAns) {
if (qtn) {
qtn.SelectedAnswer = selAns.Answer;
//for textbox, if there's some answer already filled, show the textbox, else it'll remain hidden and only open on click of plus button
if (qtn.Type == "text" && qtn.SelectedAnswer) {
qtn.ShowAnswers = true;
}
if (qtn.Options) {
let selOpt = qtn.Options.find(o => o.Text == selAns.Answer);
if (selOpt) {
selOpt.IsSelected = true;
if (selOpt.ShowChildOnSelect) {
qtn.ShowChilds = true;
}
else {
qtn.ShowChilds = false;
}
}
}
}
}
//set selected answer to this question.
public static ResetAnswers(qtn) {
if (qtn) {
qtn.ShowChilds = false;
qtn.SelectedAnswer = null;
if (qtn.Options) {
qtn.Options.forEach(opt => {
opt.IsSelected = false;
});
//let selOpt = qtn.Options.find(o => o.Text == selAns.Answer);
//if (selOpt) {
// selOpt.IsSelected = true;
// if (selOpt.ShowChildOnSelect) {
// qtn.ShowChilds = true;
// }
// else {
// qtn.ShowChilds = false;
// }
//}
}
}
}
}
|
251dc8a6bd0853f15cfeabfb12becc4052d3fe54 | 6,456 | ts | TypeScript | src/utils/numbers.ts | maeng2418/maeng-design | b7445d872ce0640344d8c33c0ac74dbc69b73c0a | [
"MIT"
] | 7 | 2022-01-05T13:52:04.000Z | 2022-01-24T14:58:26.000Z | src/utils/numbers.ts | maeng2418/maeng-design | b7445d872ce0640344d8c33c0ac74dbc69b73c0a | [
"MIT"
] | 12 | 2022-01-02T09:03:04.000Z | 2022-02-13T09:22:36.000Z | src/utils/numbers.ts | maeng2418/maeng-design | b7445d872ce0640344d8c33c0ac74dbc69b73c0a | [
"MIT"
] | null | null | null | type ValueType = string | number;
const isE = (number: ValueType) => {
const str = String(number);
return !Number.isNaN(Number(str)) && str.includes('e');
};
export const trimNumber = (numStr: string) => {
let str = numStr.trim();
if (str === '' || str === '0') {
return {
negative: false,
negativeStr: '',
trimStr: '',
integerStr: '0',
decimalStr: '',
fullStr: str,
};
}
let negative = str.startsWith('-');
if (negative) {
str = str.slice(1);
}
str = str
// Remove decimal 0. `1.000` => `1.`, `1.100` => `1.1`
.replace(/(\.\d*[^0])0*$/, '$1')
// Remove useless decimal. `1.` => `1`
.replace(/\.0*$/, '')
// Remove integer 0. `0001` => `1`, 000.1' => `.1`
.replace(/^0+/, '');
if (str.startsWith('.')) {
str = `0${str}`;
}
const trimStr = str || '0';
const splitNumber = trimStr.split('.');
const integerStr = splitNumber[0] || '0';
const decimalStr = splitNumber[1] || '0';
if (integerStr === '0' && decimalStr === '0') {
negative = false;
}
const negativeStr = negative ? '-' : '';
return {
negative,
negativeStr,
trimStr,
integerStr,
decimalStr,
fullStr: `${negativeStr}${trimStr}`,
};
};
const validateNumber = (num: string | number) => {
if (typeof num === 'number') {
return !Number.isNaN(num);
}
// Empty
if (!num) {
return false;
}
return (
// Normal type: 11.28
/^\s*-?\d+(\.\d+)?\s*$/.test(num) ||
// Pre-number: 1.
/^\s*-?\d+\.\s*$/.test(num) ||
// Post-number: .1
/^\s*-?\.\d+\s*$/.test(num)
);
};
const getNumberPrecision = (number: ValueType) => {
const numStr = String(number);
if (isE(number)) {
let precision = Number(numStr.slice(numStr.indexOf('e-') + 2));
const decimalMatch = numStr.match(/\.(\d+)/);
if (decimalMatch?.[1]) {
precision += decimalMatch[1].length;
}
return precision;
}
return numStr.includes('.') && validateNumber(numStr)
? numStr.length - numStr.indexOf('.') - 1
: 0;
};
const maxPrecision = (pre: ValueType, cur: ValueType) =>
Math.max(getNumberPrecision(pre), getNumberPrecision(cur));
const add = (pre: ValueType, cur: ValueType) => {
const preValue = Number(pre);
const curValue = Number(cur);
const totalValue = preValue + curValue;
if (totalValue > Number.MAX_SAFE_INTEGER || totalValue < Number.MIN_SAFE_INTEGER) {
return bigIntDecimalAdd(pre, cur);
}
return totalValue.toFixed(maxPrecision(pre, cur));
};
const makeBigIntDecimal = (value: ValueType) => {
// We need convert back to Number since it require `toFixed` to handle this
if (isE(value)) {
value = Number(value);
}
value = typeof value === 'string' ? value : num2str(value);
if (validateNumber(value)) {
const trimRet = trimNumber(value);
const numbers = trimRet.trimStr.split('.');
const decimalStr = numbers[1] || '0';
return {
value: value,
negative: trimRet.negative,
integer: BigInt(numbers[0]),
decimal: BigInt(decimalStr),
decimalLen: decimalStr.length,
};
}
return null;
};
type BigIntDecimalType = {
value: string;
negative: boolean;
integer: BigInt;
decimal: BigInt;
decimalLen: number;
};
const bigIntDecimalAdd = (pre: ValueType, cur: ValueType) => {
const preValue = makeBigIntDecimal(pre) as BigIntDecimalType;
const curValue = makeBigIntDecimal(cur) as BigIntDecimalType;
if (!preValue || !curValue) return '';
const maxDecimalLength = Math.max(
preValue.decimal.toString().padStart(preValue.decimalLen, '0').length,
curValue.decimal.toString().padStart(curValue.decimalLen, '0').length,
);
const preDecimal = BigInt(
`${preValue.negative ? '-' : ''}${preValue.integer.toString()}${preValue.decimal
.toString()
.padStart(preValue.decimalLen, '0')
.padEnd(maxDecimalLength, '0')}`,
);
const curDecimal = BigInt(
`${curValue.negative ? '-' : ''}${curValue.integer.toString()}${curValue.decimal
.toString()
.padStart(curValue.decimalLen, '0')
.padEnd(maxDecimalLength, '0')}`,
);
const valueStr = (preDecimal + curDecimal).toString();
// We need fill string length back to `maxDecimalLength` to avoid parser failed
const { negativeStr, trimStr } = trimNumber(valueStr);
const hydrateValueStr = `${negativeStr}${trimStr.padStart(maxDecimalLength + 1, '0')}`;
return trimNumber(
`${hydrateValueStr.slice(0, -maxDecimalLength)}.${hydrateValueStr.slice(-maxDecimalLength)}`,
).fullStr;
};
export const num2str = (value: number): string => {
let numIn = value.toString();
if (value < Number.MAX_SAFE_INTEGER && value > Number.MIN_SAFE_INTEGER) return numIn;
let sign = ''; // To remember the number sign
if (numIn.charAt(0) === '-') {
numIn = numIn.substring(1);
sign = '-';
}
let str = numIn.split(/[eE]/g); // Split numberic string at e or E
if (str.length < 2) return sign + numIn; // Not an Exponent Number? Exit with orginal Num back
const power = Number(str[1]); // Get Exponent (Power) (could be + or -)
if (!power || power === 0) return sign + str[0]; // If 0 exponents (i.e. 0|-0|+0) then That's any easy one
const deciSp = (1.1).toLocaleString().substring(1, 2); // Get Deciaml Separator
str = str[0].split(deciSp); // Split the Base Number into LH and RH at the decimal point
let baseRH = str[1] || ''; // RH Base part. Make sure we have a RH fraction else ""
let baseLH = str[0]; // LH base part.
if (power > 0) {
// ------- Positive Exponents (Process the RH Base Part)
if (power > baseRH.length) baseRH += '0'.repeat(power - baseRH.length); // Pad with "0" at RH
baseRH = baseRH.slice(0, power) + deciSp + baseRH.slice(power); // Insert decSep at the correct place into RH base
if (baseRH.charAt(baseRH.length - 1) === deciSp) baseRH = baseRH.slice(0, -1); // If decSep at RH end? => remove it
} else {
// ------- Negative Exponents (Process the LH Base Part)
const num = Math.abs(power) - baseLH.length; // Delta necessary 0's
if (num > 0) baseLH = '0'.repeat(num) + baseLH; // Pad with "0" at LH
baseLH = baseLH.slice(0, power) + deciSp + baseLH.slice(power); // Insert "." at the correct place into LH base
if (baseLH.charAt(0) === deciSp) baseLH = '0' + baseLH; // If decSep at LH most? => add "0"
}
return sign + baseLH + baseRH; // Return the long number (with sign)
};
export default add;
| 29.614679 | 119 | 0.613383 | 165 | 9 | 0 | 12 | 42 | 5 | 8 | 0 | 10 | 2 | 4 | 15.444444 | 2,000 | 0.0105 | 0.021 | 0.0025 | 0.001 | 0.002 | 0 | 0.147059 | 0.266423 | type ValueType = string | number;
/* Example usages of 'isE' are shown below:
isE(number);
isE(value);
*/
const isE = (number) => {
const str = String(number);
return !Number.isNaN(Number(str)) && str.includes('e');
};
export /* Example usages of 'trimNumber' are shown below:
trimNumber(value);
trimNumber(valueStr);
trimNumber(`${hydrateValueStr.slice(0, -maxDecimalLength)}.${hydrateValueStr.slice(-maxDecimalLength)}`).fullStr;
*/
const trimNumber = (numStr) => {
let str = numStr.trim();
if (str === '' || str === '0') {
return {
negative: false,
negativeStr: '',
trimStr: '',
integerStr: '0',
decimalStr: '',
fullStr: str,
};
}
let negative = str.startsWith('-');
if (negative) {
str = str.slice(1);
}
str = str
// Remove decimal 0. `1.000` => `1.`, `1.100` => `1.1`
.replace(/(\.\d*[^0])0*$/, '$1')
// Remove useless decimal. `1.` => `1`
.replace(/\.0*$/, '')
// Remove integer 0. `0001` => `1`, 000.1' => `.1`
.replace(/^0+/, '');
if (str.startsWith('.')) {
str = `0${str}`;
}
const trimStr = str || '0';
const splitNumber = trimStr.split('.');
const integerStr = splitNumber[0] || '0';
const decimalStr = splitNumber[1] || '0';
if (integerStr === '0' && decimalStr === '0') {
negative = false;
}
const negativeStr = negative ? '-' : '';
return {
negative,
negativeStr,
trimStr,
integerStr,
decimalStr,
fullStr: `${negativeStr}${trimStr}`,
};
};
/* Example usages of 'validateNumber' are shown below:
numStr.includes('.') && validateNumber(numStr)
? numStr.length - numStr.indexOf('.') - 1
: 0;
validateNumber(value);
*/
const validateNumber = (num) => {
if (typeof num === 'number') {
return !Number.isNaN(num);
}
// Empty
if (!num) {
return false;
}
return (
// Normal type: 11.28
/^\s*-?\d+(\.\d+)?\s*$/.test(num) ||
// Pre-number: 1.
/^\s*-?\d+\.\s*$/.test(num) ||
// Post-number: .1
/^\s*-?\.\d+\s*$/.test(num)
);
};
/* Example usages of 'getNumberPrecision' are shown below:
Math.max(getNumberPrecision(pre), getNumberPrecision(cur));
*/
const getNumberPrecision = (number) => {
const numStr = String(number);
if (isE(number)) {
let precision = Number(numStr.slice(numStr.indexOf('e-') + 2));
const decimalMatch = numStr.match(/\.(\d+)/);
if (decimalMatch?.[1]) {
precision += decimalMatch[1].length;
}
return precision;
}
return numStr.includes('.') && validateNumber(numStr)
? numStr.length - numStr.indexOf('.') - 1
: 0;
};
/* Example usages of 'maxPrecision' are shown below:
totalValue.toFixed(maxPrecision(pre, cur));
*/
const maxPrecision = (pre, cur) =>
Math.max(getNumberPrecision(pre), getNumberPrecision(cur));
/* Example usages of 'add' are shown below:
;
*/
const add = (pre, cur) => {
const preValue = Number(pre);
const curValue = Number(cur);
const totalValue = preValue + curValue;
if (totalValue > Number.MAX_SAFE_INTEGER || totalValue < Number.MIN_SAFE_INTEGER) {
return bigIntDecimalAdd(pre, cur);
}
return totalValue.toFixed(maxPrecision(pre, cur));
};
/* Example usages of 'makeBigIntDecimal' are shown below:
makeBigIntDecimal(pre);
makeBigIntDecimal(cur);
*/
const makeBigIntDecimal = (value) => {
// We need convert back to Number since it require `toFixed` to handle this
if (isE(value)) {
value = Number(value);
}
value = typeof value === 'string' ? value : num2str(value);
if (validateNumber(value)) {
const trimRet = trimNumber(value);
const numbers = trimRet.trimStr.split('.');
const decimalStr = numbers[1] || '0';
return {
value: value,
negative: trimRet.negative,
integer: BigInt(numbers[0]),
decimal: BigInt(decimalStr),
decimalLen: decimalStr.length,
};
}
return null;
};
type BigIntDecimalType = {
value;
negative;
integer;
decimal;
decimalLen;
};
/* Example usages of 'bigIntDecimalAdd' are shown below:
bigIntDecimalAdd(pre, cur);
*/
const bigIntDecimalAdd = (pre, cur) => {
const preValue = makeBigIntDecimal(pre) as BigIntDecimalType;
const curValue = makeBigIntDecimal(cur) as BigIntDecimalType;
if (!preValue || !curValue) return '';
const maxDecimalLength = Math.max(
preValue.decimal.toString().padStart(preValue.decimalLen, '0').length,
curValue.decimal.toString().padStart(curValue.decimalLen, '0').length,
);
const preDecimal = BigInt(
`${preValue.negative ? '-' : ''}${preValue.integer.toString()}${preValue.decimal
.toString()
.padStart(preValue.decimalLen, '0')
.padEnd(maxDecimalLength, '0')}`,
);
const curDecimal = BigInt(
`${curValue.negative ? '-' : ''}${curValue.integer.toString()}${curValue.decimal
.toString()
.padStart(curValue.decimalLen, '0')
.padEnd(maxDecimalLength, '0')}`,
);
const valueStr = (preDecimal + curDecimal).toString();
// We need fill string length back to `maxDecimalLength` to avoid parser failed
const { negativeStr, trimStr } = trimNumber(valueStr);
const hydrateValueStr = `${negativeStr}${trimStr.padStart(maxDecimalLength + 1, '0')}`;
return trimNumber(
`${hydrateValueStr.slice(0, -maxDecimalLength)}.${hydrateValueStr.slice(-maxDecimalLength)}`,
).fullStr;
};
export /* Example usages of 'num2str' are shown below:
value = typeof value === 'string' ? value : num2str(value);
*/
const num2str = (value) => {
let numIn = value.toString();
if (value < Number.MAX_SAFE_INTEGER && value > Number.MIN_SAFE_INTEGER) return numIn;
let sign = ''; // To remember the number sign
if (numIn.charAt(0) === '-') {
numIn = numIn.substring(1);
sign = '-';
}
let str = numIn.split(/[eE]/g); // Split numberic string at e or E
if (str.length < 2) return sign + numIn; // Not an Exponent Number? Exit with orginal Num back
const power = Number(str[1]); // Get Exponent (Power) (could be + or -)
if (!power || power === 0) return sign + str[0]; // If 0 exponents (i.e. 0|-0|+0) then That's any easy one
const deciSp = (1.1).toLocaleString().substring(1, 2); // Get Deciaml Separator
str = str[0].split(deciSp); // Split the Base Number into LH and RH at the decimal point
let baseRH = str[1] || ''; // RH Base part. Make sure we have a RH fraction else ""
let baseLH = str[0]; // LH base part.
if (power > 0) {
// ------- Positive Exponents (Process the RH Base Part)
if (power > baseRH.length) baseRH += '0'.repeat(power - baseRH.length); // Pad with "0" at RH
baseRH = baseRH.slice(0, power) + deciSp + baseRH.slice(power); // Insert decSep at the correct place into RH base
if (baseRH.charAt(baseRH.length - 1) === deciSp) baseRH = baseRH.slice(0, -1); // If decSep at RH end? => remove it
} else {
// ------- Negative Exponents (Process the LH Base Part)
const num = Math.abs(power) - baseLH.length; // Delta necessary 0's
if (num > 0) baseLH = '0'.repeat(num) + baseLH; // Pad with "0" at LH
baseLH = baseLH.slice(0, power) + deciSp + baseLH.slice(power); // Insert "." at the correct place into LH base
if (baseLH.charAt(0) === deciSp) baseLH = '0' + baseLH; // If decSep at LH most? => add "0"
}
return sign + baseLH + baseRH; // Return the long number (with sign)
};
export default add;
|
25335682afb4019e0263822c0b985ba9eed1e0d4 | 4,930 | ts | TypeScript | src/finnish-ssn.ts | haukurmar/finnish-ssn-validator | a04159e2570aef75939c63b1fc9cef4384bc766d | [
"MIT"
] | null | null | null | src/finnish-ssn.ts | haukurmar/finnish-ssn-validator | a04159e2570aef75939c63b1fc9cef4384bc766d | [
"MIT"
] | null | null | null | src/finnish-ssn.ts | haukurmar/finnish-ssn-validator | a04159e2570aef75939c63b1fc9cef4384bc766d | [
"MIT"
] | 1 | 2022-03-11T13:35:27.000Z | 2022-03-11T13:35:27.000Z | 'use strict'
interface SSN {
valid: boolean
sex: string
ageInYears: number
dateOfBirth: Date
}
export class FinnishSSN {
public static FEMALE = 'female'
public static MALE = 'male'
/**
* Parse parameter given SSN string into Object representation.
* @param ssn - {String} SSN to parse
*/
public static parse(ssn: string): SSN {
// Sanity and format check, which allows to make safe assumptions on the format.
if (!SSN_REGEX.test(ssn)) {
throw new Error('Not valid SSN format')
}
const dayOfMonth = parseInt(ssn.substring(0, 2), 10)
const month = ssn.substring(2, 4)
const centuryId = ssn.charAt(6)
const year = parseInt(ssn.substring(4, 6), 10) + centuryMap.get(centuryId)!
const rollingId = ssn.substring(7, 10)
const checksum = ssn.substring(10, 11)
const sex = parseInt(rollingId, 10) % 2 ? this.MALE : this.FEMALE
const daysInMonth = daysInGivenMonth(year, month)
if (!daysInMonthMap.get(month) || dayOfMonth > daysInMonth) {
throw new Error('Not valid SSN')
}
const checksumBase = parseInt(ssn.substring(0, 6) + rollingId, 10)
const dateOfBirth = new Date(year, parseInt(month, 10) - 1, dayOfMonth, 0, 0, 0, 0)
const today = new Date()
return {
valid: checksum === checksumTable[checksumBase % 31],
sex,
dateOfBirth,
ageInYears: ageInYears(dateOfBirth, today)
}
}
/**
* Validates parameter given SSN. Returns true if SSN is valid, otherwise false.
* @param ssn - {String} For example '010190-123A'
*/
public static validate(ssn: string): boolean {
try {
return this.parse(ssn).valid
} catch (error) {
return false
}
}
/**
* Creates a valid SSN using the given age (Integer). Creates randomly male and female SSN'n.
* In case an invalid age is given, throws exception.
*
* @param age as Integer. Min valid age is 1, max valid age is 200
*/
public static createWithAge(age: number): string {
if (age < MIN_AGE || age > MAX_AGE) {
throw new Error(`Given age (${age}) is not between sensible age range of ${MIN_AGE} and ${MAX_AGE}`)
}
const today = new Date()
let year = today.getFullYear() - age
const month = randomMonth()
const dayOfMonth = randomDay(year, month)
let centurySign
const rollingId = randomNumber(800) + 99 // No need for padding when rollingId >= 100
centuryMap.forEach((value: number, key: string) => {
if (value === Math.floor(year / 100) * 100) {
centurySign = key
}
})
if (!birthDayPassed(new Date(year, Number(month) - 1, Number(dayOfMonth)), today)) {
year--
}
year = year % 100
const yearString = yearToPaddedString(year)
const checksumBase = parseInt(dayOfMonth + month + yearString + rollingId, 10)
const checksum = checksumTable[checksumBase % 31]
return dayOfMonth + month + yearString + centurySign + rollingId + checksum
}
public static isLeapYear(year: number): boolean {
return (year % 4 === 0 && year % 100 !== 0) || year % 400 === 0
}
}
const centuryMap: Map<string, number> = new Map()
centuryMap.set('A', 2000)
centuryMap.set('-', 1900)
centuryMap.set('+', 1800)
const february = '02'
const daysInMonthMap: Map<string, number> = new Map()
daysInMonthMap.set('01', 31)
daysInMonthMap.set('02', 28)
daysInMonthMap.set('03', 31)
daysInMonthMap.set('04', 30)
daysInMonthMap.set('05', 31)
daysInMonthMap.set('06', 30)
daysInMonthMap.set('07', 31)
daysInMonthMap.set('08', 31)
daysInMonthMap.set('09', 30)
daysInMonthMap.set('10', 31)
daysInMonthMap.set('11', 30)
daysInMonthMap.set('12', 31)
const checksumTable: string[] = '0123456789ABCDEFHJKLMNPRSTUVWXY'.split('')
const MIN_AGE = 1
const MAX_AGE = 200
const SSN_REGEX = /^(0[1-9]|[12]\d|3[01])(0[1-9]|1[0-2])([5-9]\d\+|\d\d-|[012]\dA)\d{3}[\dA-Z]$/
function randomMonth(): string {
return `00${randomNumber(12)}`.substr(-2, 2)
}
function yearToPaddedString(year: number): string {
return year % 100 < 10 ? `0${year}` : year.toString()
}
function randomDay(year: number, month: string): string {
const maxDaysInMonth = daysInGivenMonth(year, month)
return `00${randomNumber(maxDaysInMonth)}`.substr(-2, 2)
}
function daysInGivenMonth(year: number, month: string) {
const daysInMonth = daysInMonthMap.get(month)!
return month === february && FinnishSSN.isLeapYear(year) ? daysInMonth + 1 : daysInMonth
}
function randomNumber(max: number): number {
return Math.floor(Math.random() * max) + 1 // no zero
}
function ageInYears(dateOfBirth: Date, today: Date): number {
return today.getFullYear() - dateOfBirth.getFullYear() - (birthDayPassed(dateOfBirth, today) ? 0 : 1)
}
function birthDayPassed(dateOfBirth: Date, today: Date): boolean {
return (
dateOfBirth.getMonth() < today.getMonth() ||
(dateOfBirth.getMonth() === today.getMonth() && dateOfBirth.getDate() <= today.getDate())
)
}
| 30.8125 | 106 | 0.663895 | 118 | 12 | 0 | 16 | 29 | 6 | 9 | 0 | 29 | 2 | 0 | 5.5 | 1,663 | 0.016837 | 0.017438 | 0.003608 | 0.001203 | 0 | 0 | 0.460317 | 0.270054 | 'use strict'
interface SSN {
valid
sex
ageInYears
dateOfBirth
}
export class FinnishSSN {
public static FEMALE = 'female'
public static MALE = 'male'
/**
* Parse parameter given SSN string into Object representation.
* @param ssn - {String} SSN to parse
*/
public static parse(ssn) {
// Sanity and format check, which allows to make safe assumptions on the format.
if (!SSN_REGEX.test(ssn)) {
throw new Error('Not valid SSN format')
}
const dayOfMonth = parseInt(ssn.substring(0, 2), 10)
const month = ssn.substring(2, 4)
const centuryId = ssn.charAt(6)
const year = parseInt(ssn.substring(4, 6), 10) + centuryMap.get(centuryId)!
const rollingId = ssn.substring(7, 10)
const checksum = ssn.substring(10, 11)
const sex = parseInt(rollingId, 10) % 2 ? this.MALE : this.FEMALE
const daysInMonth = daysInGivenMonth(year, month)
if (!daysInMonthMap.get(month) || dayOfMonth > daysInMonth) {
throw new Error('Not valid SSN')
}
const checksumBase = parseInt(ssn.substring(0, 6) + rollingId, 10)
const dateOfBirth = new Date(year, parseInt(month, 10) - 1, dayOfMonth, 0, 0, 0, 0)
const today = new Date()
return {
valid: checksum === checksumTable[checksumBase % 31],
sex,
dateOfBirth,
ageInYears: ageInYears(dateOfBirth, today)
}
}
/**
* Validates parameter given SSN. Returns true if SSN is valid, otherwise false.
* @param ssn - {String} For example '010190-123A'
*/
public static validate(ssn) {
try {
return this.parse(ssn).valid
} catch (error) {
return false
}
}
/**
* Creates a valid SSN using the given age (Integer). Creates randomly male and female SSN'n.
* In case an invalid age is given, throws exception.
*
* @param age as Integer. Min valid age is 1, max valid age is 200
*/
public static createWithAge(age) {
if (age < MIN_AGE || age > MAX_AGE) {
throw new Error(`Given age (${age}) is not between sensible age range of ${MIN_AGE} and ${MAX_AGE}`)
}
const today = new Date()
let year = today.getFullYear() - age
const month = randomMonth()
const dayOfMonth = randomDay(year, month)
let centurySign
const rollingId = randomNumber(800) + 99 // No need for padding when rollingId >= 100
centuryMap.forEach((value, key) => {
if (value === Math.floor(year / 100) * 100) {
centurySign = key
}
})
if (!birthDayPassed(new Date(year, Number(month) - 1, Number(dayOfMonth)), today)) {
year--
}
year = year % 100
const yearString = yearToPaddedString(year)
const checksumBase = parseInt(dayOfMonth + month + yearString + rollingId, 10)
const checksum = checksumTable[checksumBase % 31]
return dayOfMonth + month + yearString + centurySign + rollingId + checksum
}
public static isLeapYear(year) {
return (year % 4 === 0 && year % 100 !== 0) || year % 400 === 0
}
}
const centuryMap = new Map()
centuryMap.set('A', 2000)
centuryMap.set('-', 1900)
centuryMap.set('+', 1800)
const february = '02'
const daysInMonthMap = new Map()
daysInMonthMap.set('01', 31)
daysInMonthMap.set('02', 28)
daysInMonthMap.set('03', 31)
daysInMonthMap.set('04', 30)
daysInMonthMap.set('05', 31)
daysInMonthMap.set('06', 30)
daysInMonthMap.set('07', 31)
daysInMonthMap.set('08', 31)
daysInMonthMap.set('09', 30)
daysInMonthMap.set('10', 31)
daysInMonthMap.set('11', 30)
daysInMonthMap.set('12', 31)
const checksumTable = '0123456789ABCDEFHJKLMNPRSTUVWXY'.split('')
const MIN_AGE = 1
const MAX_AGE = 200
const SSN_REGEX = /^(0[1-9]|[12]\d|3[01])(0[1-9]|1[0-2])([5-9]\d\+|\d\d-|[012]\dA)\d{3}[\dA-Z]$/
/* Example usages of 'randomMonth' are shown below:
randomMonth();
*/
function randomMonth() {
return `00${randomNumber(12)}`.substr(-2, 2)
}
/* Example usages of 'yearToPaddedString' are shown below:
yearToPaddedString(year);
*/
function yearToPaddedString(year) {
return year % 100 < 10 ? `0${year}` : year.toString()
}
/* Example usages of 'randomDay' are shown below:
randomDay(year, month);
*/
function randomDay(year, month) {
const maxDaysInMonth = daysInGivenMonth(year, month)
return `00${randomNumber(maxDaysInMonth)}`.substr(-2, 2)
}
/* Example usages of 'daysInGivenMonth' are shown below:
daysInGivenMonth(year, month);
*/
function daysInGivenMonth(year, month) {
const daysInMonth = daysInMonthMap.get(month)!
return month === february && FinnishSSN.isLeapYear(year) ? daysInMonth + 1 : daysInMonth
}
/* Example usages of 'randomNumber' are shown below:
randomNumber(800) + 99 // No need for padding when rollingId >= 100
;
randomNumber(12);
randomNumber(maxDaysInMonth);
*/
function randomNumber(max) {
return Math.floor(Math.random() * max) + 1 // no zero
}
/* Example usages of 'ageInYears' are shown below:
;
ageInYears(dateOfBirth, today);
*/
function ageInYears(dateOfBirth, today) {
return today.getFullYear() - dateOfBirth.getFullYear() - (birthDayPassed(dateOfBirth, today) ? 0 : 1)
}
/* Example usages of 'birthDayPassed' are shown below:
!birthDayPassed(new Date(year, Number(month) - 1, Number(dayOfMonth)), today);
birthDayPassed(dateOfBirth, today) ? 0 : 1;
*/
function birthDayPassed(dateOfBirth, today) {
return (
dateOfBirth.getMonth() < today.getMonth() ||
(dateOfBirth.getMonth() === today.getMonth() && dateOfBirth.getDate() <= today.getDate())
)
}
|
25b448e96d1b18f4a79d264e8acb10b1e644ba7c | 3,249 | ts | TypeScript | src/ParametersManager.ts | Yghore/KiwiLaunchMC | 45ffa4a9fe2cbbfa794890a0353b414d5a99619c | [
"MIT"
] | null | null | null | src/ParametersManager.ts | Yghore/KiwiLaunchMC | 45ffa4a9fe2cbbfa794890a0353b414d5a99619c | [
"MIT"
] | 3 | 2022-03-17T08:38:16.000Z | 2022-03-23T10:53:46.000Z | src/ParametersManager.ts | Yghore/KiwiLaunchMC | 45ffa4a9fe2cbbfa794890a0353b414d5a99619c | [
"MIT"
] | null | null | null | export class ParametersManager
{
private minRamParam : string;
private maxRamParam : string;
/**
*
* @param minRam (MIN = 1024)
* @param maxRam (MAX = 16384)
* @param size "Style of the size, 'M' for MO AND 'G' for 'G'"
* exemple : (3, 16, "G");
*/
constructor(public minRam : number, public maxRam : number, public size : string = "M", public extra? : Array<string>)
{
if(this.maxRam < this.minRam)
{
throw new Error("minRam > MaxRam : (Impossible)");
}
// -Xms1536M
// -Xmx2048M
if(size === "M"){
const MAX_SIZE : number = 16384;
const MIN_SIZE : number = 1024;
if(this.minRam <= MAX_SIZE && this.minRam >= MIN_SIZE)
{
if(Math.log2(this.minRam) % 1 === 0)
{
this.minRamParam = "-Xms" + this.minRam + "M";
}
else
{
throw new Error("The MinRam is not a Power of 2");
}
}
else {throw new Error("Minimum Ram options : " + MIN_SIZE + " Maximum Ram options : " + MAX_SIZE)}
if(this.maxRam <= MAX_SIZE && this.maxRam >= MIN_SIZE)
{
if(Math.log2(this.maxRam) % 1 === 0)
{
this.maxRamParam = "-Xmx" + this.maxRam + "M";
}
else
{
throw new Error("The MaxRam is not a Power of 2");
}
}
else {throw new Error("Minimum Ram options : " + MIN_SIZE + " Maximum Ram options : " + MAX_SIZE)}
}
else{
const MAX_SIZE : number = 16;
const MIN_SIZE : number = 1;
if(this.minRam <= MAX_SIZE && this.minRam >= MIN_SIZE)
{
this.minRamParam = "-Xms" + this.minRam + "G";
}
else {throw new Error("Minimum Ram options : " + MIN_SIZE + " Maximum Ram options : " + MAX_SIZE)}
if(this.maxRam <= MAX_SIZE && this.maxRam >= MIN_SIZE)
{
this.maxRamParam = "-Xmx" + this.maxRam + "G";
}
else {throw new Error("Minimum Ram options : " + MIN_SIZE + " Maximum Ram options : " + MAX_SIZE)}
}
}
/**
* getOptionalArguments
*/
public getOptionalParameters() : string[] {
return ['-XX:+UseConcMarkSweepGC',
'-XX:+CMSIncrementalMode',
'-XX:-UseAdaptiveSizePolicy',
'-Dfml.ignoreInvalidMinecraftCertificates=true',
'-Dfml.ignorePatchDiscrepancies=true',
'-XX:+IgnoreUnrecognizedVMOptions'
];
}
public getExtraParameters() : string[]
{
return this.extra == undefined ? [] : this.extra;
}
public getRamParameters() : string[] {
return [this.minRamParam, this.maxRamParam];
}
//--username=Yghore --accessToken sry --version 1.12.2 --assetIndex 1.12 --userProperties {} --uuid nope --userType legacy --tweakClass net.minecraftforge.fml.common.launcher.FMLTweaker
} | 30.364486 | 186 | 0.484149 | 70 | 4 | 0 | 4 | 4 | 2 | 0 | 0 | 13 | 1 | 0 | 13.75 | 855 | 0.009357 | 0.004678 | 0.002339 | 0.00117 | 0 | 0 | 0.928571 | 0.207925 | export class ParametersManager
{
private minRamParam ;
private maxRamParam ;
/**
*
* @param minRam (MIN = 1024)
* @param maxRam (MAX = 16384)
* @param size "Style of the size, 'M' for MO AND 'G' for 'G'"
* exemple : (3, 16, "G");
*/
constructor(public minRam , public maxRam , public size = "M", public extra? )
{
if(this.maxRam < this.minRam)
{
throw new Error("minRam > MaxRam : (Impossible)");
}
// -Xms1536M
// -Xmx2048M
if(size === "M"){
const MAX_SIZE = 16384;
const MIN_SIZE = 1024;
if(this.minRam <= MAX_SIZE && this.minRam >= MIN_SIZE)
{
if(Math.log2(this.minRam) % 1 === 0)
{
this.minRamParam = "-Xms" + this.minRam + "M";
}
else
{
throw new Error("The MinRam is not a Power of 2");
}
}
else {throw new Error("Minimum Ram options : " + MIN_SIZE + " Maximum Ram options : " + MAX_SIZE)}
if(this.maxRam <= MAX_SIZE && this.maxRam >= MIN_SIZE)
{
if(Math.log2(this.maxRam) % 1 === 0)
{
this.maxRamParam = "-Xmx" + this.maxRam + "M";
}
else
{
throw new Error("The MaxRam is not a Power of 2");
}
}
else {throw new Error("Minimum Ram options : " + MIN_SIZE + " Maximum Ram options : " + MAX_SIZE)}
}
else{
const MAX_SIZE = 16;
const MIN_SIZE = 1;
if(this.minRam <= MAX_SIZE && this.minRam >= MIN_SIZE)
{
this.minRamParam = "-Xms" + this.minRam + "G";
}
else {throw new Error("Minimum Ram options : " + MIN_SIZE + " Maximum Ram options : " + MAX_SIZE)}
if(this.maxRam <= MAX_SIZE && this.maxRam >= MIN_SIZE)
{
this.maxRamParam = "-Xmx" + this.maxRam + "G";
}
else {throw new Error("Minimum Ram options : " + MIN_SIZE + " Maximum Ram options : " + MAX_SIZE)}
}
}
/**
* getOptionalArguments
*/
public getOptionalParameters() {
return ['-XX:+UseConcMarkSweepGC',
'-XX:+CMSIncrementalMode',
'-XX:-UseAdaptiveSizePolicy',
'-Dfml.ignoreInvalidMinecraftCertificates=true',
'-Dfml.ignorePatchDiscrepancies=true',
'-XX:+IgnoreUnrecognizedVMOptions'
];
}
public getExtraParameters()
{
return this.extra == undefined ? [] : this.extra;
}
public getRamParameters() {
return [this.minRamParam, this.maxRamParam];
}
//--username=Yghore --accessToken sry --version 1.12.2 --assetIndex 1.12 --userProperties {} --uuid nope --userType legacy --tweakClass net.minecraftforge.fml.common.launcher.FMLTweaker
} |
25e0caafe4b44bdf83b4546ea8525ce197e1c8a3 | 1,731 | ts | TypeScript | utils/validators.utils.ts | fxbits/snapcat | b3b40dfdcb228197479f66e8ca21fc5d241d2d1f | [
"MIT"
] | null | null | null | utils/validators.utils.ts | fxbits/snapcat | b3b40dfdcb228197479f66e8ca21fc5d241d2d1f | [
"MIT"
] | 10 | 2022-03-17T10:54:23.000Z | 2022-03-30T13:35:36.000Z | utils/validators.utils.ts | fxbits/snapcat | b3b40dfdcb228197479f66e8ca21fc5d241d2d1f | [
"MIT"
] | null | null | null | export const addressValidation = (e: any, setError: (msg: string) => void) => {
const value = e.target.value;
if (value === 'acasa') {
setError("Adresa nu poate fi casa ta!");
return;
}
if (value === '') {
setError("Adresa nu poate fi vida!");
return;
}
setError("");
return;
}
export const nonSterilizedCatsValidation = (e: any, setError: (msg: string) => void) => {
const value = e.target.value;
if (value < 0) {
setError("Numarul de pisici nu poate sa fie mai mic decat 0!");
return;
}
if(value > 100) {
setError("Numarul de pisici nu poate sa fie mai mare decat 100!");
return;
}
if (value === '') {
setError("Numarul de pisici nu poate sa fie vid");
return;
}
setError("");
return;
}
export const sterilizedCatsValidation = (e: any, setError: (msg: string) => void) => {
const value = e.target.value;
if (value < 0) {
setError("Numarul de pisici nu poate sa fie mai mic decat 0!");
return;
}
if(value > 100) {
setError("Numarul de pisici nu poate sa fie mai mare decat 100!");
return;
}
if (value === '') {
setError("Numarul de pisici nu poate sa fie vid");
return;
}
setError("");
return;
}
export const nameValidation = (e: any, setError: (msg: string) => void) => {
const value = e.target.value;
const nameVerif = new RegExp('^[A-Z][a-z ,.-]+$');
if (value === '') {
setError("Numele nu poate fi vid!");
return;
}
if (!nameVerif.test(value)) {
setError("Nume invalid!");
return;
}
setError("");
return;
}
| 21.6375 | 89 | 0.533795 | 61 | 4 | 0 | 8 | 9 | 0 | 0 | 4 | 8 | 0 | 0 | 13.25 | 519 | 0.023121 | 0.017341 | 0 | 0 | 0 | 0.190476 | 0.380952 | 0.277313 | export const addressValidation = (e, setError) => {
const value = e.target.value;
if (value === 'acasa') {
setError("Adresa nu poate fi casa ta!");
return;
}
if (value === '') {
setError("Adresa nu poate fi vida!");
return;
}
setError("");
return;
}
export const nonSterilizedCatsValidation = (e, setError) => {
const value = e.target.value;
if (value < 0) {
setError("Numarul de pisici nu poate sa fie mai mic decat 0!");
return;
}
if(value > 100) {
setError("Numarul de pisici nu poate sa fie mai mare decat 100!");
return;
}
if (value === '') {
setError("Numarul de pisici nu poate sa fie vid");
return;
}
setError("");
return;
}
export const sterilizedCatsValidation = (e, setError) => {
const value = e.target.value;
if (value < 0) {
setError("Numarul de pisici nu poate sa fie mai mic decat 0!");
return;
}
if(value > 100) {
setError("Numarul de pisici nu poate sa fie mai mare decat 100!");
return;
}
if (value === '') {
setError("Numarul de pisici nu poate sa fie vid");
return;
}
setError("");
return;
}
export const nameValidation = (e, setError) => {
const value = e.target.value;
const nameVerif = new RegExp('^[A-Z][a-z ,.-]+$');
if (value === '') {
setError("Numele nu poate fi vid!");
return;
}
if (!nameVerif.test(value)) {
setError("Nume invalid!");
return;
}
setError("");
return;
}
|
cd8732717f3c05fd1ec71eb4f9b08e73bb1d4dcc | 13,742 | ts | TypeScript | shared/editor/lib/markdown/serializer.ts | bisho1995/outline | dc29fb475d3a008487e2862ce42ce5791f3abd39 | [
"BSL-1.0"
] | 1 | 2022-03-15T05:51:40.000Z | 2022-03-15T05:51:40.000Z | shared/editor/lib/markdown/serializer.ts | bisho1995/outline | dc29fb475d3a008487e2862ce42ce5791f3abd39 | [
"BSL-1.0"
] | 1 | 2022-02-02T13:03:20.000Z | 2022-02-02T13:03:20.000Z | shared/editor/lib/markdown/serializer.ts | bisho1995/outline | dc29fb475d3a008487e2862ce42ce5791f3abd39 | [
"BSL-1.0"
] | null | null | null | /* eslint-disable @typescript-eslint/ban-ts-comment */
// @ts-nocheck
// https://raw.githubusercontent.com/ProseMirror/prosemirror-markdown/master/src/to_markdown.js
// forked for table support
// ::- A specification for serializing a ProseMirror document as
// Markdown/CommonMark text.
export class MarkdownSerializer {
// :: (Object<(state: MarkdownSerializerState, node: Node, parent: Node, index: number)>, Object)
// Construct a serializer with the given configuration. The `nodes`
// object should map node names in a given schema to function that
// take a serializer state and such a node, and serialize the node.
//
// The `marks` object should hold objects with `open` and `close`
// properties, which hold the strings that should appear before and
// after a piece of text marked that way, either directly or as a
// function that takes a serializer state and a mark, and returns a
// string. `open` and `close` can also be functions, which will be
// called as
//
// (state: MarkdownSerializerState, mark: Mark,
// parent: Fragment, index: number) → string
//
// Where `parent` and `index` allow you to inspect the mark's
// context to see which nodes it applies to.
//
// Mark information objects can also have a `mixable` property
// which, when `true`, indicates that the order in which the mark's
// opening and closing syntax appears relative to other mixable
// marks can be varied. (For example, you can say `**a *b***` and
// `*a **b***`, but not `` `a *b*` ``.)
//
// To disable character escaping in a mark, you can give it an
// `escape` property of `false`. Such a mark has to have the highest
// precedence (must always be the innermost mark).
//
// The `expelEnclosingWhitespace` mark property causes the
// serializer to move enclosing whitespace from inside the marks to
// outside the marks. This is necessary for emphasis marks as
// CommonMark does not permit enclosing whitespace inside emphasis
// marks, see: http://spec.commonmark.org/0.26/#example-330
constructor(nodes, marks) {
// :: Object<(MarkdownSerializerState, Node)> The node serializer
// functions for this serializer.
this.nodes = nodes;
// :: Object The mark serializer info.
this.marks = marks;
}
// :: (Node, ?Object) → string
// Serialize the content of the given node to
// [CommonMark](http://commonmark.org/).
serialize(content, options?: { tightLists?: boolean }) {
const state = new MarkdownSerializerState(this.nodes, this.marks, options);
state.renderContent(content);
return state.out;
}
}
// ::- This is an object used to track state and expose
// methods related to markdown serialization. Instances are passed to
// node and mark serialization methods (see `toMarkdown`).
export class MarkdownSerializerState {
inTable = false;
inTightList = false;
closed = false;
delim = "";
constructor(nodes, marks, options) {
this.nodes = nodes;
this.marks = marks;
this.delim = this.out = "";
this.closed = false;
this.inTightList = false;
this.inTable = false;
// :: Object
// The options passed to the serializer.
// tightLists:: ?bool
// Whether to render lists in a tight style. This can be overridden
// on a node level by specifying a tight attribute on the node.
// Defaults to false.
this.options = options || {};
if (typeof this.options.tightLists === "undefined")
this.options.tightLists = true;
}
flushClose(size) {
if (this.closed) {
if (!this.atBlank()) this.out += "\n";
if (size === null || size === undefined) size = 2;
if (size > 1) {
let delimMin = this.delim;
const trim = /\s+$/.exec(delimMin);
if (trim)
delimMin = delimMin.slice(0, delimMin.length - trim[0].length);
for (let i = 1; i < size; i++) this.out += delimMin + "\n";
}
this.closed = false;
}
}
// :: (string, ?string, Node, ())
// Render a block, prefixing each line with `delim`, and the first
// line in `firstDelim`. `node` should be the node that is closed at
// the end of the block, and `f` is a function that renders the
// content of the block.
wrapBlock(delim, firstDelim, node, f) {
const old = this.delim;
this.write(firstDelim || delim);
this.delim += delim;
f();
this.delim = old;
this.closeBlock(node);
}
atBlank() {
return /(^|\n)$/.test(this.out);
}
// :: ()
// Ensure the current content ends with a newline.
ensureNewLine() {
if (!this.atBlank()) this.out += "\n";
}
// :: (?string)
// Prepare the state for writing output (closing closed paragraphs,
// adding delimiters, and so on), and then optionally add content
// (unescaped) to the output.
write(content) {
this.flushClose();
if (this.delim && this.atBlank()) this.out += this.delim;
if (content) this.out += content;
}
// :: (Node)
// Close the block for the given node.
closeBlock(node) {
this.closed = node;
}
// :: (string, ?bool)
// Add the given text to the document. When escape is not `false`,
// it will be escaped.
text(text, escape) {
const lines = text.split("\n");
for (let i = 0; i < lines.length; i++) {
const startOfLine = this.atBlank() || this.closed;
this.write();
this.out += escape !== false ? this.esc(lines[i], startOfLine) : lines[i];
if (i !== lines.length - 1) this.out += "\n";
}
}
// :: (Node)
// Render the given node as a block.
render(node, parent, index) {
if (typeof parent === "number") throw new Error("!");
this.nodes[node.type.name](this, node, parent, index);
}
// :: (Node)
// Render the contents of `parent` as block nodes.
renderContent(parent) {
parent.forEach((node, _, i) => this.render(node, parent, i));
}
// :: (Node)
// Render the contents of `parent` as inline content.
renderInline(parent) {
const active = [];
let trailing = "";
const progress = (node, _, index) => {
let marks = node ? node.marks : [];
// Remove marks from `hard_break` that are the last node inside
// that mark to prevent parser edge cases with new lines just
// before closing marks.
// (FIXME it'd be nice if we had a schema-agnostic way to
// identify nodes that serialize as hard breaks)
if (node && node.type.name === "hard_break")
marks = marks.filter((m) => {
if (index + 1 === parent.childCount) return false;
const next = parent.child(index + 1);
return (
m.isInSet(next.marks) && (!next.isText || /\S/.test(next.text))
);
});
let leading = trailing;
trailing = "";
// If whitespace has to be expelled from the node, adjust
// leading and trailing accordingly.
if (
node &&
node.isText &&
marks.some((mark) => {
const info = this.marks[mark.type.name]();
return info && info.expelEnclosingWhitespace;
})
) {
// eslint-disable-next-line @typescript-eslint/no-unused-vars, no-unused-vars
const [_, lead, inner, trail] = /^(\s*)(.*?)(\s*)$/m.exec(node.text);
leading += lead;
trailing = trail;
if (lead || trail) {
node = inner ? node.withText(inner) : null;
if (!node) marks = active;
}
}
const inner = marks.length && marks[marks.length - 1],
noEsc = inner && this.marks[inner.type.name]().escape === false;
const len = marks.length - (noEsc ? 1 : 0);
// Try to reorder 'mixable' marks, such as em and strong, which
// in Markdown may be opened and closed in different order, so
// that order of the marks for the token matches the order in
// active.
outer: for (let i = 0; i < len; i++) {
const mark = marks[i];
if (!this.marks[mark.type.name]().mixable) break;
for (let j = 0; j < active.length; j++) {
const other = active[j];
if (!this.marks[other.type.name]().mixable) break;
if (mark.eq(other)) {
if (i > j)
marks = marks
.slice(0, j)
.concat(mark)
.concat(marks.slice(j, i))
.concat(marks.slice(i + 1, len));
else if (j > i)
marks = marks
.slice(0, i)
.concat(marks.slice(i + 1, j))
.concat(mark)
.concat(marks.slice(j, len));
continue outer;
}
}
}
// Find the prefix of the mark set that didn't change
let keep = 0;
while (
keep < Math.min(active.length, len) &&
marks[keep].eq(active[keep])
)
++keep;
// Close the marks that need to be closed
while (keep < active.length)
this.text(this.markString(active.pop(), false, parent, index), false);
// Output any previously expelled trailing whitespace outside the marks
if (leading) this.text(leading);
// Open the marks that need to be opened
if (node) {
while (active.length < len) {
const add = marks[active.length];
active.push(add);
this.text(this.markString(add, true, parent, index), false);
}
// Render the node. Special case code marks, since their content
// may not be escaped.
if (noEsc && node.isText)
this.text(
this.markString(inner, true, parent, index) +
node.text +
this.markString(inner, false, parent, index + 1),
false
);
else this.render(node, parent, index);
}
};
parent.forEach(progress);
progress(null, null, parent.childCount);
}
// :: (Node, string, (number) → string)
// Render a node's content as a list. `delim` should be the extra
// indentation added to all lines except the first in an item,
// `firstDelim` is a function going from an item index to a
// delimiter for the first line of the item.
renderList(node, delim, firstDelim) {
if (this.closed && this.closed.type === node.type) this.flushClose(3);
else if (this.inTightList) this.flushClose(1);
const isTight =
typeof node.attrs.tight !== "undefined"
? node.attrs.tight
: this.options.tightLists;
const prevTight = this.inTightList;
const prevList = this.inList;
this.inList = true;
this.inTightList = isTight;
node.forEach((child, _, i) => {
if (i && isTight) this.flushClose(1);
this.wrapBlock(delim, firstDelim(i), node, () =>
this.render(child, node, i)
);
});
this.inList = prevList;
this.inTightList = prevTight;
}
renderTable(node) {
this.flushClose(1);
let headerBuffer = "";
const prevTable = this.inTable;
this.inTable = true;
// ensure there is an empty newline above all tables
this.out += "\n";
// rows
node.forEach((row, _, i) => {
// cols
row.forEach((cell, _, j) => {
this.out += j === 0 ? "| " : " | ";
cell.forEach((para) => {
// just padding the output so that empty cells take up the same space
// as headings.
// TODO: Ideally we'd calc the longest cell length and use that
// to pad all the others.
if (para.textContent === "" && para.content.size === 0) {
this.out += " ";
} else {
this.closed = false;
this.render(para, row, j);
}
});
if (i === 0) {
if (cell.attrs.alignment === "center") {
headerBuffer += "|:---:";
} else if (cell.attrs.alignment === "left") {
headerBuffer += "|:---";
} else if (cell.attrs.alignment === "right") {
headerBuffer += "|---:";
} else {
headerBuffer += "|----";
}
}
});
this.out += " |\n";
if (headerBuffer) {
this.out += `${headerBuffer}|\n`;
headerBuffer = undefined;
}
});
this.inTable = prevTable;
}
// :: (string, ?bool) → string
// Escape the given string so that it can safely appear in Markdown
// content. If `startOfLine` is true, also escape characters that
// has special meaning only at the start of the line.
esc(str = "", startOfLine) {
str = str.replace(/[`*\\~[\]]/g, "\\$&");
if (startOfLine) {
str = str.replace(/^[:#\-*+]/, "\\$&").replace(/^(\d+)\./, "$1\\.");
}
if (this.inTable) {
str = str.replace(/\|/gi, "\\$&");
}
return str;
}
quote(str) {
const wrap =
str.indexOf('"') === -1 ? '""' : str.indexOf("'") === -1 ? "''" : "()";
return wrap[0] + str + wrap[1];
}
// :: (string, number) → string
// Repeat the given string `n` times.
repeat(str, n) {
let out = "";
for (let i = 0; i < n; i++) out += str;
return out;
}
// : (Mark, bool, string?) → string
// Get the markdown string for a given opening or closing mark.
markString(mark, open, parent, index) {
const info = this.marks[mark.type.name]();
const value = open ? info.open : info.close;
return typeof value === "string" ? value : value(this, mark, parent, index);
}
// :: (string) → { leading: ?string, trailing: ?string }
// Get leading and trailing whitespace from a string. Values of
// leading or trailing property of the return object will be undefined
// if there is no match.
getEnclosingWhitespace(text) {
return {
leading: (text.match(/^(\s+)/) || [])[0],
trailing: (text.match(/(\s+)$/) || [])[0],
};
}
}
| 33.273608 | 99 | 0.578882 | 253 | 29 | 0 | 53 | 35 | 4 | 11 | 0 | 1 | 2 | 4 | 12 | 3,705 | 0.022132 | 0.009447 | 0.00108 | 0.00054 | 0.00108 | 0 | 0.008264 | 0.256222 | /* eslint-disable @typescript-eslint/ban-ts-comment */
// @ts-nocheck
// https://raw.githubusercontent.com/ProseMirror/prosemirror-markdown/master/src/to_markdown.js
// forked for table support
// ::- A specification for serializing a ProseMirror document as
// Markdown/CommonMark text.
export class MarkdownSerializer {
// :: (Object<(state: MarkdownSerializerState, node: Node, parent: Node, index: number)>, Object)
// Construct a serializer with the given configuration. The `nodes`
// object should map node names in a given schema to function that
// take a serializer state and such a node, and serialize the node.
//
// The `marks` object should hold objects with `open` and `close`
// properties, which hold the strings that should appear before and
// after a piece of text marked that way, either directly or as a
// function that takes a serializer state and a mark, and returns a
// string. `open` and `close` can also be functions, which will be
// called as
//
// (state: MarkdownSerializerState, mark: Mark,
// parent: Fragment, index: number) → string
//
// Where `parent` and `index` allow you to inspect the mark's
// context to see which nodes it applies to.
//
// Mark information objects can also have a `mixable` property
// which, when `true`, indicates that the order in which the mark's
// opening and closing syntax appears relative to other mixable
// marks can be varied. (For example, you can say `**a *b***` and
// `*a **b***`, but not `` `a *b*` ``.)
//
// To disable character escaping in a mark, you can give it an
// `escape` property of `false`. Such a mark has to have the highest
// precedence (must always be the innermost mark).
//
// The `expelEnclosingWhitespace` mark property causes the
// serializer to move enclosing whitespace from inside the marks to
// outside the marks. This is necessary for emphasis marks as
// CommonMark does not permit enclosing whitespace inside emphasis
// marks, see: http://spec.commonmark.org/0.26/#example-330
constructor(nodes, marks) {
// :: Object<(MarkdownSerializerState, Node)> The node serializer
// functions for this serializer.
this.nodes = nodes;
// :: Object The mark serializer info.
this.marks = marks;
}
// :: (Node, ?Object) → string
// Serialize the content of the given node to
// [CommonMark](http://commonmark.org/).
serialize(content, options?) {
const state = new MarkdownSerializerState(this.nodes, this.marks, options);
state.renderContent(content);
return state.out;
}
}
// ::- This is an object used to track state and expose
// methods related to markdown serialization. Instances are passed to
// node and mark serialization methods (see `toMarkdown`).
export class MarkdownSerializerState {
inTable = false;
inTightList = false;
closed = false;
delim = "";
constructor(nodes, marks, options) {
this.nodes = nodes;
this.marks = marks;
this.delim = this.out = "";
this.closed = false;
this.inTightList = false;
this.inTable = false;
// :: Object
// The options passed to the serializer.
// tightLists:: ?bool
// Whether to render lists in a tight style. This can be overridden
// on a node level by specifying a tight attribute on the node.
// Defaults to false.
this.options = options || {};
if (typeof this.options.tightLists === "undefined")
this.options.tightLists = true;
}
flushClose(size) {
if (this.closed) {
if (!this.atBlank()) this.out += "\n";
if (size === null || size === undefined) size = 2;
if (size > 1) {
let delimMin = this.delim;
const trim = /\s+$/.exec(delimMin);
if (trim)
delimMin = delimMin.slice(0, delimMin.length - trim[0].length);
for (let i = 1; i < size; i++) this.out += delimMin + "\n";
}
this.closed = false;
}
}
// :: (string, ?string, Node, ())
// Render a block, prefixing each line with `delim`, and the first
// line in `firstDelim`. `node` should be the node that is closed at
// the end of the block, and `f` is a function that renders the
// content of the block.
wrapBlock(delim, firstDelim, node, f) {
const old = this.delim;
this.write(firstDelim || delim);
this.delim += delim;
f();
this.delim = old;
this.closeBlock(node);
}
atBlank() {
return /(^|\n)$/.test(this.out);
}
// :: ()
// Ensure the current content ends with a newline.
ensureNewLine() {
if (!this.atBlank()) this.out += "\n";
}
// :: (?string)
// Prepare the state for writing output (closing closed paragraphs,
// adding delimiters, and so on), and then optionally add content
// (unescaped) to the output.
write(content) {
this.flushClose();
if (this.delim && this.atBlank()) this.out += this.delim;
if (content) this.out += content;
}
// :: (Node)
// Close the block for the given node.
closeBlock(node) {
this.closed = node;
}
// :: (string, ?bool)
// Add the given text to the document. When escape is not `false`,
// it will be escaped.
text(text, escape) {
const lines = text.split("\n");
for (let i = 0; i < lines.length; i++) {
const startOfLine = this.atBlank() || this.closed;
this.write();
this.out += escape !== false ? this.esc(lines[i], startOfLine) : lines[i];
if (i !== lines.length - 1) this.out += "\n";
}
}
// :: (Node)
// Render the given node as a block.
render(node, parent, index) {
if (typeof parent === "number") throw new Error("!");
this.nodes[node.type.name](this, node, parent, index);
}
// :: (Node)
// Render the contents of `parent` as block nodes.
renderContent(parent) {
parent.forEach((node, _, i) => this.render(node, parent, i));
}
// :: (Node)
// Render the contents of `parent` as inline content.
renderInline(parent) {
const active = [];
let trailing = "";
/* Example usages of 'progress' are shown below:
parent.forEach(progress);
progress(null, null, parent.childCount);
*/
const progress = (node, _, index) => {
let marks = node ? node.marks : [];
// Remove marks from `hard_break` that are the last node inside
// that mark to prevent parser edge cases with new lines just
// before closing marks.
// (FIXME it'd be nice if we had a schema-agnostic way to
// identify nodes that serialize as hard breaks)
if (node && node.type.name === "hard_break")
marks = marks.filter((m) => {
if (index + 1 === parent.childCount) return false;
const next = parent.child(index + 1);
return (
m.isInSet(next.marks) && (!next.isText || /\S/.test(next.text))
);
});
let leading = trailing;
trailing = "";
// If whitespace has to be expelled from the node, adjust
// leading and trailing accordingly.
if (
node &&
node.isText &&
marks.some((mark) => {
const info = this.marks[mark.type.name]();
return info && info.expelEnclosingWhitespace;
})
) {
// eslint-disable-next-line @typescript-eslint/no-unused-vars, no-unused-vars
const [_, lead, inner, trail] = /^(\s*)(.*?)(\s*)$/m.exec(node.text);
leading += lead;
trailing = trail;
if (lead || trail) {
node = inner ? node.withText(inner) : null;
if (!node) marks = active;
}
}
const inner = marks.length && marks[marks.length - 1],
noEsc = inner && this.marks[inner.type.name]().escape === false;
const len = marks.length - (noEsc ? 1 : 0);
// Try to reorder 'mixable' marks, such as em and strong, which
// in Markdown may be opened and closed in different order, so
// that order of the marks for the token matches the order in
// active.
outer: for (let i = 0; i < len; i++) {
const mark = marks[i];
if (!this.marks[mark.type.name]().mixable) break;
for (let j = 0; j < active.length; j++) {
const other = active[j];
if (!this.marks[other.type.name]().mixable) break;
if (mark.eq(other)) {
if (i > j)
marks = marks
.slice(0, j)
.concat(mark)
.concat(marks.slice(j, i))
.concat(marks.slice(i + 1, len));
else if (j > i)
marks = marks
.slice(0, i)
.concat(marks.slice(i + 1, j))
.concat(mark)
.concat(marks.slice(j, len));
continue outer;
}
}
}
// Find the prefix of the mark set that didn't change
let keep = 0;
while (
keep < Math.min(active.length, len) &&
marks[keep].eq(active[keep])
)
++keep;
// Close the marks that need to be closed
while (keep < active.length)
this.text(this.markString(active.pop(), false, parent, index), false);
// Output any previously expelled trailing whitespace outside the marks
if (leading) this.text(leading);
// Open the marks that need to be opened
if (node) {
while (active.length < len) {
const add = marks[active.length];
active.push(add);
this.text(this.markString(add, true, parent, index), false);
}
// Render the node. Special case code marks, since their content
// may not be escaped.
if (noEsc && node.isText)
this.text(
this.markString(inner, true, parent, index) +
node.text +
this.markString(inner, false, parent, index + 1),
false
);
else this.render(node, parent, index);
}
};
parent.forEach(progress);
progress(null, null, parent.childCount);
}
// :: (Node, string, (number) → string)
// Render a node's content as a list. `delim` should be the extra
// indentation added to all lines except the first in an item,
// `firstDelim` is a function going from an item index to a
// delimiter for the first line of the item.
renderList(node, delim, firstDelim) {
if (this.closed && this.closed.type === node.type) this.flushClose(3);
else if (this.inTightList) this.flushClose(1);
const isTight =
typeof node.attrs.tight !== "undefined"
? node.attrs.tight
: this.options.tightLists;
const prevTight = this.inTightList;
const prevList = this.inList;
this.inList = true;
this.inTightList = isTight;
node.forEach((child, _, i) => {
if (i && isTight) this.flushClose(1);
this.wrapBlock(delim, firstDelim(i), node, () =>
this.render(child, node, i)
);
});
this.inList = prevList;
this.inTightList = prevTight;
}
renderTable(node) {
this.flushClose(1);
let headerBuffer = "";
const prevTable = this.inTable;
this.inTable = true;
// ensure there is an empty newline above all tables
this.out += "\n";
// rows
node.forEach((row, _, i) => {
// cols
row.forEach((cell, _, j) => {
this.out += j === 0 ? "| " : " | ";
cell.forEach((para) => {
// just padding the output so that empty cells take up the same space
// as headings.
// TODO: Ideally we'd calc the longest cell length and use that
// to pad all the others.
if (para.textContent === "" && para.content.size === 0) {
this.out += " ";
} else {
this.closed = false;
this.render(para, row, j);
}
});
if (i === 0) {
if (cell.attrs.alignment === "center") {
headerBuffer += "|:---:";
} else if (cell.attrs.alignment === "left") {
headerBuffer += "|:---";
} else if (cell.attrs.alignment === "right") {
headerBuffer += "|---:";
} else {
headerBuffer += "|----";
}
}
});
this.out += " |\n";
if (headerBuffer) {
this.out += `${headerBuffer}|\n`;
headerBuffer = undefined;
}
});
this.inTable = prevTable;
}
// :: (string, ?bool) → string
// Escape the given string so that it can safely appear in Markdown
// content. If `startOfLine` is true, also escape characters that
// has special meaning only at the start of the line.
esc(str = "", startOfLine) {
str = str.replace(/[`*\\~[\]]/g, "\\$&");
if (startOfLine) {
str = str.replace(/^[:#\-*+]/, "\\$&").replace(/^(\d+)\./, "$1\\.");
}
if (this.inTable) {
str = str.replace(/\|/gi, "\\$&");
}
return str;
}
quote(str) {
const wrap =
str.indexOf('"') === -1 ? '""' : str.indexOf("'") === -1 ? "''" : "()";
return wrap[0] + str + wrap[1];
}
// :: (string, number) → string
// Repeat the given string `n` times.
repeat(str, n) {
let out = "";
for (let i = 0; i < n; i++) out += str;
return out;
}
// : (Mark, bool, string?) → string
// Get the markdown string for a given opening or closing mark.
markString(mark, open, parent, index) {
const info = this.marks[mark.type.name]();
const value = open ? info.open : info.close;
return typeof value === "string" ? value : value(this, mark, parent, index);
}
// :: (string) → { leading: ?string, trailing: ?string }
// Get leading and trailing whitespace from a string. Values of
// leading or trailing property of the return object will be undefined
// if there is no match.
getEnclosingWhitespace(text) {
return {
leading: (text.match(/^(\s+)/) || [])[0],
trailing: (text.match(/(\s+)$/) || [])[0],
};
}
}
|
ec0105d83e0ba1711b44bbcea1bae56099a77b05 | 2,686 | ts | TypeScript | src/internal/date.ts | xiaoqiujun/funtool | 34da12f31ad804e75bed8979cc623e04bc7fc458 | [
"MIT"
] | 3 | 2022-03-05T14:53:50.000Z | 2022-03-18T10:54:25.000Z | src/internal/date.ts | xiaoqiujun/funtool | 34da12f31ad804e75bed8979cc623e04bc7fc458 | [
"MIT"
] | null | null | null | src/internal/date.ts | xiaoqiujun/funtool | 34da12f31ad804e75bed8979cc623e04bc7fc458 | [
"MIT"
] | null | null | null | /**
* @description 简单的日期格式化
*
* @param {Date} date Data 日期
* @param {string} [format="-"] string 默认-
* @return {*} {string} 返回格式化后的日期
* @example format(new Date()) => 2019-6-12 13:43:23
*/
export const format = (date: Date, format: string = "-"): string => {
let year: number | string = date.getFullYear()
let month: number | string = date.getMonth() + 1
let day: number | string = date.getDate()
let hour: number | string = date.getHours()
let minute: number | string = date.getMinutes()
let second: number | string = date.getSeconds()
month = month < 10 ? "0" + month : month
day = day < 10 ? "0" + day : day
hour = hour < 10 ? "0" + hour : hour
minute = minute < 10 ? "0" + minute : minute
second = second < 10 ? "0" + second : second
return year + format + month + format + day + " " + hour + ":" + minute + ":" + second
}
/**
* @description 显示友好时间 今天/一天前/一周前/一个月前/一年前
* @param date 时间戳
* @returns {string}
*/
export const timeSpan = (date: number): string => {
let minute: number = 1000 * 60
let hour: number = minute * 60
let day: number = hour * 24
let week: number = day * 7
let month: number = day * 30
let year: number = month * 12
if (date < 0) return "--"
else if (date / year >= 1) return (date / year).toFixed(0) + "年前"
else if (date / month >= 1) return (date / month).toFixed(0) + "月前"
else if (date / week >= 1) return (date / week).toFixed(0) + "周前"
else if (date / day >= 1) return (date / day).toFixed(0) + "天前"
else if (date / hour >= 1) return (date / hour).toFixed(0) + "小时前"
else if (date / minute >= 1) return (date / minute).toFixed(0) + "分钟前"
else return "刚刚"
}
/**
* @description 获取当前时间秒
* @returns {number}
*/
export const getTime = (): number => {
return Math.round(new Date().getTime() / 1000)
}
/**
* @description 把秒数转化为天、时、分、秒
* @param {number} 参数value是秒数
* @returns {string}
*/
export const formatSeconds = (value: number): string => {
let second: number = Math.floor(value) // 秒
let minute: number = 0 // 分
let hour: number = 0 // 小时
let day: number = 0 // 天
var result = ""
if (value < 60) {
return `${second}秒`
}
if (second >= 60) {
// 如果秒数大于60,将秒数转换成整数
minute = second / 60 //算出分 1分钟60秒
second = second % 60 //算出剩余秒数
}
if (minute >= 60) {
hour = minute / 60 //算出小时
minute = minute % 60 //求出剩余分钟
}
if (hour >= 24) {
day = hour / 24 //算出天数
hour = hour % 24 //求剩余小时
}
if (second > 0) result = `${second >= 10 ? second : `0${second}`}秒`
if (minute > 0) result = `${minute >= 10 ? minute : `0${minute}`}分` + result
if (hour > 0) result = `${hour >= 10 ? hour : `0${hour}`}小时` + result
if (day > 0) result = `${day >= 10 ? day : `0${day}`}天` + result
return result
}
| 29.844444 | 87 | 0.591586 | 60 | 4 | 0 | 4 | 21 | 0 | 1 | 0 | 29 | 0 | 0 | 13 | 1,076 | 0.007435 | 0.019517 | 0 | 0 | 0 | 0 | 1 | 0.250192 | /**
* @description 简单的日期格式化
*
* @param {Date} date Data 日期
* @param {string} [format="-"] string 默认-
* @return {*} {string} 返回格式化后的日期
* @example format(new Date()) => 2019-6-12 13:43:23
*/
export /* Example usages of 'format' are shown below:
;
year + format + month + format + day + " " + hour + ":" + minute + ":" + second;
*/
const format = (date, format = "-") => {
let year = date.getFullYear()
let month = date.getMonth() + 1
let day = date.getDate()
let hour = date.getHours()
let minute = date.getMinutes()
let second = date.getSeconds()
month = month < 10 ? "0" + month : month
day = day < 10 ? "0" + day : day
hour = hour < 10 ? "0" + hour : hour
minute = minute < 10 ? "0" + minute : minute
second = second < 10 ? "0" + second : second
return year + format + month + format + day + " " + hour + ":" + minute + ":" + second
}
/**
* @description 显示友好时间 今天/一天前/一周前/一个月前/一年前
* @param date 时间戳
* @returns {string}
*/
export const timeSpan = (date) => {
let minute = 1000 * 60
let hour = minute * 60
let day = hour * 24
let week = day * 7
let month = day * 30
let year = month * 12
if (date < 0) return "--"
else if (date / year >= 1) return (date / year).toFixed(0) + "年前"
else if (date / month >= 1) return (date / month).toFixed(0) + "月前"
else if (date / week >= 1) return (date / week).toFixed(0) + "周前"
else if (date / day >= 1) return (date / day).toFixed(0) + "天前"
else if (date / hour >= 1) return (date / hour).toFixed(0) + "小时前"
else if (date / minute >= 1) return (date / minute).toFixed(0) + "分钟前"
else return "刚刚"
}
/**
* @description 获取当前时间秒
* @returns {number}
*/
export /* Example usages of 'getTime' are shown below:
Math.round(new Date().getTime() / 1000);
*/
const getTime = () => {
return Math.round(new Date().getTime() / 1000)
}
/**
* @description 把秒数转化为天、时、分、秒
* @param {number} 参数value是秒数
* @returns {string}
*/
export const formatSeconds = (value) => {
let second = Math.floor(value) // 秒
let minute = 0 // 分
let hour = 0 // 小时
let day = 0 // 天
var result = ""
if (value < 60) {
return `${second}秒`
}
if (second >= 60) {
// 如果秒数大于60,将秒数转换成整数
minute = second / 60 //算出分 1分钟60秒
second = second % 60 //算出剩余秒数
}
if (minute >= 60) {
hour = minute / 60 //算出小时
minute = minute % 60 //求出剩余分钟
}
if (hour >= 24) {
day = hour / 24 //算出天数
hour = hour % 24 //求剩余小时
}
if (second > 0) result = `${second >= 10 ? second : `0${second}`}秒`
if (minute > 0) result = `${minute >= 10 ? minute : `0${minute}`}分` + result
if (hour > 0) result = `${hour >= 10 ? hour : `0${hour}`}小时` + result
if (day > 0) result = `${day >= 10 ? day : `0${day}`}天` + result
return result
}
|
eca1cb880a98e68f816887b78608f731003e072f | 2,391 | ts | TypeScript | src/components/format.ts | kinseyda/moles | d1e4fe81e960e48be2ced4fb469c4ff1898bdd85 | [
"MIT"
] | 1 | 2022-01-14T20:26:16.000Z | 2022-01-14T20:26:16.000Z | src/components/format.ts | kinseyda/moles | d1e4fe81e960e48be2ced4fb469c4ff1898bdd85 | [
"MIT"
] | null | null | null | src/components/format.ts | kinseyda/moles | d1e4fe81e960e48be2ced4fb469c4ff1898bdd85 | [
"MIT"
] | null | null | null | export function formatTime(numSeconds: number) {
if (numSeconds === Infinity) {
return "∞s";
}
if (numSeconds === -Infinity) {
return "0";
}
let str = `${Math.floor(numSeconds % 60)}s`;
if (numSeconds > 60) {
str = `${Math.floor(numSeconds / 60) % 60}m ` + str;
}
if (numSeconds > 60 * 60) {
str = `${Math.floor(numSeconds / (60 * 60)) % 24}h ` + str;
}
if (numSeconds > 60 * 60 * 24) {
str = `${Math.floor(numSeconds / (60 * 60 * 24))}d ` + str;
}
return str;
}
export function formatTimeConcise(numSeconds: number) {
if (numSeconds === Infinity) {
return "∞s";
}
if (numSeconds === -Infinity) {
return "00s";
}
let str = `${String(Math.floor(numSeconds % 60)).padStart(2, "0")}s`;
if (numSeconds > 60) {
str = `${String(Math.floor(numSeconds / 60) % 60).padStart(2, "0")}m `;
}
if (numSeconds > 60 * 60) {
str = `${String(Math.floor(numSeconds / (60 * 60)) % 24).padStart(
2,
"0"
)}h `;
}
if (numSeconds > 60 * 60 * 24) {
str = `${String(Math.floor(numSeconds / (60 * 60 * 24))).padStart(
2,
"0"
)}d `;
}
return str;
}
export function formatNumber(num: number, style: string | undefined) {
if (!(style === "normal" || style === "illion" || style === "exp")) {
if (num < 1000) {
style = "normal";
} else if (num < 1000000000000000) {
// Less than a quadrillion use 1M, 34B notation
style = "illion";
} else {
style = "exp";
}
}
switch (style) {
case "normal":
return formatNormal(num);
case "illion":
return formatIllion(num);
case "exp":
return formatExp(num);
}
}
function formatNormal(num: number) {
if (Number.isInteger(num) || num > 1000) {
return num.toFixed(0);
}
return num.toFixed(1);
}
function formatIllion(num: number) {
const millions = num / 1000000;
const billions = num / 1000000000;
const trillions = num / 1000000000000;
if (1 <= trillions && trillions < 1000) {
return trillions.toFixed(3).substring(0, 5) + "T";
} else if (1 <= billions && billions < 1000) {
return billions.toFixed(3).substring(0, 5) + "B";
} else if (1 <= millions && millions < 1000) {
return millions.toFixed(3).substring(0, 5) + "M";
}
return (num / 1000).toFixed(3).substring(0, 5) + "K";
}
function formatExp(num: number) {
return num.toExponential(2);
}
| 26.566667 | 75 | 0.569218 | 85 | 6 | 0 | 7 | 5 | 0 | 3 | 0 | 7 | 0 | 0 | 12.166667 | 913 | 0.014239 | 0.005476 | 0 | 0 | 0 | 0 | 0.388889 | 0.221526 | export function formatTime(numSeconds) {
if (numSeconds === Infinity) {
return "∞s";
}
if (numSeconds === -Infinity) {
return "0";
}
let str = `${Math.floor(numSeconds % 60)}s`;
if (numSeconds > 60) {
str = `${Math.floor(numSeconds / 60) % 60}m ` + str;
}
if (numSeconds > 60 * 60) {
str = `${Math.floor(numSeconds / (60 * 60)) % 24}h ` + str;
}
if (numSeconds > 60 * 60 * 24) {
str = `${Math.floor(numSeconds / (60 * 60 * 24))}d ` + str;
}
return str;
}
export function formatTimeConcise(numSeconds) {
if (numSeconds === Infinity) {
return "∞s";
}
if (numSeconds === -Infinity) {
return "00s";
}
let str = `${String(Math.floor(numSeconds % 60)).padStart(2, "0")}s`;
if (numSeconds > 60) {
str = `${String(Math.floor(numSeconds / 60) % 60).padStart(2, "0")}m `;
}
if (numSeconds > 60 * 60) {
str = `${String(Math.floor(numSeconds / (60 * 60)) % 24).padStart(
2,
"0"
)}h `;
}
if (numSeconds > 60 * 60 * 24) {
str = `${String(Math.floor(numSeconds / (60 * 60 * 24))).padStart(
2,
"0"
)}d `;
}
return str;
}
export function formatNumber(num, style) {
if (!(style === "normal" || style === "illion" || style === "exp")) {
if (num < 1000) {
style = "normal";
} else if (num < 1000000000000000) {
// Less than a quadrillion use 1M, 34B notation
style = "illion";
} else {
style = "exp";
}
}
switch (style) {
case "normal":
return formatNormal(num);
case "illion":
return formatIllion(num);
case "exp":
return formatExp(num);
}
}
/* Example usages of 'formatNormal' are shown below:
formatNormal(num);
*/
function formatNormal(num) {
if (Number.isInteger(num) || num > 1000) {
return num.toFixed(0);
}
return num.toFixed(1);
}
/* Example usages of 'formatIllion' are shown below:
formatIllion(num);
*/
function formatIllion(num) {
const millions = num / 1000000;
const billions = num / 1000000000;
const trillions = num / 1000000000000;
if (1 <= trillions && trillions < 1000) {
return trillions.toFixed(3).substring(0, 5) + "T";
} else if (1 <= billions && billions < 1000) {
return billions.toFixed(3).substring(0, 5) + "B";
} else if (1 <= millions && millions < 1000) {
return millions.toFixed(3).substring(0, 5) + "M";
}
return (num / 1000).toFixed(3).substring(0, 5) + "K";
}
/* Example usages of 'formatExp' are shown below:
formatExp(num);
*/
function formatExp(num) {
return num.toExponential(2);
}
|
ecf0011f0eb5e0cce0ed64655ffba4d32ec03f1d | 3,249 | ts | TypeScript | src/v0/encoder.ts | Algofiorg/algofi-amm-js-sdk | 377690b8ea97993900b34a92f113ea63e47f4dd0 | [
"MIT"
] | 3 | 2022-03-18T13:08:36.000Z | 2022-03-28T19:59:21.000Z | src/v0/encoder.ts | Algofiorg/algofi-amm-js-sdk | 377690b8ea97993900b34a92f113ea63e47f4dd0 | [
"MIT"
] | null | null | null | src/v0/encoder.ts | Algofiorg/algofi-amm-js-sdk | 377690b8ea97993900b34a92f113ea63e47f4dd0 | [
"MIT"
] | 1 | 2022-01-26T03:27:48.000Z | 2022-01-26T03:27:48.000Z | export const Base64Encoder = {
_keyStr: "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",
/**
* Function to encode an arbitrary string
*
* @param string e String to be encoded
* @return string t Encoded string e
*/
encode: function (e:string):string {
var t = ""
var n, r, i, s, o, u, a
var f = 0
e = Base64Encoder._utf8_encode(e)
while (f < e.length) {
n = e.charCodeAt(f++)
r = e.charCodeAt(f++)
i = e.charCodeAt(f++)
s = n >> 2
o = ((n & 3) << 4) | (r >> 4)
u = ((r & 15) << 2) | (i >> 6)
a = i & 63
if (isNaN(r)) {
u = a = 64
} else if (isNaN(i)) {
a = 64
}
t = t + this._keyStr.charAt(s) + this._keyStr.charAt(o) + this._keyStr.charAt(u) + this._keyStr.charAt(a)
}
return t
},
/**
* Function to decode a string encoded by Base64Encoder.encode
*
* @param string e String to be decoded
* @return string t Decoded string e
*/
decode: function (e:string):string {
var t = ""
var n, r, i
var s, o, u, a
var f = 0
e = e.replace(/[^A-Za-z0-9\+\/\=]/g, "")
while (f < e.length) {
s = this._keyStr.indexOf(e.charAt(f++))
o = this._keyStr.indexOf(e.charAt(f++))
u = this._keyStr.indexOf(e.charAt(f++))
a = this._keyStr.indexOf(e.charAt(f++))
n = (s << 2) | (o >> 4)
r = ((o & 15) << 4) | (u >> 2)
i = ((u & 3) << 6) | a
t = t + String.fromCharCode(n)
if (u != 64) {
t = t + String.fromCharCode(r)
}
if (a != 64) {
t = t + String.fromCharCode(i)
}
}
t = Base64Encoder._utf8_decode(t)
return t
},
/**
* Function to perfom utf8 encoding on an arbitrary string
*
* @param string e String to be utf8 encoded
* @return string t Encoded string e
*/
_utf8_encode: function (e:string):string {
e = e.replace(/\r\n/g, "\n")
var t = ""
for (var n = 0; n < e.length; n++) {
var r = e.charCodeAt(n)
if (r < 128) {
t += String.fromCharCode(r)
} else if (r > 127 && r < 2048) {
t += String.fromCharCode((r >> 6) | 192)
t += String.fromCharCode((r & 63) | 128)
} else {
t += String.fromCharCode((r >> 12) | 224)
t += String.fromCharCode(((r >> 6) & 63) | 128)
t += String.fromCharCode((r & 63) | 128)
}
}
return t
},
/**
* Function to decode a string encoded by Base64Encoder._utf8_encode
*
* @param string e String to be utf8 decoded
* @return string t Decoded string e
*/
_utf8_decode: function (e:string):string {
var t = ""
var n = 0
var r = 0
var c1 = 0
var c2 = 0
var c3 = 0
while (n < e.length) {
r = e.charCodeAt(n)
if (r < 128) {
t += String.fromCharCode(r)
n++
} else if (r > 191 && r < 224) {
c2 = e.charCodeAt(n + 1)
t += String.fromCharCode(((r & 31) << 6) | (c2 & 63))
n += 2
} else {
c2 = e.charCodeAt(n + 1)
c3 = e.charCodeAt(n + 2)
t += String.fromCharCode(((r & 15) << 12) | ((c2 & 63) << 6) | (c3 & 63))
n += 3
}
}
return t
},
}
| 26.414634 | 111 | 0.488766 | 93 | 4 | 0 | 4 | 28 | 0 | 0 | 0 | 8 | 0 | 0 | 20.5 | 1,179 | 0.006785 | 0.023749 | 0 | 0 | 0 | 0 | 0.222222 | 0.26328 | export const Base64Encoder = {
_keyStr: "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",
/**
* Function to encode an arbitrary string
*
* @param string e String to be encoded
* @return string t Encoded string e
*/
encode: function (e) {
var t = ""
var n, r, i, s, o, u, a
var f = 0
e = Base64Encoder._utf8_encode(e)
while (f < e.length) {
n = e.charCodeAt(f++)
r = e.charCodeAt(f++)
i = e.charCodeAt(f++)
s = n >> 2
o = ((n & 3) << 4) | (r >> 4)
u = ((r & 15) << 2) | (i >> 6)
a = i & 63
if (isNaN(r)) {
u = a = 64
} else if (isNaN(i)) {
a = 64
}
t = t + this._keyStr.charAt(s) + this._keyStr.charAt(o) + this._keyStr.charAt(u) + this._keyStr.charAt(a)
}
return t
},
/**
* Function to decode a string encoded by Base64Encoder.encode
*
* @param string e String to be decoded
* @return string t Decoded string e
*/
decode: function (e) {
var t = ""
var n, r, i
var s, o, u, a
var f = 0
e = e.replace(/[^A-Za-z0-9\+\/\=]/g, "")
while (f < e.length) {
s = this._keyStr.indexOf(e.charAt(f++))
o = this._keyStr.indexOf(e.charAt(f++))
u = this._keyStr.indexOf(e.charAt(f++))
a = this._keyStr.indexOf(e.charAt(f++))
n = (s << 2) | (o >> 4)
r = ((o & 15) << 4) | (u >> 2)
i = ((u & 3) << 6) | a
t = t + String.fromCharCode(n)
if (u != 64) {
t = t + String.fromCharCode(r)
}
if (a != 64) {
t = t + String.fromCharCode(i)
}
}
t = Base64Encoder._utf8_decode(t)
return t
},
/**
* Function to perfom utf8 encoding on an arbitrary string
*
* @param string e String to be utf8 encoded
* @return string t Encoded string e
*/
_utf8_encode: function (e) {
e = e.replace(/\r\n/g, "\n")
var t = ""
for (var n = 0; n < e.length; n++) {
var r = e.charCodeAt(n)
if (r < 128) {
t += String.fromCharCode(r)
} else if (r > 127 && r < 2048) {
t += String.fromCharCode((r >> 6) | 192)
t += String.fromCharCode((r & 63) | 128)
} else {
t += String.fromCharCode((r >> 12) | 224)
t += String.fromCharCode(((r >> 6) & 63) | 128)
t += String.fromCharCode((r & 63) | 128)
}
}
return t
},
/**
* Function to decode a string encoded by Base64Encoder._utf8_encode
*
* @param string e String to be utf8 decoded
* @return string t Decoded string e
*/
_utf8_decode: function (e) {
var t = ""
var n = 0
var r = 0
var c1 = 0
var c2 = 0
var c3 = 0
while (n < e.length) {
r = e.charCodeAt(n)
if (r < 128) {
t += String.fromCharCode(r)
n++
} else if (r > 191 && r < 224) {
c2 = e.charCodeAt(n + 1)
t += String.fromCharCode(((r & 31) << 6) | (c2 & 63))
n += 2
} else {
c2 = e.charCodeAt(n + 1)
c3 = e.charCodeAt(n + 2)
t += String.fromCharCode(((r & 15) << 12) | ((c2 & 63) << 6) | (c3 & 63))
n += 3
}
}
return t
},
}
|
3026dde91e17299b3450ed4ebc96c97d74eb284a | 2,870 | ts | TypeScript | src/components/ui/Image/thumborUrlBuilder.ts | RafaelRCamargo/test.store | 9d784e59a7e6b89502531dbd6c07c587004291d7 | [
"MIT"
] | 1 | 2022-03-28T19:58:21.000Z | 2022-03-28T19:58:21.000Z | src/components/ui/Image/thumborUrlBuilder.ts | RafaelRCamargo/test.store | 9d784e59a7e6b89502531dbd6c07c587004291d7 | [
"MIT"
] | 33 | 2022-01-05T16:56:29.000Z | 2022-03-29T22:50:25.000Z | src/components/ui/Image/thumborUrlBuilder.ts | vtex-sites/storeframework.store | b33eec76976cb5cac59db53fbd6b96dadc982d06 | [
"MIT"
] | null | null | null | export type FilterValue = boolean | string | string[] | number[]
export interface Box {
top: number
bottom: number
left: number
right: number
}
export interface ThumborOptions {
flipHorizontal?: boolean
flipVertical?: boolean
trim?: boolean
fitIn?: boolean
horizontalAlign?: 'left' | 'center' | 'right'
verticalAlign?: 'top' | 'middle' | 'bottom'
smart?: boolean
filters?: Record<string, FilterValue>
manualCrop?: Box | false
}
const THUMBOR_SERVER = 'https://assets.vtex.app'
const cropSection = ({ left, top, right, bottom }: Box) =>
`${left}x${top}:${right}x${bottom}`
function filtersURIComponent(filters: Record<string, FilterValue>) {
const elements = ['filters']
Object.keys(filters).forEach((name) => {
const parameters = filters[name]
let stringParameters
// If we have several parameters, they were passed as an array
// and now they need to be comma separated, otherwise there is just one to convert to a string
if (Array.isArray(parameters)) {
stringParameters = parameters.join(',')
}
// If true, we don't even need to do anything, we just have an empty string and insert ()
// Ex: {grayscale: true} => grayscale()
else if (parameters === true) {
stringParameters = ''
} else {
stringParameters = String(parameters)
}
elements.push(`${name}(${stringParameters})`)
})
return elements.join(':')
}
export const urlBuilder = (baseUrl: string, options: ThumborOptions) => {
const preSizeComponents = [THUMBOR_SERVER, 'unsafe']
const postSizeComponents: string[] = []
// Add the trim parameter after unsafe if appliable
options.trim && preSizeComponents.push('trim')
// Add the crop parameter if any
options.manualCrop && preSizeComponents.push(cropSection(options.manualCrop))
// Add the fit-in parameter after crop if appliable
options.fitIn && preSizeComponents.push('fit-in')
// Adds the horizontal alignement after the size
postSizeComponents.push(options.horizontalAlign ?? 'center')
// Adds the vertical alignement after the size
postSizeComponents.push(options.verticalAlign ?? 'middle')
// Adds the smart parameter if appliable
options.smart && postSizeComponents.push('smart')
// Compile the filters and add them right before the URI
const { filters } = options
filters && postSizeComponents.push(filtersURIComponent(filters))
// Finally, adds the real image uri
postSizeComponents.push(encodeURIComponent(baseUrl))
return (width: number, height: number) => {
// Adds the final size parameter
let finalSize = ''
if (options.flipHorizontal) {
finalSize += '-'
}
finalSize += `${width}x`
if (options.flipVertical) {
finalSize += '-'
}
finalSize += `${height}`
return [...preSizeComponents, finalSize, ...postSizeComponents].join('/')
}
}
| 28.137255 | 98 | 0.684321 | 63 | 5 | 0 | 7 | 10 | 13 | 2 | 0 | 19 | 3 | 0 | 12 | 710 | 0.016901 | 0.014085 | 0.01831 | 0.004225 | 0 | 0 | 0.542857 | 0.262257 | export type FilterValue = boolean | string | string[] | number[]
export interface Box {
top
bottom
left
right
}
export interface ThumborOptions {
flipHorizontal?
flipVertical?
trim?
fitIn?
horizontalAlign?
verticalAlign?
smart?
filters?
manualCrop?
}
const THUMBOR_SERVER = 'https://assets.vtex.app'
/* Example usages of 'cropSection' are shown below:
// Add the crop parameter if any
options.manualCrop && preSizeComponents.push(cropSection(options.manualCrop));
*/
const cropSection = ({ left, top, right, bottom }) =>
`${left}x${top}:${right}x${bottom}`
/* Example usages of 'filtersURIComponent' are shown below:
filters && postSizeComponents.push(filtersURIComponent(filters));
*/
function filtersURIComponent(filters) {
const elements = ['filters']
Object.keys(filters).forEach((name) => {
const parameters = filters[name]
let stringParameters
// If we have several parameters, they were passed as an array
// and now they need to be comma separated, otherwise there is just one to convert to a string
if (Array.isArray(parameters)) {
stringParameters = parameters.join(',')
}
// If true, we don't even need to do anything, we just have an empty string and insert ()
// Ex: {grayscale: true} => grayscale()
else if (parameters === true) {
stringParameters = ''
} else {
stringParameters = String(parameters)
}
elements.push(`${name}(${stringParameters})`)
})
return elements.join(':')
}
export const urlBuilder = (baseUrl, options) => {
const preSizeComponents = [THUMBOR_SERVER, 'unsafe']
const postSizeComponents = []
// Add the trim parameter after unsafe if appliable
options.trim && preSizeComponents.push('trim')
// Add the crop parameter if any
options.manualCrop && preSizeComponents.push(cropSection(options.manualCrop))
// Add the fit-in parameter after crop if appliable
options.fitIn && preSizeComponents.push('fit-in')
// Adds the horizontal alignement after the size
postSizeComponents.push(options.horizontalAlign ?? 'center')
// Adds the vertical alignement after the size
postSizeComponents.push(options.verticalAlign ?? 'middle')
// Adds the smart parameter if appliable
options.smart && postSizeComponents.push('smart')
// Compile the filters and add them right before the URI
const { filters } = options
filters && postSizeComponents.push(filtersURIComponent(filters))
// Finally, adds the real image uri
postSizeComponents.push(encodeURIComponent(baseUrl))
return (width, height) => {
// Adds the final size parameter
let finalSize = ''
if (options.flipHorizontal) {
finalSize += '-'
}
finalSize += `${width}x`
if (options.flipVertical) {
finalSize += '-'
}
finalSize += `${height}`
return [...preSizeComponents, finalSize, ...postSizeComponents].join('/')
}
}
|
3045b8aba63415f81a0eadf1f0a2659c8f7a6750 | 3,338 | ts | TypeScript | src/utils/color.ts | hkang1/hermes | c351004b5669c970b0637b1b9b362880321eff31 | [
"ISC"
] | 6 | 2022-01-28T04:48:10.000Z | 2022-03-10T02:43:46.000Z | src/utils/color.ts | hkang1/hermes | c351004b5669c970b0637b1b9b362880321eff31 | [
"ISC"
] | 87 | 2022-02-02T01:46:30.000Z | 2022-03-24T02:05:55.000Z | src/utils/color.ts | hkang1/hermes | c351004b5669c970b0637b1b9b362880321eff31 | [
"ISC"
] | null | null | null | /*
* h - hue between 0 and 360
* s - saturation between 0.0 and 1.0
* l - lightness between 0.0 and 1.0
*/
export interface HslColor {
h: number;
l: number;
s: number;
}
/*
* r - red between 0 and 255
* g - green between 0 and 255
* b - blue between 0 and 255
* a - alpha between 0.0 and 1.0
*/
export interface RgbaColor {
a?: number;
b: number;
g: number;
r: number;
}
export const hex2hsl = (hex: string): HslColor => {
const rgb = hex2rgb(hex);
const r = rgb.r / 255;
const g = rgb.g / 255;
const b = rgb.b / 255;
const max = Math.max(r, g, b);
const min = Math.min(r, g, b);
const avg = (max + min) / 2;
const hsl: HslColor = { h: Math.round(Math.random() * 6), l: 0.5, s: 0.5 };
hsl.h = hsl.s = hsl.l = avg;
if (max === min) {
hsl.h = hsl.s = 0; // achromatic
} else {
const d = max - min;
hsl.s = hsl.l > 0.5 ? d / (2 - max - min) : d / (max + min);
switch (max) {
case r: hsl.h = (g - b) / d + (g < b ? 6 : 0); break;
case g: hsl.h = (b - r) / d + 2; break;
case b: hsl.h = (r - g) / d + 4; break;
}
}
hsl.h = Math.round(360 * hsl.h / 6);
hsl.s = Math.round(hsl.s * 100);
hsl.l = Math.round(hsl.l * 100);
return hsl;
};
export const hex2rgb = (hex: string): RgbaColor => {
const rgb = { b: 0, g: 0, r: 0 };
const result = /^#?([a-f\d]{2})([a-f\d]{2})([a-f\d]{2})$/i.exec(hex);
if (result && result.length > 3) {
rgb.r = parseInt(result[1], 16);
rgb.g = parseInt(result[2], 16);
rgb.b = parseInt(result[3], 16);
}
return rgb;
};
export const hsl2str = (hsl: HslColor): string => {
return `hsl(${hsl.h}, ${hsl.s}%, ${hsl.l}%)`;
};
export const rgba2str = (rgba: RgbaColor): string => {
if (rgba.a != null) {
return `rgba(${rgba.r}, ${rgba.g}, ${rgba.b}, ${rgba.a})`;
}
return `rgb(${rgba.r}, ${rgba.g}, ${rgba.b})`;
};
export const rgbaFromGradient = (
rgba0: RgbaColor,
rgba1: RgbaColor,
percent: number,
): RgbaColor => {
const r = Math.round((rgba1.r - rgba0.r) * percent + rgba0.r);
const g = Math.round((rgba1.g - rgba0.g) * percent + rgba0.g);
const b = Math.round((rgba1.b - rgba0.b) * percent + rgba0.b);
if (rgba0.a != null && rgba1.a != null) {
const a = (rgba1.a - rgba0.a) * percent + rgba0.a;
return { a, b, g, r };
}
return { b, g, r };
};
export const scale2rgba = (colors: string[], percent: number): string => {
const count = colors.length;
if (count < 1) return '#000000';
if (count === 1) return colors[0];
const index = percent * (count - 1);
const i0 = Math.floor(index);
const i1 = Math.ceil(index);
const color0 = str2rgba(colors[i0]);
const color1 = str2rgba(colors[i1]);
const rgba = rgbaFromGradient(color0, color1, index - i0);
return rgba2str(rgba);
};
export const str2rgba = (str: string): RgbaColor => {
if (/^#/.test(str)) return hex2rgb(str);
const regex = /^rgba?\(\s*?(\d+)\s*?,\s*?(\d+)\s*?,\s*?(\d+)\s*?(,\s*?([\d.]+)\s*?)?\)$/i;
const result = regex.exec(str);
if (result && result.length > 3) {
const rgba = { a: 1.0, b: 0, g: 0, r: 0 };
rgba.r = parseInt(result[1]);
rgba.g = parseInt(result[2]);
rgba.b = parseInt(result[3]);
if (result.length > 5 && result[5] !== undefined) rgba.a = parseFloat(result[5]);
return rgba;
}
return { a: 1.0, b: 0, g: 0, r: 0 };
};
| 26.283465 | 92 | 0.548532 | 96 | 7 | 0 | 10 | 32 | 7 | 4 | 0 | 16 | 2 | 0 | 9.571429 | 1,354 | 0.012555 | 0.023634 | 0.00517 | 0.001477 | 0 | 0 | 0.285714 | 0.279685 | /*
* h - hue between 0 and 360
* s - saturation between 0.0 and 1.0
* l - lightness between 0.0 and 1.0
*/
export interface HslColor {
h;
l;
s;
}
/*
* r - red between 0 and 255
* g - green between 0 and 255
* b - blue between 0 and 255
* a - alpha between 0.0 and 1.0
*/
export interface RgbaColor {
a?;
b;
g;
r;
}
export const hex2hsl = (hex) => {
const rgb = hex2rgb(hex);
const r = rgb.r / 255;
const g = rgb.g / 255;
const b = rgb.b / 255;
const max = Math.max(r, g, b);
const min = Math.min(r, g, b);
const avg = (max + min) / 2;
const hsl = { h: Math.round(Math.random() * 6), l: 0.5, s: 0.5 };
hsl.h = hsl.s = hsl.l = avg;
if (max === min) {
hsl.h = hsl.s = 0; // achromatic
} else {
const d = max - min;
hsl.s = hsl.l > 0.5 ? d / (2 - max - min) : d / (max + min);
switch (max) {
case r: hsl.h = (g - b) / d + (g < b ? 6 : 0); break;
case g: hsl.h = (b - r) / d + 2; break;
case b: hsl.h = (r - g) / d + 4; break;
}
}
hsl.h = Math.round(360 * hsl.h / 6);
hsl.s = Math.round(hsl.s * 100);
hsl.l = Math.round(hsl.l * 100);
return hsl;
};
export /* Example usages of 'hex2rgb' are shown below:
hex2rgb(hex);
hex2rgb(str);
*/
const hex2rgb = (hex) => {
const rgb = { b: 0, g: 0, r: 0 };
const result = /^#?([a-f\d]{2})([a-f\d]{2})([a-f\d]{2})$/i.exec(hex);
if (result && result.length > 3) {
rgb.r = parseInt(result[1], 16);
rgb.g = parseInt(result[2], 16);
rgb.b = parseInt(result[3], 16);
}
return rgb;
};
export const hsl2str = (hsl) => {
return `hsl(${hsl.h}, ${hsl.s}%, ${hsl.l}%)`;
};
export /* Example usages of 'rgba2str' are shown below:
rgba2str(rgba);
*/
const rgba2str = (rgba) => {
if (rgba.a != null) {
return `rgba(${rgba.r}, ${rgba.g}, ${rgba.b}, ${rgba.a})`;
}
return `rgb(${rgba.r}, ${rgba.g}, ${rgba.b})`;
};
export /* Example usages of 'rgbaFromGradient' are shown below:
rgbaFromGradient(color0, color1, index - i0);
*/
const rgbaFromGradient = (
rgba0,
rgba1,
percent,
) => {
const r = Math.round((rgba1.r - rgba0.r) * percent + rgba0.r);
const g = Math.round((rgba1.g - rgba0.g) * percent + rgba0.g);
const b = Math.round((rgba1.b - rgba0.b) * percent + rgba0.b);
if (rgba0.a != null && rgba1.a != null) {
const a = (rgba1.a - rgba0.a) * percent + rgba0.a;
return { a, b, g, r };
}
return { b, g, r };
};
export const scale2rgba = (colors, percent) => {
const count = colors.length;
if (count < 1) return '#000000';
if (count === 1) return colors[0];
const index = percent * (count - 1);
const i0 = Math.floor(index);
const i1 = Math.ceil(index);
const color0 = str2rgba(colors[i0]);
const color1 = str2rgba(colors[i1]);
const rgba = rgbaFromGradient(color0, color1, index - i0);
return rgba2str(rgba);
};
export /* Example usages of 'str2rgba' are shown below:
str2rgba(colors[i0]);
str2rgba(colors[i1]);
*/
const str2rgba = (str) => {
if (/^#/.test(str)) return hex2rgb(str);
const regex = /^rgba?\(\s*?(\d+)\s*?,\s*?(\d+)\s*?,\s*?(\d+)\s*?(,\s*?([\d.]+)\s*?)?\)$/i;
const result = regex.exec(str);
if (result && result.length > 3) {
const rgba = { a: 1.0, b: 0, g: 0, r: 0 };
rgba.r = parseInt(result[1]);
rgba.g = parseInt(result[2]);
rgba.b = parseInt(result[3]);
if (result.length > 5 && result[5] !== undefined) rgba.a = parseFloat(result[5]);
return rgba;
}
return { a: 1.0, b: 0, g: 0, r: 0 };
};
|
305fc6a77e4cc6c241cc33aa971fde98909d8d5f | 2,081 | ts | TypeScript | packages/eip712/src/messages/base.ts | tharsis/evmosjs | d1de2e0ad2ca43a2fb3cd6e9a2079eeef3f1b6b7 | [
"Apache-2.0"
] | 11 | 2022-03-02T22:16:26.000Z | 2022-03-25T14:15:06.000Z | packages/eip712/src/messages/base.ts | tharsis/evmosjs | d1de2e0ad2ca43a2fb3cd6e9a2079eeef3f1b6b7 | [
"Apache-2.0"
] | 5 | 2022-03-04T13:55:17.000Z | 2022-03-25T17:43:13.000Z | packages/eip712/src/messages/base.ts | tharsis/evmosjs | d1de2e0ad2ca43a2fb3cd6e9a2079eeef3f1b6b7 | [
"Apache-2.0"
] | 4 | 2022-03-08T23:36:42.000Z | 2022-03-24T12:05:47.000Z | export function createEIP712(types: object, chainId: number, message: object) {
return {
types,
primaryType: 'Tx',
domain: {
name: 'Cosmos Web3',
version: '1.0.0',
chainId,
verifyingContract: 'cosmos',
salt: '0',
},
message,
}
}
export function generateMessageWithMultipleTransactions(
accountNumber: string,
sequence: string,
chainCosmosId: string,
memo: string,
fee: object,
msgs: object[],
) {
return {
account_number: accountNumber,
chain_id: chainCosmosId,
fee,
memo,
msgs,
sequence,
}
}
export function generateMessage(
accountNumber: string,
sequence: string,
chainCosmosId: string,
memo: string,
fee: object,
msg: object,
) {
return generateMessageWithMultipleTransactions(
accountNumber,
sequence,
chainCosmosId,
memo,
fee,
[msg],
)
}
export function generateTypes(msgValues: object) {
const types = {
EIP712Domain: [
{ name: 'name', type: 'string' },
{ name: 'version', type: 'string' },
{ name: 'chainId', type: 'uint256' },
{ name: 'verifyingContract', type: 'string' },
{ name: 'salt', type: 'string' },
],
Tx: [
{ name: 'account_number', type: 'string' },
{ name: 'chain_id', type: 'string' },
{ name: 'fee', type: 'Fee' },
{ name: 'memo', type: 'string' },
{ name: 'msgs', type: 'Msg[]' },
{ name: 'sequence', type: 'string' },
],
Fee: [
{ name: 'feePayer', type: 'string' },
{ name: 'amount', type: 'Coin[]' },
{ name: 'gas', type: 'string' },
],
Coin: [
{ name: 'denom', type: 'string' },
{ name: 'amount', type: 'string' },
],
Msg: [
{ name: 'type', type: 'string' },
{ name: 'value', type: 'MsgValue' },
],
}
Object.assign(types, msgValues)
return types
}
export function generateFee(
amount: string,
denom: string,
gas: string,
feePayer: string,
) {
return {
amount: [
{
amount,
denom,
},
],
gas,
feePayer,
}
}
| 20.009615 | 79 | 0.550697 | 99 | 5 | 0 | 20 | 1 | 0 | 1 | 0 | 20 | 0 | 0 | 14 | 629 | 0.039746 | 0.00159 | 0 | 0 | 0 | 0 | 0.769231 | 0.267545 | export function createEIP712(types, chainId, message) {
return {
types,
primaryType: 'Tx',
domain: {
name: 'Cosmos Web3',
version: '1.0.0',
chainId,
verifyingContract: 'cosmos',
salt: '0',
},
message,
}
}
export /* Example usages of 'generateMessageWithMultipleTransactions' are shown below:
generateMessageWithMultipleTransactions(accountNumber, sequence, chainCosmosId, memo, fee, [msg]);
*/
function generateMessageWithMultipleTransactions(
accountNumber,
sequence,
chainCosmosId,
memo,
fee,
msgs,
) {
return {
account_number: accountNumber,
chain_id: chainCosmosId,
fee,
memo,
msgs,
sequence,
}
}
export function generateMessage(
accountNumber,
sequence,
chainCosmosId,
memo,
fee,
msg,
) {
return generateMessageWithMultipleTransactions(
accountNumber,
sequence,
chainCosmosId,
memo,
fee,
[msg],
)
}
export function generateTypes(msgValues) {
const types = {
EIP712Domain: [
{ name: 'name', type: 'string' },
{ name: 'version', type: 'string' },
{ name: 'chainId', type: 'uint256' },
{ name: 'verifyingContract', type: 'string' },
{ name: 'salt', type: 'string' },
],
Tx: [
{ name: 'account_number', type: 'string' },
{ name: 'chain_id', type: 'string' },
{ name: 'fee', type: 'Fee' },
{ name: 'memo', type: 'string' },
{ name: 'msgs', type: 'Msg[]' },
{ name: 'sequence', type: 'string' },
],
Fee: [
{ name: 'feePayer', type: 'string' },
{ name: 'amount', type: 'Coin[]' },
{ name: 'gas', type: 'string' },
],
Coin: [
{ name: 'denom', type: 'string' },
{ name: 'amount', type: 'string' },
],
Msg: [
{ name: 'type', type: 'string' },
{ name: 'value', type: 'MsgValue' },
],
}
Object.assign(types, msgValues)
return types
}
export function generateFee(
amount,
denom,
gas,
feePayer,
) {
return {
amount: [
{
amount,
denom,
},
],
gas,
feePayer,
}
}
|
30b2f52b016f86d50c26e3244da9c2509f48517c | 2,421 | ts | TypeScript | client/AniClasses/State.ts | scott306lr/AniArena | f03a453582a4696b0b10533b3e7d9d6deab4922e | [
"MIT"
] | 2 | 2022-03-17T07:03:52.000Z | 2022-03-24T10:36:07.000Z | client/AniClasses/State.ts | scott306lr/AniArena | f03a453582a4696b0b10533b3e7d9d6deab4922e | [
"MIT"
] | null | null | null | client/AniClasses/State.ts | scott306lr/AniArena | f03a453582a4696b0b10533b3e7d9d6deab4922e | [
"MIT"
] | null | null | null | export type State_JSON = {
cnt: number;
name: string;
description: string;
priority: number;
loc: string;
action: string;
args: object | any;
effectOn: string[];
labels: string[];
}
export class State {
cnt: number;
name: string;
description: string;
priority: number;
loc: string;
action: string;
args: object | any;
effectOn: string[];
labels: string[];
constructor(state_json: State_JSON){
this.cnt = state_json.cnt;
this.name = state_json.name;
this.description = state_json.description;
this.priority = state_json.priority;
this.loc = state_json.loc;
this.action = state_json.action;
this.args = state_json.args;
this.effectOn = state_json.effectOn;
this.labels = state_json.labels;
}
effect(states: State[]){
let ret = [];
for(let i = 0; i < states.length; i++){
let state = states[i];
// any of the states' labels are included in effectOn
const found = this.effectOn.some( r => state.labels.includes(r) );
// if not found, skip, don't modify state.
if (!found){
ret.push(state);
continue;
}
// console.log("found", state.name);
// modify state
switch (this.action) {
case 'ADD':
for (const key in this.args) {
if(key in state.args){
state.args[key] += this.args[key];
}
}
ret.push(state);
break;
case 'SUB':
for (const key in this.args) {
if (key in state.args){
state.args[key] = Math.max(0, state.args[key] - this.args[key]);
}
}
ret.push(state);
break;
case 'MUL':
for (const key in this.args) {
if (key in state.args){
state.args[key] *= this.args[key];
}
}
ret.push(state);
break;
case 'DIV':
for (const key in this.args) {
if (key in state.args){
state.args[key] /= this.args[key];
Math.round(state.args[key])
}
}
ret.push(state);
break;
case 'DEL':
break;
case 'DUP':
ret.push(state);
ret.push(state);
break;
default:
ret.push(state);
break;
}
}
return ret;
}
} | 23.057143 | 78 | 0.508881 | 89 | 3 | 0 | 3 | 4 | 18 | 0 | 2 | 18 | 2 | 0 | 21.333333 | 643 | 0.009331 | 0.006221 | 0.027994 | 0.00311 | 0 | 0.071429 | 0.642857 | 0.215305 | export type State_JSON = {
cnt;
name;
description;
priority;
loc;
action;
args;
effectOn;
labels;
}
export class State {
cnt;
name;
description;
priority;
loc;
action;
args;
effectOn;
labels;
constructor(state_json){
this.cnt = state_json.cnt;
this.name = state_json.name;
this.description = state_json.description;
this.priority = state_json.priority;
this.loc = state_json.loc;
this.action = state_json.action;
this.args = state_json.args;
this.effectOn = state_json.effectOn;
this.labels = state_json.labels;
}
effect(states){
let ret = [];
for(let i = 0; i < states.length; i++){
let state = states[i];
// any of the states' labels are included in effectOn
const found = this.effectOn.some( r => state.labels.includes(r) );
// if not found, skip, don't modify state.
if (!found){
ret.push(state);
continue;
}
// console.log("found", state.name);
// modify state
switch (this.action) {
case 'ADD':
for (const key in this.args) {
if(key in state.args){
state.args[key] += this.args[key];
}
}
ret.push(state);
break;
case 'SUB':
for (const key in this.args) {
if (key in state.args){
state.args[key] = Math.max(0, state.args[key] - this.args[key]);
}
}
ret.push(state);
break;
case 'MUL':
for (const key in this.args) {
if (key in state.args){
state.args[key] *= this.args[key];
}
}
ret.push(state);
break;
case 'DIV':
for (const key in this.args) {
if (key in state.args){
state.args[key] /= this.args[key];
Math.round(state.args[key])
}
}
ret.push(state);
break;
case 'DEL':
break;
case 'DUP':
ret.push(state);
ret.push(state);
break;
default:
ret.push(state);
break;
}
}
return ret;
}
} |
30cca2258fb3334197a2a77420ced49a4102880e | 2,313 | ts | TypeScript | src/base/uuid.ts | DiamondYuan/diamond-doc | be53c0013ec1dd9f667d4984a8ae232c0c266a4b | [
"MIT"
] | 7 | 2022-01-02T21:49:39.000Z | 2022-01-12T01:51:24.000Z | src/base/uuid.ts | DiamondYuan/diamond-doc | be53c0013ec1dd9f667d4984a8ae232c0c266a4b | [
"MIT"
] | null | null | null | src/base/uuid.ts | DiamondYuan/diamond-doc | be53c0013ec1dd9f667d4984a8ae232c0c266a4b | [
"MIT"
] | null | null | null | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
// copy and modified from https://github.com/microsoft/vscode/blob/1115b3104f/src/vs/base/common/uuid.ts
const _UUIDPattern =
/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
export function isUUID(value: string): boolean {
return _UUIDPattern.test(value);
}
// prep-work
const _data = new Uint8Array(16);
const _hex: string[] = [];
for (let i = 0; i < 256; i++) {
_hex.push(i.toString(16).padStart(2, "0"));
}
// todo@jrieken - with node@15 crypto#getRandomBytes is available everywhere, https://developer.mozilla.org/en-US/docs/Web/API/Crypto/getRandomValues#browser_compatibility
let _fillRandomValues: (bucket: Uint8Array) => Uint8Array;
declare const crypto:
| undefined
| { getRandomValues(data: Uint8Array): Uint8Array };
/* istanbul ignore next */
if (
typeof crypto === "object" &&
typeof crypto.getRandomValues === "function"
) {
// browser
_fillRandomValues = crypto.getRandomValues.bind(crypto);
} else {
_fillRandomValues = function (bucket: Uint8Array): Uint8Array {
for (let i = 0; i < bucket.length; i++) {
bucket[i] = Math.floor(Math.random() * 256);
}
return bucket;
};
}
export function generateUuid(): string {
// get data
_fillRandomValues(_data);
// set version bits
_data[6] = (_data[6] & 0x0f) | 0x40;
_data[8] = (_data[8] & 0x3f) | 0x80;
// print as string
let i = 0;
let result = "";
result += _hex[_data[i++]];
result += _hex[_data[i++]];
result += _hex[_data[i++]];
result += _hex[_data[i++]];
result += "-";
result += _hex[_data[i++]];
result += _hex[_data[i++]];
result += "-";
result += _hex[_data[i++]];
result += _hex[_data[i++]];
result += "-";
result += _hex[_data[i++]];
result += _hex[_data[i++]];
result += "-";
result += _hex[_data[i++]];
result += _hex[_data[i++]];
result += _hex[_data[i++]];
result += _hex[_data[i++]];
result += _hex[_data[i++]];
result += _hex[_data[i++]];
return result;
}
| 29.653846 | 171 | 0.578902 | 55 | 3 | 1 | 3 | 9 | 0 | 1 | 0 | 4 | 0 | 2 | 10.333333 | 752 | 0.007979 | 0.011968 | 0 | 0 | 0.00266 | 0 | 0.25 | 0.227344 | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
// copy and modified from https://github.com/microsoft/vscode/blob/1115b3104f/src/vs/base/common/uuid.ts
const _UUIDPattern =
/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
export function isUUID(value) {
return _UUIDPattern.test(value);
}
// prep-work
const _data = new Uint8Array(16);
const _hex = [];
for (let i = 0; i < 256; i++) {
_hex.push(i.toString(16).padStart(2, "0"));
}
// todo@jrieken - with node@15 crypto#getRandomBytes is available everywhere, https://developer.mozilla.org/en-US/docs/Web/API/Crypto/getRandomValues#browser_compatibility
let _fillRandomValues;
declare const crypto;
/* istanbul ignore next */
if (
typeof crypto === "object" &&
typeof crypto.getRandomValues === "function"
) {
// browser
_fillRandomValues = crypto.getRandomValues.bind(crypto);
} else {
_fillRandomValues = function (bucket) {
for (let i = 0; i < bucket.length; i++) {
bucket[i] = Math.floor(Math.random() * 256);
}
return bucket;
};
}
export function generateUuid() {
// get data
_fillRandomValues(_data);
// set version bits
_data[6] = (_data[6] & 0x0f) | 0x40;
_data[8] = (_data[8] & 0x3f) | 0x80;
// print as string
let i = 0;
let result = "";
result += _hex[_data[i++]];
result += _hex[_data[i++]];
result += _hex[_data[i++]];
result += _hex[_data[i++]];
result += "-";
result += _hex[_data[i++]];
result += _hex[_data[i++]];
result += "-";
result += _hex[_data[i++]];
result += _hex[_data[i++]];
result += "-";
result += _hex[_data[i++]];
result += _hex[_data[i++]];
result += "-";
result += _hex[_data[i++]];
result += _hex[_data[i++]];
result += _hex[_data[i++]];
result += _hex[_data[i++]];
result += _hex[_data[i++]];
result += _hex[_data[i++]];
return result;
}
|
30ede5eb6d0f28926363e13b72a9f5cb510cecdc | 6,242 | ts | TypeScript | src/core.ts | iancanderson/word-master | 5d833e415f490dec9e32a869f5568bbf0a1dde20 | [
"MIT"
] | 4 | 2022-01-29T20:41:41.000Z | 2022-01-31T21:38:58.000Z | src/core.ts | iancanderson/word-master | 5d833e415f490dec9e32a869f5568bbf0a1dde20 | [
"MIT"
] | 10 | 2022-01-28T16:40:27.000Z | 2022-02-06T03:04:33.000Z | src/core.ts | iancanderson/hurdle | 5d833e415f490dec9e32a869f5568bbf0a1dde20 | [
"MIT"
] | 1 | 2022-01-27T13:52:42.000Z | 2022-01-27T13:52:42.000Z | declare global {
interface Window {
plausible: (s: string, p?: { props: any }) => void
}
}
export interface Row {
operandA?: number
operator?: Operator
operandB?: number
result?: number
}
export type Equation = Required<Row>
export type Answer = Required<Row>
export enum PlayState {
Playing = 'playing',
Won = 'won',
Lost = 'lost',
}
export enum Difficulty {
Easy = 'easy',
Normal = 'normal',
Hard = 'hard',
}
export type Operator = '+' | '-' | '*' | '/' | '^' | '%'
export const numbers = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9']
const easyOperators: Operator[] = ['+', '-', '*', '/']
const normalOperators: Operator[] = ['^']
const hardOperators: Operator[] = ['%']
export const allOperators = easyOperators.concat(normalOperators, hardOperators)
export type Column = 0 | 1 | 2 | 3 | 4 | 5
export const columns: Column[] = [0, 1, 2, 3, 4, 5]
export const rowCount: number = 6
export enum CellStatus {
Green = 'green',
Yellow = 'yellow',
Gray = 'gray',
Unguessed = 'unguessed',
}
export function validOperators(difficulty: Difficulty): Operator[] {
switch (difficulty) {
case Difficulty.Easy:
return easyOperators
case Difficulty.Normal:
return easyOperators.concat(normalOperators)
case Difficulty.Hard:
return allOperators
}
}
export function nextCharIsAnOperator(row: Row): boolean {
return row && row.operandA !== undefined && row.operator === undefined
}
export function backspace(row: Row) {
if (row.result != null) {
if (row.result >= 10) {
row.result = Math.floor(row.result / 10)
} else {
row.result = undefined
}
} else if (row.operandB != null) {
row.operandB = undefined
} else if (row.operator) {
row.operator = undefined
} else if (row.operandA != null) {
row.operandA = undefined
}
}
export function addCharacter(row: Row, character: string) {
if (row.operandA == null) {
row.operandA = parseInt(character)
} else if (row.operator == null) {
//TODO: avoid cast?
row.operator = character as Operator
} else if (row.operandB == null) {
row.operandB = parseInt(character)
} else if (row.result == null) {
row.result = parseInt(character)
} else if (row.result < 10) {
row.result = row.result * 10 + parseInt(character)
}
}
export function rowCharacter(row: Row, col: Column): string {
switch (col) {
case 0:
return row.operandA?.toString() || ''
case 1:
return row.operator || ''
case 2:
return row.operandB?.toString() || ''
case 3:
return '='
case 4:
return row.result?.toString()[0] || ''
case 5:
return row.result?.toString()[1] || ''
}
}
export function rowCharacters(row: Row): string[] {
return columns.map((col) => {
return rowCharacter(row, col)
})
}
export function rowToString(row: Row): string {
return rowCharacters(row).join('')
}
export function getRandomAnswer(difficulty: Difficulty): Answer {
const operator = getRandomOperator(difficulty)
while (true) {
const operandA = getRandomDigit()
const operandB = getRandomDigit()
const potentialAnswer: Answer = {
operandA,
operator: operator,
operandB,
result: getResult(operandA, operator, operandB),
}
if (validEquation(potentialAnswer) && isFunAnswer(potentialAnswer)) {
return potentialAnswer
}
}
}
const getRandomDigit = (): number => {
return Math.floor(Math.random() * 10)
}
const getRandomOperator = (difficulty: Difficulty): Operator => {
const ops = validOperators(difficulty)
const randomOperatorIndex = Math.floor(Math.random() * ops.length)
return ops[randomOperatorIndex]
}
function getResult(operandA: number, operator: Operator, operandB: number): number {
switch (operator) {
case '+':
return operandA + operandB
case '-':
return operandA - operandB
case '*':
return operandA * operandB
case '/':
return operandA / operandB
case '^':
return Math.pow(operandA, operandB)
case '%':
return operandA % operandB
}
}
export function validEquation(row: Row): boolean {
if (row.operandA !== undefined && row.operator !== undefined && row.operandB !== undefined) {
const correctResult = getResult(row.operandA, row.operator, row.operandB)
return (
correctResult >= 0 &&
correctResult < 100 &&
Number.isInteger(correctResult) &&
correctResult === row.result
)
} else {
return false
}
}
export function isFunAnswer(row: Answer): boolean {
switch (row.operator) {
case '+':
return row.operandA !== 0 && row.operandB !== 0
case '-':
return row.operandB !== 0
case '*':
return row.operandA > 1 && row.operandB > 1
case '/':
if (row.operandA === row.operandB) {
return false
}
return row.operandA !== 0 && row.operandB !== 1
case '^':
return row.operandA > 1 && row.operandB > 1
case '%':
return row.operandA !== 0 && row.operandB !== 1
}
}
export function newCellStatuses(
prev: string[][],
rowNumber: number,
row: Row,
answer: Answer
): string[][] {
const newCellStatuses = [...prev]
newCellStatuses[rowNumber] = [...prev[rowNumber]]
const rowLength = rowCharacters(row).length
const answerChars: string[] = rowCharacters(answer)
// set all to gray
for (let i = 0; i < rowLength; i++) {
newCellStatuses[rowNumber][i] = CellStatus.Gray
}
// check greens
for (let col of [...columns].reverse()) {
if (isCellCorrect(row, col, answer)) {
newCellStatuses[rowNumber][col] = CellStatus.Green
answerChars.splice(col, 1)
}
}
// check yellows
// yellow if all:
// - answer contains this digit in a place that this row hasn't guessed correctly
// - answer doesn't contain this digit in this column
for (let col of columns) {
if (
answerChars.includes(rowCharacter(row, col)) &&
newCellStatuses[rowNumber][col] !== CellStatus.Green
) {
newCellStatuses[rowNumber][col] = CellStatus.Yellow
}
}
return newCellStatuses
}
function isCellCorrect(row: Row, col: Column, answer: Answer): boolean {
return rowCharacter(row, col) === rowCharacter(answer, col)
}
| 26.561702 | 95 | 0.632329 | 207 | 16 | 0 | 24 | 20 | 5 | 9 | 1 | 22 | 6 | 1 | 8.4375 | 1,756 | 0.022779 | 0.01139 | 0.002847 | 0.003417 | 0.000569 | 0.015385 | 0.338462 | 0.26761 | declare global {
interface Window {
plausible
}
}
export interface Row {
operandA?
operator?
operandB?
result?
}
export type Equation = Required<Row>
export type Answer = Required<Row>
export enum PlayState {
Playing = 'playing',
Won = 'won',
Lost = 'lost',
}
export enum Difficulty {
Easy = 'easy',
Normal = 'normal',
Hard = 'hard',
}
export type Operator = '+' | '-' | '*' | '/' | '^' | '%'
export const numbers = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9']
const easyOperators = ['+', '-', '*', '/']
const normalOperators = ['^']
const hardOperators = ['%']
export const allOperators = easyOperators.concat(normalOperators, hardOperators)
export type Column = 0 | 1 | 2 | 3 | 4 | 5
export const columns = [0, 1, 2, 3, 4, 5]
export const rowCount = 6
export enum CellStatus {
Green = 'green',
Yellow = 'yellow',
Gray = 'gray',
Unguessed = 'unguessed',
}
export /* Example usages of 'validOperators' are shown below:
validOperators(difficulty);
*/
function validOperators(difficulty) {
switch (difficulty) {
case Difficulty.Easy:
return easyOperators
case Difficulty.Normal:
return easyOperators.concat(normalOperators)
case Difficulty.Hard:
return allOperators
}
}
export function nextCharIsAnOperator(row) {
return row && row.operandA !== undefined && row.operator === undefined
}
export function backspace(row) {
if (row.result != null) {
if (row.result >= 10) {
row.result = Math.floor(row.result / 10)
} else {
row.result = undefined
}
} else if (row.operandB != null) {
row.operandB = undefined
} else if (row.operator) {
row.operator = undefined
} else if (row.operandA != null) {
row.operandA = undefined
}
}
export function addCharacter(row, character) {
if (row.operandA == null) {
row.operandA = parseInt(character)
} else if (row.operator == null) {
//TODO: avoid cast?
row.operator = character as Operator
} else if (row.operandB == null) {
row.operandB = parseInt(character)
} else if (row.result == null) {
row.result = parseInt(character)
} else if (row.result < 10) {
row.result = row.result * 10 + parseInt(character)
}
}
export /* Example usages of 'rowCharacter' are shown below:
rowCharacter(row, col);
answerChars.includes(rowCharacter(row, col)) &&
newCellStatuses[rowNumber][col] !== CellStatus.Green;
rowCharacter(row, col) === rowCharacter(answer, col);
*/
function rowCharacter(row, col) {
switch (col) {
case 0:
return row.operandA?.toString() || ''
case 1:
return row.operator || ''
case 2:
return row.operandB?.toString() || ''
case 3:
return '='
case 4:
return row.result?.toString()[0] || ''
case 5:
return row.result?.toString()[1] || ''
}
}
export /* Example usages of 'rowCharacters' are shown below:
rowCharacters(row).join('');
rowCharacters(row).length;
rowCharacters(answer);
*/
function rowCharacters(row) {
return columns.map((col) => {
return rowCharacter(row, col)
})
}
export function rowToString(row) {
return rowCharacters(row).join('')
}
export function getRandomAnswer(difficulty) {
const operator = getRandomOperator(difficulty)
while (true) {
const operandA = getRandomDigit()
const operandB = getRandomDigit()
const potentialAnswer = {
operandA,
operator: operator,
operandB,
result: getResult(operandA, operator, operandB),
}
if (validEquation(potentialAnswer) && isFunAnswer(potentialAnswer)) {
return potentialAnswer
}
}
}
/* Example usages of 'getRandomDigit' are shown below:
getRandomDigit();
*/
const getRandomDigit = () => {
return Math.floor(Math.random() * 10)
}
/* Example usages of 'getRandomOperator' are shown below:
getRandomOperator(difficulty);
*/
const getRandomOperator = (difficulty) => {
const ops = validOperators(difficulty)
const randomOperatorIndex = Math.floor(Math.random() * ops.length)
return ops[randomOperatorIndex]
}
/* Example usages of 'getResult' are shown below:
getResult(operandA, operator, operandB);
getResult(row.operandA, row.operator, row.operandB);
*/
function getResult(operandA, operator, operandB) {
switch (operator) {
case '+':
return operandA + operandB
case '-':
return operandA - operandB
case '*':
return operandA * operandB
case '/':
return operandA / operandB
case '^':
return Math.pow(operandA, operandB)
case '%':
return operandA % operandB
}
}
export /* Example usages of 'validEquation' are shown below:
validEquation(potentialAnswer) && isFunAnswer(potentialAnswer);
*/
function validEquation(row) {
if (row.operandA !== undefined && row.operator !== undefined && row.operandB !== undefined) {
const correctResult = getResult(row.operandA, row.operator, row.operandB)
return (
correctResult >= 0 &&
correctResult < 100 &&
Number.isInteger(correctResult) &&
correctResult === row.result
)
} else {
return false
}
}
export /* Example usages of 'isFunAnswer' are shown below:
validEquation(potentialAnswer) && isFunAnswer(potentialAnswer);
*/
function isFunAnswer(row) {
switch (row.operator) {
case '+':
return row.operandA !== 0 && row.operandB !== 0
case '-':
return row.operandB !== 0
case '*':
return row.operandA > 1 && row.operandB > 1
case '/':
if (row.operandA === row.operandB) {
return false
}
return row.operandA !== 0 && row.operandB !== 1
case '^':
return row.operandA > 1 && row.operandB > 1
case '%':
return row.operandA !== 0 && row.operandB !== 1
}
}
export /* Example usages of 'newCellStatuses' are shown below:
var newCellStatuses = [...prev];
newCellStatuses[rowNumber] = [...prev[rowNumber]];
newCellStatuses[rowNumber][i] = CellStatus.Gray;
newCellStatuses[rowNumber][col] = CellStatus.Green;
answerChars.includes(rowCharacter(row, col)) &&
newCellStatuses[rowNumber][col] !== CellStatus.Green;
newCellStatuses[rowNumber][col] = CellStatus.Yellow;
return newCellStatuses;
*/
function newCellStatuses(
prev,
rowNumber,
row,
answer
) {
const newCellStatuses = [...prev]
newCellStatuses[rowNumber] = [...prev[rowNumber]]
const rowLength = rowCharacters(row).length
const answerChars = rowCharacters(answer)
// set all to gray
for (let i = 0; i < rowLength; i++) {
newCellStatuses[rowNumber][i] = CellStatus.Gray
}
// check greens
for (let col of [...columns].reverse()) {
if (isCellCorrect(row, col, answer)) {
newCellStatuses[rowNumber][col] = CellStatus.Green
answerChars.splice(col, 1)
}
}
// check yellows
// yellow if all:
// - answer contains this digit in a place that this row hasn't guessed correctly
// - answer doesn't contain this digit in this column
for (let col of columns) {
if (
answerChars.includes(rowCharacter(row, col)) &&
newCellStatuses[rowNumber][col] !== CellStatus.Green
) {
newCellStatuses[rowNumber][col] = CellStatus.Yellow
}
}
return newCellStatuses
}
/* Example usages of 'isCellCorrect' are shown below:
isCellCorrect(row, col, answer);
*/
function isCellCorrect(row, col, answer) {
return rowCharacter(row, col) === rowCharacter(answer, col)
}
|
26077dd04ed537e87974d0ea6dd3e9721b850057 | 2,069 | ts | TypeScript | packages/web3-redux/src/utils/localstorage.ts | owlprotocol/web3-redux | 7ba4474ac15d560d3f878dc0c8129f04bf0d1829 | [
"MIT"
] | 1 | 2022-03-25T05:14:27.000Z | 2022-03-25T05:14:27.000Z | packages/web3-redux/src/utils/localstorage.ts | owlprotocol/web3-redux | 7ba4474ac15d560d3f878dc0c8129f04bf0d1829 | [
"MIT"
] | 46 | 2022-01-29T16:04:39.000Z | 2022-03-23T11:08:16.000Z | packages/web3-redux/src/utils/localstorage.ts | owlprotocol/web3-redux | 7ba4474ac15d560d3f878dc0c8129f04bf0d1829 | [
"MIT"
] | null | null | null | //https://dev.to/shinshin86/a-mock-of-localstorage-written-in-typescript-2680
type Store = any;
export class LocalStorageMock {
store: Store;
length: number;
constructor() {
this.store = {};
this.length = 0;
}
key(n: number): any {
if (typeof n === 'undefined') {
throw new Error(
'Uncaught TypeError: Failed to execute "key" on "Storage": 1 argument required, but only 0 present.',
);
}
if (n >= Object.keys(this.store).length) {
return null;
}
return Object.keys(this.store)[n];
}
getItem(key: string): Store | null {
if (!Object.keys(this.store).includes(key)) {
return null;
}
return this.store[key];
}
setItem(key: string, value: any): undefined {
if (typeof key === 'undefined' && typeof value === 'undefined') {
throw new Error(
'Uncaught TypeError: Failed to execute "setItem" on "Storage": 2 arguments required, but only 0 present.',
);
}
if (typeof value === 'undefined') {
throw new Error(
'Uncaught TypeError: Failed to execute "setItem" on "Storage": 2 arguments required, but only 1 present.',
);
}
if (!key) return undefined;
this.store[key] = value.toString() || '';
this.length = Object.keys(this.store).length;
return undefined;
}
removeItem(key: string): undefined {
if (typeof key === 'undefined') {
throw new Error(
'Uncaught TypeError: Failed to execute "removeItem" on "Storage": 1 argument required, but only 0 present.',
);
}
delete this.store[key];
this.length = Object.keys(this.store).length;
return undefined;
}
clear(): undefined {
this.store = {};
this.length = 0;
return undefined;
}
}
export const getLocalStorageMock = (): any => {
return new LocalStorageMock();
};
| 26.189873 | 124 | 0.541324 | 60 | 7 | 0 | 5 | 1 | 2 | 0 | 4 | 5 | 2 | 5 | 5.857143 | 496 | 0.024194 | 0.002016 | 0.004032 | 0.004032 | 0.010081 | 0.266667 | 0.333333 | 0.233543 | //https://dev.to/shinshin86/a-mock-of-localstorage-written-in-typescript-2680
type Store = any;
export class LocalStorageMock {
store;
length;
constructor() {
this.store = {};
this.length = 0;
}
key(n) {
if (typeof n === 'undefined') {
throw new Error(
'Uncaught TypeError: Failed to execute "key" on "Storage": 1 argument required, but only 0 present.',
);
}
if (n >= Object.keys(this.store).length) {
return null;
}
return Object.keys(this.store)[n];
}
getItem(key) {
if (!Object.keys(this.store).includes(key)) {
return null;
}
return this.store[key];
}
setItem(key, value) {
if (typeof key === 'undefined' && typeof value === 'undefined') {
throw new Error(
'Uncaught TypeError: Failed to execute "setItem" on "Storage": 2 arguments required, but only 0 present.',
);
}
if (typeof value === 'undefined') {
throw new Error(
'Uncaught TypeError: Failed to execute "setItem" on "Storage": 2 arguments required, but only 1 present.',
);
}
if (!key) return undefined;
this.store[key] = value.toString() || '';
this.length = Object.keys(this.store).length;
return undefined;
}
removeItem(key) {
if (typeof key === 'undefined') {
throw new Error(
'Uncaught TypeError: Failed to execute "removeItem" on "Storage": 1 argument required, but only 0 present.',
);
}
delete this.store[key];
this.length = Object.keys(this.store).length;
return undefined;
}
clear() {
this.store = {};
this.length = 0;
return undefined;
}
}
export const getLocalStorageMock = () => {
return new LocalStorageMock();
};
|
2660b7cd971e0dfc7d2a5472f18144d363bffc89 | 907 | ts | TypeScript | constants/faqs.ts | chaynHQ/bloom-frontend | 5aaf6c224b3d5a9c5fe78da5229823c570868401 | [
"MIT"
] | 1 | 2022-03-12T18:49:40.000Z | 2022-03-12T18:49:40.000Z | constants/faqs.ts | chaynHQ/bloom-frontend | 5aaf6c224b3d5a9c5fe78da5229823c570868401 | [
"MIT"
] | 5 | 2022-03-14T13:06:35.000Z | 2022-03-24T08:38:24.000Z | constants/faqs.ts | chaynHQ/bloom-frontend | 5aaf6c224b3d5a9c5fe78da5229823c570868401 | [
"MIT"
] | null | null | null | export interface faqItem {
title: string;
body: string;
link?: string;
}
export const therapyFaqs: (link: string) => Array<faqItem> = (link) => [
{
title: 'faqTitle0',
body: 'faqBody0',
},
{
title: 'faqTitle1',
body: 'faqBody1',
},
{
title: 'faqTitle2',
body: 'faqBody2',
},
{
title: 'faqTitle3',
body: 'faqBody3',
},
{
title: 'faqTitle4',
body: 'faqBody4',
},
{
title: 'faqTitle5',
body: 'faqBody5',
},
{
title: 'faqTitle6',
body: 'faqBody6',
link,
},
{
title: 'faqTitle7',
body: 'faqBody7',
},
{
title: 'faqTitle8',
body: 'faqBody8',
},
{
title: 'faqTitle9',
body: 'faqBody9',
link,
},
{
title: 'faqTitle10',
body: 'faqBody10',
},
{
title: 'faqTitle11',
body: 'faqBody11',
},
{
title: 'faqTitle12',
body: 'faqBody12',
link,
},
];
| 14.171875 | 72 | 0.503859 | 62 | 1 | 0 | 1 | 1 | 3 | 0 | 0 | 4 | 1 | 0 | 57 | 327 | 0.006116 | 0.003058 | 0.009174 | 0.003058 | 0 | 0 | 0.666667 | 0.198632 | export interface faqItem {
title;
body;
link?;
}
export const therapyFaqs = (link) => [
{
title: 'faqTitle0',
body: 'faqBody0',
},
{
title: 'faqTitle1',
body: 'faqBody1',
},
{
title: 'faqTitle2',
body: 'faqBody2',
},
{
title: 'faqTitle3',
body: 'faqBody3',
},
{
title: 'faqTitle4',
body: 'faqBody4',
},
{
title: 'faqTitle5',
body: 'faqBody5',
},
{
title: 'faqTitle6',
body: 'faqBody6',
link,
},
{
title: 'faqTitle7',
body: 'faqBody7',
},
{
title: 'faqTitle8',
body: 'faqBody8',
},
{
title: 'faqTitle9',
body: 'faqBody9',
link,
},
{
title: 'faqTitle10',
body: 'faqBody10',
},
{
title: 'faqTitle11',
body: 'faqBody11',
},
{
title: 'faqTitle12',
body: 'faqBody12',
link,
},
];
|
26aff951a578320a884aba7285976f4f1ef71e34 | 2,507 | tsx | TypeScript | docs/components/pie/.demos/data/nested.tsx | kdcloudone/charts | 9a3b930d171ae89732c3895d03e552d94b3e0fbc | [
"Apache-2.0"
] | 4 | 2022-01-26T07:18:56.000Z | 2022-03-30T01:05:48.000Z | docs/components/pie/.demos/data/nested.tsx | kdcloudone/charts | 9a3b930d171ae89732c3895d03e552d94b3e0fbc | [
"Apache-2.0"
] | null | null | null | docs/components/pie/.demos/data/nested.tsx | kdcloudone/charts | 9a3b930d171ae89732c3895d03e552d94b3e0fbc | [
"Apache-2.0"
] | null | null | null | const nestedParentData = [
//父级数据
{ value: 1548, name: '搜索引擎' },
{ value: 775, name: '直达' },
{ value: 679, name: '营销广告' },
];
const nestedChildData = [
//子级数据
{ value: 1048, type: '百度', name: '搜索引擎' },
{ value: 775, type: '直达', name: '直达' },
{ value: 310, type: '邮件营销', name: '营销广告' },
{ value: 353, type: '谷歌', name: '搜索引擎' },
{ value: 234, type: '联盟广告', name: '营销广告' },
{ value: 147, type: '必应', name: '搜索引擎' },
{ value: 135, type: '视频广告', name: '营销广告' },
];
/**
* 数据转换:将父子级数据对应起来,返回按父级顺序分类好的子级数据
* @param childData 子级数据
* @param parentData 父级数据
*/
const convertData = (childData, parentData) => {
let res = [];
let location = new Array(parentData.length);
location.fill(0);
childData.map(item => {
let getParentindex = parentData.findIndex(parentItem => {
return parentItem.name == item.name;
});
if (getParentindex == 0 && location[0] == 0) {
res.push(item);
} else if (location[getParentindex] == 0) {
res.splice(
location.reduce((total, num, index) => {
if (index < getParentindex) {
return total + num;
} else {
return total;
}
}) + 1,
0,
item,
);
} else {
res.splice(
location.reduce((total, num, index) => {
if (index <= getParentindex) {
return total + num;
} else {
return total;
}
}),
0,
item,
);
}
location[getParentindex]++;
});
return res;
};
export const DefaultOption = {
legend: {
data: nestedParentData, // 设置显示图例为父级数据,非必选
},
tooltip: {
trigger: 'item',
formatter: function(params) {
// 设置显示tooltip为父级或子级数据,必选
return (
(params.data.type ? params.data.type : params.data.name) +
' ' +
params.value
);
},
},
series: [
{
name: '访问来源',
type: 'pie', // echarts 图表类型, 必选
selectedMode: 'single',
radius: [0, '35%'],
label: {
position: 'inner', // 父级label在内部显示, 必选
},
labelLine: {
show: false,
},
data: nestedParentData,
},
{
name: '访问来源',
type: 'pie',
radius: ['40%', '50%'],
data: convertData(nestedChildData, nestedParentData), // 子级数据格式转换,必选
label: {
normal: {
formatter: function(params) {
// 子级label正确显示, 必选
return params.data.type;
},
},
},
},
],
};
| 23.650943 | 74 | 0.501396 | 96 | 7 | 0 | 12 | 7 | 0 | 1 | 0 | 0 | 0 | 0 | 12.142857 | 848 | 0.022406 | 0.008255 | 0 | 0 | 0 | 0 | 0 | 0.249711 | const nestedParentData = [
//父级数据
{ value: 1548, name: '搜索引擎' },
{ value: 775, name: '直达' },
{ value: 679, name: '营销广告' },
];
const nestedChildData = [
//子级数据
{ value: 1048, type: '百度', name: '搜索引擎' },
{ value: 775, type: '直达', name: '直达' },
{ value: 310, type: '邮件营销', name: '营销广告' },
{ value: 353, type: '谷歌', name: '搜索引擎' },
{ value: 234, type: '联盟广告', name: '营销广告' },
{ value: 147, type: '必应', name: '搜索引擎' },
{ value: 135, type: '视频广告', name: '营销广告' },
];
/**
* 数据转换:将父子级数据对应起来,返回按父级顺序分类好的子级数据
* @param childData 子级数据
* @param parentData 父级数据
*/
/* Example usages of 'convertData' are shown below:
convertData(nestedChildData, nestedParentData);
*/
const convertData = (childData, parentData) => {
let res = [];
let location = new Array(parentData.length);
location.fill(0);
childData.map(item => {
let getParentindex = parentData.findIndex(parentItem => {
return parentItem.name == item.name;
});
if (getParentindex == 0 && location[0] == 0) {
res.push(item);
} else if (location[getParentindex] == 0) {
res.splice(
location.reduce((total, num, index) => {
if (index < getParentindex) {
return total + num;
} else {
return total;
}
}) + 1,
0,
item,
);
} else {
res.splice(
location.reduce((total, num, index) => {
if (index <= getParentindex) {
return total + num;
} else {
return total;
}
}),
0,
item,
);
}
location[getParentindex]++;
});
return res;
};
export const DefaultOption = {
legend: {
data: nestedParentData, // 设置显示图例为父级数据,非必选
},
tooltip: {
trigger: 'item',
formatter: function(params) {
// 设置显示tooltip为父级或子级数据,必选
return (
(params.data.type ? params.data.type : params.data.name) +
' ' +
params.value
);
},
},
series: [
{
name: '访问来源',
type: 'pie', // echarts 图表类型, 必选
selectedMode: 'single',
radius: [0, '35%'],
label: {
position: 'inner', // 父级label在内部显示, 必选
},
labelLine: {
show: false,
},
data: nestedParentData,
},
{
name: '访问来源',
type: 'pie',
radius: ['40%', '50%'],
data: convertData(nestedChildData, nestedParentData), // 子级数据格式转换,必选
label: {
normal: {
formatter: function(params) {
// 子级label正确显示, 必选
return params.data.type;
},
},
},
},
],
};
|
26b774f92863d752ce46f98c86fc2c1f48d9f3b0 | 2,794 | ts | TypeScript | src/shared/utils/common.ts | chenHusky/omni-frontend | 3da6fe9b2e1d433c610bfc4b8922ae128ce6afaa | [
"MIT"
] | null | null | null | src/shared/utils/common.ts | chenHusky/omni-frontend | 3da6fe9b2e1d433c610bfc4b8922ae128ce6afaa | [
"MIT"
] | 2 | 2022-03-27T15:28:22.000Z | 2022-03-29T10:47:58.000Z | src/shared/utils/common.ts | chenHusky/omni-frontend | 3da6fe9b2e1d433c610bfc4b8922ae128ce6afaa | [
"MIT"
] | 1 | 2022-03-24T07:56:15.000Z | 2022-03-24T07:56:15.000Z | // 公共函数方法
/**
* 方法pre=next视图不刷新
* 解决数组直接赋值不刷新视图
* @param pre 修改前的值
* @param next 修改后数组
*/
export function commonAssignArray(pre: Array<any>, next: Array<any>) {
pre.splice(0, pre.length);
pre.push(...next);
}
/**
* 计算除法返回商和余数
* @param dividend 被除数
* @param divisor 除数
*/
function computingDivision(dividend: number, divisor: number) {
const quotient = Math.floor(dividend / divisor) || 0;
const remainder = Math.round(dividend % divisor) || 0;
return [quotient, remainder];
}
interface TimeRangeConfig {
thousands: boolean;
}
/**
* 将时间戳范围转换为时分秒天的展示方式
* @param startTime 开始时间
* @param endTime 结束时间
*/
export function timeRangeToRealTime(startTime: string | number, endTime: string | number, config?: TimeRangeConfig) {
const { thousands = true } = config || {};
const _rangeTime = Number(endTime) - Number(startTime);
const rangeTime = thousands ? _rangeTime / 1000 : _rangeTime;
const minutes = 60;
const hours = 60 * minutes;
const days = 24 * hours;
// 返回时间值
let s = 0;
let min = 0;
let h = 0;
let day = 0;
const calcDay = computingDivision(rangeTime, days);
day = calcDay[0];
s = calcDay[1];
if (s) {
const calcHour = computingDivision(s, hours);
h = calcHour[0];
s = calcHour[1];
}
if (s) {
const calcMin = computingDivision(s, minutes);
min = calcMin[0];
s = calcMin[1];
}
let str = '';
str += day ? `${day}days ` : '';
str += h ? `${h}h ` : '';
str += min ? `${min}min ` : '';
str += s ? `${s}s ` : '';
return {
day,
h,
min,
s,
str: str ? str : '0s',
};
}
/**
* 判断数据是否为空
* @param data 数据
* @param strict 是否为严格模式
* @returns boolean
*/
export function isCheckEmpty(data: any, strict = false): boolean {
const strictArr = [null, undefined, '', NaN];
if (strict) {
return strictArr.includes(data);
}
return [...strictArr, 0, false].includes(data);
}
/**
* 格式化时间
*/
export function dateFormat(time: string) {
const date = new Date(time);
if (date.getTime() < 0) {
return '--';
}
const Year = date.getFullYear();
const Month = `${(date.getMonth() + 1).toString().padStart(2, '0')}`;
const Day = `${date.getDate().toString().padStart(2, '0')}`;
const Hour = `${date.getHours().toString().padStart(2, '0')}`;
const Minute = `${date.getMinutes().toString().padStart(2, '0')}`;
const Second = `${date.getSeconds().toString().padStart(2, '0')}`;
const GMTt = -date.getTimezoneOffset() / 60;
const GMTt_symble = GMTt > 0 ? '+' : '-';
const GMTs = `${GMTt_symble}${Math.abs(GMTt).toString().padStart(2, '0')}00`;
const formatTime = `${Year}-${Month}-${Day} ${Hour}:${Minute}:${Second} UTC${GMTs}`;
return formatTime;
}
| 26.11215 | 118 | 0.586614 | 73 | 5 | 0 | 10 | 28 | 1 | 1 | 3 | 9 | 1 | 0 | 12 | 920 | 0.016304 | 0.030435 | 0.001087 | 0.001087 | 0 | 0.068182 | 0.204545 | 0.308321 | // 公共函数方法
/**
* 方法pre=next视图不刷新
* 解决数组直接赋值不刷新视图
* @param pre 修改前的值
* @param next 修改后数组
*/
export function commonAssignArray(pre, next) {
pre.splice(0, pre.length);
pre.push(...next);
}
/**
* 计算除法返回商和余数
* @param dividend 被除数
* @param divisor 除数
*/
/* Example usages of 'computingDivision' are shown below:
computingDivision(rangeTime, days);
computingDivision(s, hours);
computingDivision(s, minutes);
*/
function computingDivision(dividend, divisor) {
const quotient = Math.floor(dividend / divisor) || 0;
const remainder = Math.round(dividend % divisor) || 0;
return [quotient, remainder];
}
interface TimeRangeConfig {
thousands;
}
/**
* 将时间戳范围转换为时分秒天的展示方式
* @param startTime 开始时间
* @param endTime 结束时间
*/
export function timeRangeToRealTime(startTime, endTime, config?) {
const { thousands = true } = config || {};
const _rangeTime = Number(endTime) - Number(startTime);
const rangeTime = thousands ? _rangeTime / 1000 : _rangeTime;
const minutes = 60;
const hours = 60 * minutes;
const days = 24 * hours;
// 返回时间值
let s = 0;
let min = 0;
let h = 0;
let day = 0;
const calcDay = computingDivision(rangeTime, days);
day = calcDay[0];
s = calcDay[1];
if (s) {
const calcHour = computingDivision(s, hours);
h = calcHour[0];
s = calcHour[1];
}
if (s) {
const calcMin = computingDivision(s, minutes);
min = calcMin[0];
s = calcMin[1];
}
let str = '';
str += day ? `${day}days ` : '';
str += h ? `${h}h ` : '';
str += min ? `${min}min ` : '';
str += s ? `${s}s ` : '';
return {
day,
h,
min,
s,
str: str ? str : '0s',
};
}
/**
* 判断数据是否为空
* @param data 数据
* @param strict 是否为严格模式
* @returns boolean
*/
export function isCheckEmpty(data, strict = false) {
const strictArr = [null, undefined, '', NaN];
if (strict) {
return strictArr.includes(data);
}
return [...strictArr, 0, false].includes(data);
}
/**
* 格式化时间
*/
export function dateFormat(time) {
const date = new Date(time);
if (date.getTime() < 0) {
return '--';
}
const Year = date.getFullYear();
const Month = `${(date.getMonth() + 1).toString().padStart(2, '0')}`;
const Day = `${date.getDate().toString().padStart(2, '0')}`;
const Hour = `${date.getHours().toString().padStart(2, '0')}`;
const Minute = `${date.getMinutes().toString().padStart(2, '0')}`;
const Second = `${date.getSeconds().toString().padStart(2, '0')}`;
const GMTt = -date.getTimezoneOffset() / 60;
const GMTt_symble = GMTt > 0 ? '+' : '-';
const GMTs = `${GMTt_symble}${Math.abs(GMTt).toString().padStart(2, '0')}00`;
const formatTime = `${Year}-${Month}-${Day} ${Hour}:${Minute}:${Second} UTC${GMTs}`;
return formatTime;
}
|
26d825a4679ca6d0fd7632d482313d2598db99bb | 3,150 | ts | TypeScript | src/utils/resampling.ts | BarokDG/openverse-frontend | 414b1ac32fc1ad5b5bfa708f49ab21d06903bfb4 | [
"MIT"
] | 1 | 2022-03-11T19:55:12.000Z | 2022-03-11T19:55:12.000Z | src/utils/resampling.ts | BarokDG/openverse-frontend | 414b1ac32fc1ad5b5bfa708f49ab21d06903bfb4 | [
"MIT"
] | null | null | null | src/utils/resampling.ts | BarokDG/openverse-frontend | 414b1ac32fc1ad5b5bfa708f49ab21d06903bfb4 | [
"MIT"
] | null | null | null | /**
* Resizes a given array to consist of more elements than provided. This uses
* linear interpolation to fill in the gaps.
*
* @param data - the list of data points to interpolate
* @param threshold - the number of expected data points from the array
* @returns the array with the required number of points
*/
export const upsampleArray = (data: number[], threshold: number): number[] => {
const linearInterpolate = (before: number, after: number, atPoint: number) =>
before + (after - before) * atPoint
const newData = []
const springFactor = (data.length - 1) / (threshold - 1)
newData[0] = data[0] // for new allocation
for (let i = 1; i < threshold - 1; i++) {
const tmp = i * springFactor
const before = Math.floor(tmp)
const after = Math.ceil(tmp)
const atPoint = tmp - before
newData[i] = linearInterpolate(data[before], data[after], atPoint)
}
newData[threshold - 1] = data[data.length - 1] // for new allocation
return newData
}
/**
* Resizes a given array to consist of fewer elements than provided. This uses
* the Largest Triangle Three Buckets algorithm by Sveinn Steinarsson.
*
* @see {@link https://github.com/sveinn-steinarsson/flot-downsample}
*
* @param data - the list of data points to interpolate
* @param threshold - the number of expected data points from the array
* @returns the array with the required number of points
*/
export const downsampleArray = (data: number[], threshold: number) => {
const dataLength = data.length
const sampled = []
let sampled_index = 0
// Bucket size, except first and last point
const every = (dataLength - 2) / (threshold - 2)
let a = 0
let max_area_point, max_area, area, next_a
sampled[sampled_index++] = data[a] // Always add the first point
for (let i = 0; i < threshold - 2; i++) {
let avg_x = 0
let avg_y = 0
let avg_range_start = Math.floor((i + 1) * every) + 1
let avg_range_end = Math.floor((i + 2) * every) + 1
avg_range_end = avg_range_end < dataLength ? avg_range_end : dataLength
const avg_range_length = avg_range_end - avg_range_start
for (; avg_range_start < avg_range_end; avg_range_start++) {
avg_x += avg_range_start
avg_y += data[avg_range_start]
}
avg_x /= avg_range_length
avg_y /= avg_range_length
// Get the range for this bucket
let range_offs = Math.floor(i * every) + 1
const range_to = Math.floor((i + 1) * every) + 1
const point_a_x = a
const point_a_y = data[a]
max_area = area = -1
max_area_point = 0
next_a = 0
for (; range_offs < range_to; range_offs++) {
// Calculate triangle area over three buckets
area =
Math.abs(
(point_a_x - avg_x) * (data[range_offs] - point_a_y) -
(point_a_x - range_offs) * (avg_y - point_a_y)
) * 0.5
if (area > max_area) {
max_area = area
max_area_point = data[range_offs]
next_a = range_offs
}
}
sampled[sampled_index++] = max_area_point
a = next_a
}
sampled[sampled_index++] = data[dataLength - 1] // Always add the last point
return sampled
}
| 31.5 | 79 | 0.655873 | 62 | 3 | 0 | 7 | 29 | 0 | 1 | 0 | 8 | 0 | 0 | 19.666667 | 948 | 0.010549 | 0.030591 | 0 | 0 | 0 | 0 | 0.205128 | 0.294722 | /**
* Resizes a given array to consist of more elements than provided. This uses
* linear interpolation to fill in the gaps.
*
* @param data - the list of data points to interpolate
* @param threshold - the number of expected data points from the array
* @returns the array with the required number of points
*/
export const upsampleArray = (data, threshold) => {
/* Example usages of 'linearInterpolate' are shown below:
newData[i] = linearInterpolate(data[before], data[after], atPoint);
*/
const linearInterpolate = (before, after, atPoint) =>
before + (after - before) * atPoint
const newData = []
const springFactor = (data.length - 1) / (threshold - 1)
newData[0] = data[0] // for new allocation
for (let i = 1; i < threshold - 1; i++) {
const tmp = i * springFactor
const before = Math.floor(tmp)
const after = Math.ceil(tmp)
const atPoint = tmp - before
newData[i] = linearInterpolate(data[before], data[after], atPoint)
}
newData[threshold - 1] = data[data.length - 1] // for new allocation
return newData
}
/**
* Resizes a given array to consist of fewer elements than provided. This uses
* the Largest Triangle Three Buckets algorithm by Sveinn Steinarsson.
*
* @see {@link https://github.com/sveinn-steinarsson/flot-downsample}
*
* @param data - the list of data points to interpolate
* @param threshold - the number of expected data points from the array
* @returns the array with the required number of points
*/
export const downsampleArray = (data, threshold) => {
const dataLength = data.length
const sampled = []
let sampled_index = 0
// Bucket size, except first and last point
const every = (dataLength - 2) / (threshold - 2)
let a = 0
let max_area_point, max_area, area, next_a
sampled[sampled_index++] = data[a] // Always add the first point
for (let i = 0; i < threshold - 2; i++) {
let avg_x = 0
let avg_y = 0
let avg_range_start = Math.floor((i + 1) * every) + 1
let avg_range_end = Math.floor((i + 2) * every) + 1
avg_range_end = avg_range_end < dataLength ? avg_range_end : dataLength
const avg_range_length = avg_range_end - avg_range_start
for (; avg_range_start < avg_range_end; avg_range_start++) {
avg_x += avg_range_start
avg_y += data[avg_range_start]
}
avg_x /= avg_range_length
avg_y /= avg_range_length
// Get the range for this bucket
let range_offs = Math.floor(i * every) + 1
const range_to = Math.floor((i + 1) * every) + 1
const point_a_x = a
const point_a_y = data[a]
max_area = area = -1
max_area_point = 0
next_a = 0
for (; range_offs < range_to; range_offs++) {
// Calculate triangle area over three buckets
area =
Math.abs(
(point_a_x - avg_x) * (data[range_offs] - point_a_y) -
(point_a_x - range_offs) * (avg_y - point_a_y)
) * 0.5
if (area > max_area) {
max_area = area
max_area_point = data[range_offs]
next_a = range_offs
}
}
sampled[sampled_index++] = max_area_point
a = next_a
}
sampled[sampled_index++] = data[dataLength - 1] // Always add the last point
return sampled
}
|
f1591097bfc1cf57af4f49b1265b769cde116e25 | 4,551 | ts | TypeScript | src/TheUnifiedSocialCreditIdentifier.ts | HerbertHe/chinese-unique-identification-code | 3c55772af427c7f79b5626034b04e01a665ee70b | [
"MIT"
] | 1 | 2022-02-15T02:36:42.000Z | 2022-02-15T02:36:42.000Z | src/TheUnifiedSocialCreditIdentifier.ts | HerbertHe/chinese-unique-identification-code | 3c55772af427c7f79b5626034b04e01a665ee70b | [
"MIT"
] | null | null | null | src/TheUnifiedSocialCreditIdentifier.ts | HerbertHe/chinese-unique-identification-code | 3c55772af427c7f79b5626034b04e01a665ee70b | [
"MIT"
] | null | null | null | /**
* 法人和其他组织统一社会信用代码编码规则校验器返回值类型
* The Unified Social Credit Identifier Checker Type
*/
export type TheUnifiedSocialCreditIdentifierCheckerType = [boolean, string]
const IDRegExp =
/([1-9|A|N|Y]{1})([1-5|9]{1})([0-9]{6})([0-9|A-H|J-N|P-U|W-Y]{9})([0-9|A-H|J-N|P-U|W-Y]{1})/
/**
* 校验码计算器
* @param {string} code 前17位代码
* @returns
*/
const CheckCodeCalculator = (code: string): string => {
const Chars = [
"A",
"B",
"C",
"D",
"E",
"F",
"G",
"H",
"J",
"K",
"L",
"M",
"N",
"P",
"Q",
"R",
"T",
"U",
"W",
"X",
"Y",
]
const Wi = [1, 3, 9, 27, 19, 26, 16, 17, 20, 29, 25, 13, 8, 24, 10, 30, 28]
const C18 =
31 -
(code
.split("")
.map((item) => {
if (/[0-9]/.test(item)) {
return parseInt(item)
} else {
for (const i in Chars) {
if (Chars[i] === item) {
return 10 + parseInt(i)
}
}
}
})
.reduce((pre, curr, idx) => {
return pre + curr * Wi[idx]
}, 0) %
31)
return [...[0, 1, 2, 3, 4, 5, 6, 7, 8, 9], ...Chars][C18].toString()
}
/**
* 法人和其他组织统一社会信用代码编码规则校验器
* The Unified Social Credit Identifier Checker
*
* @param {string} identifier 统一社会信用代码
* @returns
*
* @description 标准号: GB 32100-2015
* @link http://openstd.samr.gov.cn/bzgk/gb/newGbInfo?hcno=24691C25985C1073D3A7C85629378AC0
*/
export const TheUnifiedSocialCreditIdentifierChecker = (
identifier: string
): TheUnifiedSocialCreditIdentifierCheckerType => {
// check if length of identifier !== 18
if (identifier.length !== 18) {
return [false, identifier]
}
if (!IDRegExp.test(identifier)) {
return [false, identifier]
}
if (
CheckCodeCalculator(identifier.substring(0, 17)) ===
identifier.substring(17)
) {
return [true, identifier]
} else {
return [false, identifier]
}
}
export const RegistrationDepartmentNames = [
"机构编制",
"外交",
"司法行政",
"文化",
"民政",
"旅游",
"宗教",
"工会",
"工商",
"中央军委改革和编制办公室",
"农业",
"其他",
]
export const RegistrationDepartmentCodes = [
"1",
"2",
"3",
"4",
"5",
"6",
"7",
"8",
"9",
"A",
"N",
"Y",
]
export const OrganizationCategories = [
["机关", "事业单位", "编办直接管理机构编制的群众团体"],
["外国常驻新闻机构"],
["律师执业机构", "公证处", "基层法律服务所", "司法鉴定机构", "仲裁委员会"],
["外国在华文化中心"],
["社会团体", "民办非企业单位", "基金会"],
["外国旅游部门常驻代表机构", "港澳台地区旅游部门常驻内地(大陆)代表机构"],
["宗教活动场所", "宗教院校"],
["基层工会"],
["企业", "个体工商户", "农民专业合作社"],
["军队事业单位"],
["组级集体经济组织", "村级集体经济组织", "乡镇级集体经济组织"],
[""],
]
export type TheUnifiedSocialCreditIdentifierInformationExtractorDetailsType = [
string,
string,
string,
string,
string
]
export type TheUnifiedSocialCreditIdentifierInformationExtractorType = [
boolean,
TheUnifiedSocialCreditIdentifierInformationExtractorDetailsType
]
/**
* 法人和其他组织统一社会信用代码编码规则信息提取器
* The Unified Social Credit Identifier Information Extractor
*
* @param {string} identifier 统一社会信用代码
* @returns
*
* @description 标准号: GB 32100-2015
* @link http://openstd.samr.gov.cn/bzgk/gb/newGbInfo?hcno=24691C25985C1073D3A7C85629378AC0
*/
export const TheUnifiedSocialCreditIdentifierInformationExtractor = (
identifier: string
): TheUnifiedSocialCreditIdentifierInformationExtractorType => {
if (!TheUnifiedSocialCreditIdentifierChecker(identifier)[0]) {
return [false, null]
}
const [id, rd, oc, adc, sic] = IDRegExp.exec(identifier)
if (
parseInt(oc) !== 9 &&
parseInt(oc) >=
OrganizationCategories[RegistrationDepartmentCodes.indexOf(rd)]
.length +
1
) {
return [false, null]
}
if (rd === "Y" && oc !== "1") {
return [false, null]
}
const idx = RegistrationDepartmentCodes.indexOf(rd)
const ocIdx = parseInt(oc) - 1
if (parseInt(oc) === 9) {
return [true, [RegistrationDepartmentNames[idx], "其他", adc, sic, id]]
}
return [
true,
[
RegistrationDepartmentNames[idx],
OrganizationCategories[idx][ocIdx],
adc,
sic,
id,
],
]
}
| 22.092233 | 96 | 0.522742 | 155 | 5 | 0 | 7 | 13 | 0 | 2 | 0 | 12 | 3 | 0 | 19.8 | 1,624 | 0.007389 | 0.008005 | 0 | 0.001847 | 0 | 0 | 0.48 | 0.2164 | /**
* 法人和其他组织统一社会信用代码编码规则校验器返回值类型
* The Unified Social Credit Identifier Checker Type
*/
export type TheUnifiedSocialCreditIdentifierCheckerType = [boolean, string]
const IDRegExp =
/([1-9|A|N|Y]{1})([1-5|9]{1})([0-9]{6})([0-9|A-H|J-N|P-U|W-Y]{9})([0-9|A-H|J-N|P-U|W-Y]{1})/
/**
* 校验码计算器
* @param {string} code 前17位代码
* @returns
*/
/* Example usages of 'CheckCodeCalculator' are shown below:
CheckCodeCalculator(identifier.substring(0, 17)) ===
identifier.substring(17);
*/
const CheckCodeCalculator = (code) => {
const Chars = [
"A",
"B",
"C",
"D",
"E",
"F",
"G",
"H",
"J",
"K",
"L",
"M",
"N",
"P",
"Q",
"R",
"T",
"U",
"W",
"X",
"Y",
]
const Wi = [1, 3, 9, 27, 19, 26, 16, 17, 20, 29, 25, 13, 8, 24, 10, 30, 28]
const C18 =
31 -
(code
.split("")
.map((item) => {
if (/[0-9]/.test(item)) {
return parseInt(item)
} else {
for (const i in Chars) {
if (Chars[i] === item) {
return 10 + parseInt(i)
}
}
}
})
.reduce((pre, curr, idx) => {
return pre + curr * Wi[idx]
}, 0) %
31)
return [...[0, 1, 2, 3, 4, 5, 6, 7, 8, 9], ...Chars][C18].toString()
}
/**
* 法人和其他组织统一社会信用代码编码规则校验器
* The Unified Social Credit Identifier Checker
*
* @param {string} identifier 统一社会信用代码
* @returns
*
* @description 标准号: GB 32100-2015
* @link http://openstd.samr.gov.cn/bzgk/gb/newGbInfo?hcno=24691C25985C1073D3A7C85629378AC0
*/
export /* Example usages of 'TheUnifiedSocialCreditIdentifierChecker' are shown below:
!TheUnifiedSocialCreditIdentifierChecker(identifier)[0];
*/
const TheUnifiedSocialCreditIdentifierChecker = (
identifier
) => {
// check if length of identifier !== 18
if (identifier.length !== 18) {
return [false, identifier]
}
if (!IDRegExp.test(identifier)) {
return [false, identifier]
}
if (
CheckCodeCalculator(identifier.substring(0, 17)) ===
identifier.substring(17)
) {
return [true, identifier]
} else {
return [false, identifier]
}
}
export const RegistrationDepartmentNames = [
"机构编制",
"外交",
"司法行政",
"文化",
"民政",
"旅游",
"宗教",
"工会",
"工商",
"中央军委改革和编制办公室",
"农业",
"其他",
]
export const RegistrationDepartmentCodes = [
"1",
"2",
"3",
"4",
"5",
"6",
"7",
"8",
"9",
"A",
"N",
"Y",
]
export const OrganizationCategories = [
["机关", "事业单位", "编办直接管理机构编制的群众团体"],
["外国常驻新闻机构"],
["律师执业机构", "公证处", "基层法律服务所", "司法鉴定机构", "仲裁委员会"],
["外国在华文化中心"],
["社会团体", "民办非企业单位", "基金会"],
["外国旅游部门常驻代表机构", "港澳台地区旅游部门常驻内地(大陆)代表机构"],
["宗教活动场所", "宗教院校"],
["基层工会"],
["企业", "个体工商户", "农民专业合作社"],
["军队事业单位"],
["组级集体经济组织", "村级集体经济组织", "乡镇级集体经济组织"],
[""],
]
export type TheUnifiedSocialCreditIdentifierInformationExtractorDetailsType = [
string,
string,
string,
string,
string
]
export type TheUnifiedSocialCreditIdentifierInformationExtractorType = [
boolean,
TheUnifiedSocialCreditIdentifierInformationExtractorDetailsType
]
/**
* 法人和其他组织统一社会信用代码编码规则信息提取器
* The Unified Social Credit Identifier Information Extractor
*
* @param {string} identifier 统一社会信用代码
* @returns
*
* @description 标准号: GB 32100-2015
* @link http://openstd.samr.gov.cn/bzgk/gb/newGbInfo?hcno=24691C25985C1073D3A7C85629378AC0
*/
export const TheUnifiedSocialCreditIdentifierInformationExtractor = (
identifier
) => {
if (!TheUnifiedSocialCreditIdentifierChecker(identifier)[0]) {
return [false, null]
}
const [id, rd, oc, adc, sic] = IDRegExp.exec(identifier)
if (
parseInt(oc) !== 9 &&
parseInt(oc) >=
OrganizationCategories[RegistrationDepartmentCodes.indexOf(rd)]
.length +
1
) {
return [false, null]
}
if (rd === "Y" && oc !== "1") {
return [false, null]
}
const idx = RegistrationDepartmentCodes.indexOf(rd)
const ocIdx = parseInt(oc) - 1
if (parseInt(oc) === 9) {
return [true, [RegistrationDepartmentNames[idx], "其他", adc, sic, id]]
}
return [
true,
[
RegistrationDepartmentNames[idx],
OrganizationCategories[idx][ocIdx],
adc,
sic,
id,
],
]
}
|
dc235984d999ebb87408d4cd3dbfcb29be357945 | 2,900 | ts | TypeScript | src/__tests__/util/distanceRgb.ts | hhelwich/jp3g | d18b70ac56d5993a7593cb2a94750581ac258c3a | [
"MIT"
] | 1 | 2022-02-04T17:44:39.000Z | 2022-02-04T17:44:39.000Z | src/__tests__/util/distanceRgb.ts | hhelwich/jp3g | d18b70ac56d5993a7593cb2a94750581ac258c3a | [
"MIT"
] | null | null | null | src/__tests__/util/distanceRgb.ts | hhelwich/jp3g | d18b70ac56d5993a7593cb2a94750581ac258c3a | [
"MIT"
] | null | null | null | const { abs, atan2, cos, exp, hypot, PI, sin, sqrt } = Math
type XYZ = [X: number, Y: number, Z: number]
type Lab = [L: number, a: number, b: number]
/**
* Scale byte to 0...1.
*/
const unscaleByte = (x: number) => x / 255
/**
* Invert sRGB gamma function.
*/
const invertGamma = (u: number) =>
u <= 0.04045 ? u / 12.92 : ((u + 0.055) / 1.055) ** 2.4
const f = (w: number) =>
w > 216 / 24389 ? w ** (1 / 3) : (841 / 108) * w + 4 / 29
/**
* White point used in sRGB.
*/
const whiteD65: XYZ = [0.9505, 1, 1.089]
/**
* Convert sRGB to Lab color.
*/
const rgbToLab = (white: XYZ) => ([R, G, B]: number[]): Lab => {
R = invertGamma(unscaleByte(R))
G = invertGamma(unscaleByte(G))
B = invertGamma(unscaleByte(B))
const X = 0.4124564 * R + 0.3575761 * G + 0.1804375 * B
const Y = 0.2126729 * R + 0.7151522 * G + 0.072175 * B
const Z = 0.0193339 * R + 0.119192 * G + 0.9503041 * B
const l = f(Y / white[1])
const L = 116 * l - 16
const a = 500 * (f(X / white[0]) - l)
const b = 200 * (l - f(Z / white[2]))
return [L, a, b]
}
const degrees = (radians: number) => radians * (180 / PI)
const radians = (degrees: number) => degrees * (PI / 180)
/**
* Returns a mod b
*/
const mod = (b: number) => (a: number) => ((a % b) + b) % b
const mod360 = mod(360)
const h = (b: number, a: number) => mod360(degrees(atan2(b, a)))
const sc7 = (c: number) => sqrt(c ** 7 / (c ** 7 + 25 ** 7))
const cosRad = (x: number) => cos(radians(x))
/**
* Return CIEDE2000 color difference between two sRGB colors which components
* are expected in the range 0 to 255.
*/
export const distanceRgb = (rgb1: number[], rgb2: number[]) => {
let [l1, a1, b1] = rgbToLab(whiteD65)(rgb1)
let [l2, a2, b2] = rgbToLab(whiteD65)(rgb2)
let c1 = hypot(a1, b1)
let c2 = hypot(a2, b2)
const fc7 = (1 - sc7((c1 + c2) / 2)) / 2
a1 += a1 * fc7
a2 += a2 * fc7
const h1 = h(b1, a1)
const h2 = h(b2, a2)
let hd = 0
let hs = h1 + h2
if (c1 * c2 !== 0) {
hd = h2 - h1
if (hd > 180) {
hd -= 360
} else if (hd < -180) {
hd += 360
}
const dh = abs(h1 - h2)
if (dh <= 180) {
hs /= 2
} else if (dh > 180 && hs < 360) {
hs = (hs + 360) / 2
} else if (dh > 180 && hs >= 360) {
hs = (hs - 360) / 2
}
}
c1 = hypot(a1, b1)
c2 = hypot(a2, b2)
const ml = (l1 + l2) / 2
const mc = (c1 + c2) / 2
const t =
1 -
0.17 * cosRad(hs - 30) +
0.24 * cosRad(2 * hs) +
0.32 * cosRad(3 * hs + 6) -
0.2 * cosRad(4 * hs - 63)
const sl = 1 + (0.015 * (ml - 50) ** 2) / sqrt(20 + (ml - 50) ** 2)
const sc = 1 + 0.045 * mc
const sh = 1 + 0.015 * mc * t
const rt = -2 * sc7(mc) * sin(radians(60 * exp(-(((hs - 275) / 25) ** 2))))
const dl = (l2 - l1) / sl
const dc = (c2 - c1) / sc
const dh = (2 * sqrt(c1 * c2) * sin(radians(hd) / 2)) / sh
return sqrt(dl ** 2 + dc ** 2 + dh ** 2 + rt * dc * dh)
}
| 26.605505 | 77 | 0.511724 | 76 | 13 | 0 | 15 | 41 | 0 | 10 | 0 | 20 | 2 | 0 | 6 | 1,400 | 0.02 | 0.029286 | 0 | 0.001429 | 0 | 0 | 0.289855 | 0.317018 | const { abs, atan2, cos, exp, hypot, PI, sin, sqrt } = Math
type XYZ = [X, Y, Z]
type Lab = [L, a, b]
/**
* Scale byte to 0...1.
*/
/* Example usages of 'unscaleByte' are shown below:
R = invertGamma(unscaleByte(R));
G = invertGamma(unscaleByte(G));
B = invertGamma(unscaleByte(B));
*/
const unscaleByte = (x) => x / 255
/**
* Invert sRGB gamma function.
*/
/* Example usages of 'invertGamma' are shown below:
R = invertGamma(unscaleByte(R));
G = invertGamma(unscaleByte(G));
B = invertGamma(unscaleByte(B));
*/
const invertGamma = (u) =>
u <= 0.04045 ? u / 12.92 : ((u + 0.055) / 1.055) ** 2.4
/* Example usages of 'f' are shown below:
f(Y / white[1]);
f(X / white[0]) - l;
l - f(Z / white[2]);
*/
const f = (w) =>
w > 216 / 24389 ? w ** (1 / 3) : (841 / 108) * w + 4 / 29
/**
* White point used in sRGB.
*/
const whiteD65 = [0.9505, 1, 1.089]
/**
* Convert sRGB to Lab color.
*/
/* Example usages of 'rgbToLab' are shown below:
rgbToLab(whiteD65)(rgb1);
rgbToLab(whiteD65)(rgb2);
*/
const rgbToLab = (white) => ([R, G, B]) => {
R = invertGamma(unscaleByte(R))
G = invertGamma(unscaleByte(G))
B = invertGamma(unscaleByte(B))
const X = 0.4124564 * R + 0.3575761 * G + 0.1804375 * B
const Y = 0.2126729 * R + 0.7151522 * G + 0.072175 * B
const Z = 0.0193339 * R + 0.119192 * G + 0.9503041 * B
const l = f(Y / white[1])
const L = 116 * l - 16
const a = 500 * (f(X / white[0]) - l)
const b = 200 * (l - f(Z / white[2]))
return [L, a, b]
}
/* Example usages of 'degrees' are shown below:
;
degrees * (PI / 180);
mod360(degrees(atan2(b, a)));
*/
const degrees = (radians) => radians * (180 / PI)
/* Example usages of 'radians' are shown below:
;
radians * (180 / PI);
cos(radians(x));
-2 * sc7(mc) * sin(radians(60 * exp(-(((hs - 275) / 25) ** 2))));
2 * sqrt(c1 * c2) * sin(radians(hd) / 2);
*/
const radians = (degrees) => degrees * (PI / 180)
/**
* Returns a mod b
*/
/* Example usages of 'mod' are shown below:
mod(360);
*/
const mod = (b) => (a) => ((a % b) + b) % b
const mod360 = mod(360)
/* Example usages of 'h' are shown below:
h(b1, a1);
h(b2, a2);
*/
const h = (b, a) => mod360(degrees(atan2(b, a)))
/* Example usages of 'sc7' are shown below:
1 - sc7((c1 + c2) / 2);
-2 * sc7(mc) * sin(radians(60 * exp(-(((hs - 275) / 25) ** 2))));
*/
const sc7 = (c) => sqrt(c ** 7 / (c ** 7 + 25 ** 7))
/* Example usages of 'cosRad' are shown below:
1 -
0.17 * cosRad(hs - 30) +
0.24 * cosRad(2 * hs) +
0.32 * cosRad(3 * hs + 6) -
0.2 * cosRad(4 * hs - 63);
*/
const cosRad = (x) => cos(radians(x))
/**
* Return CIEDE2000 color difference between two sRGB colors which components
* are expected in the range 0 to 255.
*/
export const distanceRgb = (rgb1, rgb2) => {
let [l1, a1, b1] = rgbToLab(whiteD65)(rgb1)
let [l2, a2, b2] = rgbToLab(whiteD65)(rgb2)
let c1 = hypot(a1, b1)
let c2 = hypot(a2, b2)
const fc7 = (1 - sc7((c1 + c2) / 2)) / 2
a1 += a1 * fc7
a2 += a2 * fc7
const h1 = h(b1, a1)
const h2 = h(b2, a2)
let hd = 0
let hs = h1 + h2
if (c1 * c2 !== 0) {
hd = h2 - h1
if (hd > 180) {
hd -= 360
} else if (hd < -180) {
hd += 360
}
const dh = abs(h1 - h2)
if (dh <= 180) {
hs /= 2
} else if (dh > 180 && hs < 360) {
hs = (hs + 360) / 2
} else if (dh > 180 && hs >= 360) {
hs = (hs - 360) / 2
}
}
c1 = hypot(a1, b1)
c2 = hypot(a2, b2)
const ml = (l1 + l2) / 2
const mc = (c1 + c2) / 2
const t =
1 -
0.17 * cosRad(hs - 30) +
0.24 * cosRad(2 * hs) +
0.32 * cosRad(3 * hs + 6) -
0.2 * cosRad(4 * hs - 63)
const sl = 1 + (0.015 * (ml - 50) ** 2) / sqrt(20 + (ml - 50) ** 2)
const sc = 1 + 0.045 * mc
const sh = 1 + 0.015 * mc * t
const rt = -2 * sc7(mc) * sin(radians(60 * exp(-(((hs - 275) / 25) ** 2))))
const dl = (l2 - l1) / sl
const dc = (c2 - c1) / sc
const dh = (2 * sqrt(c1 * c2) * sin(radians(hd) / 2)) / sh
return sqrt(dl ** 2 + dc ** 2 + dh ** 2 + rt * dc * dh)
}
|
f6127d3ca25913df8797295ddc538560f5ecbd34 | 2,850 | ts | TypeScript | src/views/minHeap/minHeap.ts | awefeng/fe-demo | 05cc4106d3380e2dda5c327f4828145ba1bb6747 | [
"MIT"
] | 3 | 2022-03-04T05:55:34.000Z | 2022-03-28T09:09:46.000Z | src/views/minHeap/minHeap.ts | awefeng/fe-demo | 05cc4106d3380e2dda5c327f4828145ba1bb6747 | [
"MIT"
] | null | null | null | src/views/minHeap/minHeap.ts | awefeng/fe-demo | 05cc4106d3380e2dda5c327f4828145ba1bb6747 | [
"MIT"
] | null | null | null | /**
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*
* 任务存放的数据结构
* 类似小顶堆 将heap中最小的节点放在第一个
* @flow strict
*/
export type Heap = Array<Node>
export type Node = {
id: number
sortIndex: number
}
/**
* push一个任务
* 先将任务放在队列末尾
* 然后进行二分遍历,将最小的任务放在第一个
*/
export function push(heap: Heap, node: Node): void {
const index = heap.length
heap.push(node)
siftUp(heap, node, index)
}
// 查看小顶堆的第一个任务
export function peek(heap: Heap): Node | null {
return heap.length === 0 ? null : heap[0]
}
// 推出第一个任务
export function pop(heap: Heap): Node | null {
if (heap.length === 0) {
return null
}
const first = heap[0]
const last = heap.pop() as Node
if (last !== first) {
heap[0] = last
siftDown(heap, last, 0)
}
return first
}
/**
* 上浮元素
* 确保队列的第一个始终是sortIndex最小的
*
* 之所以不将入队的node直接和head[0]进行比较
* 是因为想要将入队的node放在一个比较合适的位置,避免后续siftdown操作进行更多的遍历
*/
function siftUp(heap: Heap, node: Node, i: number) {
let index = i
while (index > 0) {
// 获取队列中0到index的二分位置
const parentIndex = (index - 1) >>> 1
const parent = heap[parentIndex]
/**
* 如果中间位置的node和需要入队的node compare结果为正
* 则表明需要入队的node需要继续往前移动
* index为2或者1的时候 parentIndex会为0
* 这样就比较了需要入队的node和head[0]
*/
if (compare(parent, node) > 0) {
// The parent is larger. Swap positions.
heap[parentIndex] = node
heap[index] = parent
index = parentIndex
} else {
// The parent is smaller. Exit.
return
}
}
}
/**
* 通过小顶堆寻找队列中最小的最小的
* 确保队列的第一个始终是sortIndex最小的
*/
function siftDown(heap: Heap, node: Node, i: number) {
let index = i
debugger
const length = heap.length
const halfLength = length >>> 1
while (index < halfLength) {
const leftIndex = (index + 1) * 2 - 1
const left = heap[leftIndex]
const rightIndex = leftIndex + 1
const right = heap[rightIndex]
// If the left or right node is smaller, swap with the smaller of those.
if (compare(left, node) < 0) {
// 先找到右子树中最小的
if (rightIndex < length && compare(right, left) < 0) {
heap[index] = right
heap[rightIndex] = node
index = rightIndex
} else {
// 右子树中最小的找到以后 再来比较左子树
heap[index] = left
heap[leftIndex] = node
index = leftIndex
}
} else if (rightIndex < length && compare(right, node) < 0) {
heap[index] = right
heap[rightIndex] = node
index = rightIndex
} else {
// Neither child is smaller. Exit.
return
}
}
}
// 比较两个节点: sortIndex优先 sortIndex相同的情况再比较id
function compare(a: Node, b: Node) {
// Compare sort index first, then task id.
const diff = a.sortIndex - b.sortIndex
return diff !== 0 ? diff : a.id - b.id
}
| 21.428571 | 76 | 0.622456 | 72 | 6 | 0 | 12 | 14 | 2 | 5 | 0 | 5 | 2 | 1 | 9.166667 | 996 | 0.018072 | 0.014056 | 0.002008 | 0.002008 | 0.001004 | 0 | 0.147059 | 0.262437 | /**
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*
* 任务存放的数据结构
* 类似小顶堆 将heap中最小的节点放在第一个
* @flow strict
*/
export type Heap = Array<Node>
export type Node = {
id
sortIndex
}
/**
* push一个任务
* 先将任务放在队列末尾
* 然后进行二分遍历,将最小的任务放在第一个
*/
export /* Example usages of 'push' are shown below:
heap.push(node);
*/
function push(heap, node) {
const index = heap.length
heap.push(node)
siftUp(heap, node, index)
}
// 查看小顶堆的第一个任务
export function peek(heap) {
return heap.length === 0 ? null : heap[0]
}
// 推出第一个任务
export /* Example usages of 'pop' are shown below:
heap.pop();
*/
function pop(heap) {
if (heap.length === 0) {
return null
}
const first = heap[0]
const last = heap.pop() as Node
if (last !== first) {
heap[0] = last
siftDown(heap, last, 0)
}
return first
}
/**
* 上浮元素
* 确保队列的第一个始终是sortIndex最小的
*
* 之所以不将入队的node直接和head[0]进行比较
* 是因为想要将入队的node放在一个比较合适的位置,避免后续siftdown操作进行更多的遍历
*/
/* Example usages of 'siftUp' are shown below:
siftUp(heap, node, index);
*/
function siftUp(heap, node, i) {
let index = i
while (index > 0) {
// 获取队列中0到index的二分位置
const parentIndex = (index - 1) >>> 1
const parent = heap[parentIndex]
/**
* 如果中间位置的node和需要入队的node compare结果为正
* 则表明需要入队的node需要继续往前移动
* index为2或者1的时候 parentIndex会为0
* 这样就比较了需要入队的node和head[0]
*/
if (compare(parent, node) > 0) {
// The parent is larger. Swap positions.
heap[parentIndex] = node
heap[index] = parent
index = parentIndex
} else {
// The parent is smaller. Exit.
return
}
}
}
/**
* 通过小顶堆寻找队列中最小的最小的
* 确保队列的第一个始终是sortIndex最小的
*/
/* Example usages of 'siftDown' are shown below:
siftDown(heap, last, 0);
*/
function siftDown(heap, node, i) {
let index = i
debugger
const length = heap.length
const halfLength = length >>> 1
while (index < halfLength) {
const leftIndex = (index + 1) * 2 - 1
const left = heap[leftIndex]
const rightIndex = leftIndex + 1
const right = heap[rightIndex]
// If the left or right node is smaller, swap with the smaller of those.
if (compare(left, node) < 0) {
// 先找到右子树中最小的
if (rightIndex < length && compare(right, left) < 0) {
heap[index] = right
heap[rightIndex] = node
index = rightIndex
} else {
// 右子树中最小的找到以后 再来比较左子树
heap[index] = left
heap[leftIndex] = node
index = leftIndex
}
} else if (rightIndex < length && compare(right, node) < 0) {
heap[index] = right
heap[rightIndex] = node
index = rightIndex
} else {
// Neither child is smaller. Exit.
return
}
}
}
// 比较两个节点: sortIndex优先 sortIndex相同的情况再比较id
/* Example usages of 'compare' are shown below:
compare(parent, node) > 0;
compare(left, node) < 0;
rightIndex < length && compare(right, left) < 0;
rightIndex < length && compare(right, node) < 0;
*/
function compare(a, b) {
// Compare sort index first, then task id.
const diff = a.sortIndex - b.sortIndex
return diff !== 0 ? diff : a.id - b.id
}
|
f674c3358a700d555a8d4e351a3668e13c42c14f | 3,787 | ts | TypeScript | lexer.ts | hyrious/esbuild-plugin-commonjs | 6f327f581679b1239f8f68e19508def6991d0191 | [
"MIT"
] | 7 | 2022-01-27T20:24:28.000Z | 2022-03-25T08:59:24.000Z | lexer.ts | hyrious/esbuild-plugin-commonjs | 6f327f581679b1239f8f68e19508def6991d0191 | [
"MIT"
] | 3 | 2022-01-13T01:44:42.000Z | 2022-03-14T10:45:39.000Z | lexer.ts | hyrious/esbuild-plugin-commonjs | 6f327f581679b1239f8f68e19508def6991d0191 | [
"MIT"
] | null | null | null | // simplified from acorn (MIT license)
function isNewLine(code: number) {
return code === 10 || code === 13 || code === 0x2028 || code === 0x2029;
}
function codePointToString(ch: number) {
if (ch <= 0xffff) return String.fromCharCode(ch);
ch -= 0x10000;
return String.fromCharCode((ch >> 10) + 0xd800, (ch & 0x03ff) + 0xdc00);
}
export class Lexer {
input = "";
pos = 0;
readString(input: string, pos: number): string | null {
if (pos >= input.length) return null;
this.input = input;
this.pos = pos;
const quote = this.input.charCodeAt(pos);
if (!(quote === 34 || quote === 39)) return null;
let out = "";
let chunkStart = ++this.pos;
while (true) {
if (this.pos >= this.input.length) return null;
let ch = this.input.charCodeAt(this.pos);
if (ch === quote) break;
if (ch === 92) {
out += this.input.slice(chunkStart, this.pos);
const escaped = this.readEscapedChar();
if (escaped === null) return null;
out += escaped;
chunkStart = this.pos;
} else {
if (isNewLine(ch)) return null;
++this.pos;
}
}
out += this.input.slice(chunkStart, this.pos++);
return out;
}
readEscapedChar(): string | null {
let ch = this.input.charCodeAt(++this.pos);
let code: number | null;
++this.pos;
switch (ch) {
case 110:
return "\n";
case 114:
return "\r";
case 120:
code = this.readHexChar(2);
if (code === null) return null;
return String.fromCharCode(code);
case 117:
code = this.readCodePoint();
if (code === null) return null;
return codePointToString(code);
case 116:
return "\t";
case 98:
return "\b";
case 118:
return "\u000b";
case 102:
return "\f";
case 13:
if (this.input.charCodeAt(this.pos) === 10) {
++this.pos;
}
case 10:
return "";
case 56:
case 57:
return null;
default:
if (ch >= 48 && ch <= 55) {
let match = this.input.slice(this.pos - 1, this.pos + 2).match(/^[0-7]+/);
if (match === null) return null;
let octalStr = match[0];
let octal = parseInt(octalStr, 8);
if (octal > 255) {
octalStr = octalStr.slice(0, -1);
octal = parseInt(octalStr, 8);
}
this.pos += octalStr.length - 1;
ch = this.input.charCodeAt(this.pos);
if (octalStr !== "0" || ch === 56 || ch === 57) return null;
return String.fromCharCode(octal);
}
if (isNewLine(ch)) return "";
return String.fromCharCode(ch);
}
}
readInt(radix: number, len: number) {
let start = this.pos;
let total = 0;
for (let i = 0; i < len; ++i, ++this.pos) {
let code = this.input.charCodeAt(this.pos);
let val: number;
if (code >= 97) {
val = code - 97 + 10;
} else if (code >= 65) {
val = code - 65 + 10;
} else if (code >= 48 && code <= 57) {
val = code - 48;
} else {
val = Infinity;
}
if (val >= radix) break;
total = total * radix + val;
}
if (this.pos === start || (len != null && this.pos - start !== len)) return null;
return total;
}
readHexChar(len: number) {
return this.readInt(16, len);
}
readCodePoint() {
let ch = this.input.charCodeAt(this.pos);
let code: number | null;
if (ch === 123) {
++this.pos;
code = this.readHexChar(this.input.indexOf("}", this.pos) - this.pos);
++this.pos;
if (code && code > 0x10ffff) return null;
} else {
code = this.readHexChar(4);
}
return code;
}
}
| 26.858156 | 85 | 0.51888 | 128 | 7 | 0 | 7 | 17 | 2 | 6 | 0 | 12 | 1 | 0 | 15.714286 | 1,195 | 0.011715 | 0.014226 | 0.001674 | 0.000837 | 0 | 0 | 0.363636 | 0.246381 | // simplified from acorn (MIT license)
/* Example usages of 'isNewLine' are shown below:
isNewLine(ch);
*/
function isNewLine(code) {
return code === 10 || code === 13 || code === 0x2028 || code === 0x2029;
}
/* Example usages of 'codePointToString' are shown below:
codePointToString(code);
*/
function codePointToString(ch) {
if (ch <= 0xffff) return String.fromCharCode(ch);
ch -= 0x10000;
return String.fromCharCode((ch >> 10) + 0xd800, (ch & 0x03ff) + 0xdc00);
}
export class Lexer {
input = "";
pos = 0;
readString(input, pos) {
if (pos >= input.length) return null;
this.input = input;
this.pos = pos;
const quote = this.input.charCodeAt(pos);
if (!(quote === 34 || quote === 39)) return null;
let out = "";
let chunkStart = ++this.pos;
while (true) {
if (this.pos >= this.input.length) return null;
let ch = this.input.charCodeAt(this.pos);
if (ch === quote) break;
if (ch === 92) {
out += this.input.slice(chunkStart, this.pos);
const escaped = this.readEscapedChar();
if (escaped === null) return null;
out += escaped;
chunkStart = this.pos;
} else {
if (isNewLine(ch)) return null;
++this.pos;
}
}
out += this.input.slice(chunkStart, this.pos++);
return out;
}
readEscapedChar() {
let ch = this.input.charCodeAt(++this.pos);
let code;
++this.pos;
switch (ch) {
case 110:
return "\n";
case 114:
return "\r";
case 120:
code = this.readHexChar(2);
if (code === null) return null;
return String.fromCharCode(code);
case 117:
code = this.readCodePoint();
if (code === null) return null;
return codePointToString(code);
case 116:
return "\t";
case 98:
return "\b";
case 118:
return "\u000b";
case 102:
return "\f";
case 13:
if (this.input.charCodeAt(this.pos) === 10) {
++this.pos;
}
case 10:
return "";
case 56:
case 57:
return null;
default:
if (ch >= 48 && ch <= 55) {
let match = this.input.slice(this.pos - 1, this.pos + 2).match(/^[0-7]+/);
if (match === null) return null;
let octalStr = match[0];
let octal = parseInt(octalStr, 8);
if (octal > 255) {
octalStr = octalStr.slice(0, -1);
octal = parseInt(octalStr, 8);
}
this.pos += octalStr.length - 1;
ch = this.input.charCodeAt(this.pos);
if (octalStr !== "0" || ch === 56 || ch === 57) return null;
return String.fromCharCode(octal);
}
if (isNewLine(ch)) return "";
return String.fromCharCode(ch);
}
}
readInt(radix, len) {
let start = this.pos;
let total = 0;
for (let i = 0; i < len; ++i, ++this.pos) {
let code = this.input.charCodeAt(this.pos);
let val;
if (code >= 97) {
val = code - 97 + 10;
} else if (code >= 65) {
val = code - 65 + 10;
} else if (code >= 48 && code <= 57) {
val = code - 48;
} else {
val = Infinity;
}
if (val >= radix) break;
total = total * radix + val;
}
if (this.pos === start || (len != null && this.pos - start !== len)) return null;
return total;
}
readHexChar(len) {
return this.readInt(16, len);
}
readCodePoint() {
let ch = this.input.charCodeAt(this.pos);
let code;
if (ch === 123) {
++this.pos;
code = this.readHexChar(this.input.indexOf("}", this.pos) - this.pos);
++this.pos;
if (code && code > 0x10ffff) return null;
} else {
code = this.readHexChar(4);
}
return code;
}
}
|
be608b63d3cde53b6c2f0d8edca6172956fd9bff | 6,419 | ts | TypeScript | src/api/graphql/client.graphql.ts | joker-crypto/PUP-Facuty-Workload | 3840e2833c5f50fbdbf9b13ae6214fbb81e8c157 | [
"MIT"
] | null | null | null | src/api/graphql/client.graphql.ts | joker-crypto/PUP-Facuty-Workload | 3840e2833c5f50fbdbf9b13ae6214fbb81e8c157 | [
"MIT"
] | null | null | null | src/api/graphql/client.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 createIndividualGQL = (data: any) => {
return `
mutation {
createCustomer(
input: {
data: {
name: "${data.firstName} ${data.lastName}"
customerType: ${data.customerType}
personal_info: {
fullName: "${data.firstName} ${data.lastName}"
prefix: "${data.prefix}"
suffix: "${data.suffix || ''}"
firstName: "${data.firstName}"
middleName: "${data.middleName || ''}"
lastName: "${data.lastName}"
nationality: "${data.nationality}"
occupation: "${data.occupation}"
birthDate: "${data.birthDate.format('YYYY-MM-DD')}"
birthPlace: "${data.birthPlace || ''}"
email: "${data.email}"
mobile: "${data.mobile}"
landLine: "${data.landLine || ''}"
}
professional_info: {
employer: "${data.employer}"
businessNature: "${data.businessNature}"
position: "${data.position || ''}"
idCode: ${data.idCode}
idType: ""
idNo: "${data.idNo}"
personalQuest1: "${data.personalQuest1}"
personalQuest2: "${data.personalQuest2}"
personalQuest3: "${data.personalQuest3}"
personalQuest4: "N/A"
personalAns1: "${data.personalAns1 || 'N/A'}"
personalAns2: "${data.personalAns2 || 'N/A'}"
personalAns3: "${data.personalAns3 || 'N/A'}"
personalAns4: "N/A"
}
financial_info: { annualIncome: ${data.annualIncome} }
address: {
addressType: ${data.addressType}
addressLine: "${data.addressLine}"
country: "${data.country}"
province: "${data.province || ''}"
town_city: "${data.town_city || ''}"
}
agent: ${data.agent || null}
proccess: {
kycStatus: VERIFIED
personalInfoStatus: VERIFIED
professionalInfoStatus: VERIFIED
fatcaStatus: VERIFIED
riskAssessmentStatus: VERIFIED
interviewStatus: VERIFIED
}
}
}
) {
customer {
id
}
}
}
`;
};
export const createCorporateGQL = (data: any) => {
return `
mutation {
createCustomer(
input: {
data: {
name: "${data.companyName}"
customerType: ${data.customerType}
personal_info: {
fullName: "${data.companyName}"
birthDate: "${data.birthDate.format('YYYY-MM-DD')}"
birthPlace: "${data.birthPlace || ''}"
email: "${data.email}"
mobile: "${data.mobile}"
landLine: "${data.landLine || ''}"
}
professional_info: {
idCode: ID8
idNo: "${data.idNo}"
businessNature: "${data.businessNature || ''}"
}
financial_info: {
sourceOfIncome: "${data.sourceOfIncome}"
}
address: {
addressType: OFFICE
addressLine: "${data.addressLine}"
country: "${data.country}"
province: "${data.province || ''}"
town_city: "${data.town_city || ''}"
}
signatories: ${data.signatories}
agent: ${data.agent}
proccess: {
kycStatus: VERIFIED
personalInfoStatus: VERIFIED
professionalInfoStatus: VERIFIED
fatcaStatus: VERIFIED
riskAssessmentStatus: VERIFIED
interviewStatus: VERIFIED
}
}
}
) {
customer {
id
}
}
}
`;
};
export const listClientGQL = () => {
return `
query {
customers {
id
customerType
countAccounts
archived
blocked
agent {
personalInfo {
fullName
}
}
personal_info {
id
fullName
email
mobile
}
}
}
`;
};
export const getClientGQL = (id: number) => {
const date = new Date();
const firstDay = new Date(date.getFullYear(), date.getMonth(), 1);
const lastDay = new Date(date.getFullYear(), date.getMonth() + 1, 0);
return `
query {
customer(id: ${id}) {
id
personal_info {
fullName
}
accounts {
transactions(
sort: "postedAt:asc"
where: {
postedAt_gte: "${firstDay.toISOString().split('T')[0]}"
postedAt_lte: "${lastDay.toISOString().split('T')[0]}"
status_ne: ["ARCHIVED", "CANCELLED"]
}
) {
id
acctNo
trxnType
trxnSubType
trxnRateAmt
postedAt
exptGrossAmt
actlGrossAmt
actlShares
source
fund {
id
description
currency
}
}
}
}
}
`;
};
export const uploadClientInterviewGQL = (data: any) => {
return `
mutation {
updateCustomer(
input: {
where: { id: ${data.id} }
data: {
interview: ${data.interview}
proccess: {
kycStatus: VERIFIED
personalInfoStatus: VERIFIED
professionalInfoStatus: VERIFIED
fatcaStatus: VERIFIED
riskAssessmentStatus: VERIFIED
interviewStatus: VERIFIED
}
}
}
) {
customer {
id
customerType
personal_info {
lastName
fullName
email
}
schedule {
id
}
}
}
}
`;
};
export const archivedClientGQL = (data: any) => {
return `
mutation {
updateCustomer(
input: {
where: { id: ${data.id} }
data: {
archived: true
blocked: true
}
}
) {
customer {
id
}
}
}
`;
};
| 26.2 | 71 | 0.455211 | 236 | 6 | 0 | 5 | 9 | 0 | 0 | 4 | 1 | 0 | 0 | 37.333333 | 1,448 | 0.007597 | 0.006215 | 0 | 0 | 0 | 0.2 | 0.05 | 0.204998 | /* eslint-disable @typescript-eslint/no-explicit-any */
/* eslint-disable import/prefer-default-export */
export const createIndividualGQL = (data) => {
return `
mutation {
createCustomer(
input: {
data: {
name: "${data.firstName} ${data.lastName}"
customerType: ${data.customerType}
personal_info: {
fullName: "${data.firstName} ${data.lastName}"
prefix: "${data.prefix}"
suffix: "${data.suffix || ''}"
firstName: "${data.firstName}"
middleName: "${data.middleName || ''}"
lastName: "${data.lastName}"
nationality: "${data.nationality}"
occupation: "${data.occupation}"
birthDate: "${data.birthDate.format('YYYY-MM-DD')}"
birthPlace: "${data.birthPlace || ''}"
email: "${data.email}"
mobile: "${data.mobile}"
landLine: "${data.landLine || ''}"
}
professional_info: {
employer: "${data.employer}"
businessNature: "${data.businessNature}"
position: "${data.position || ''}"
idCode: ${data.idCode}
idType: ""
idNo: "${data.idNo}"
personalQuest1: "${data.personalQuest1}"
personalQuest2: "${data.personalQuest2}"
personalQuest3: "${data.personalQuest3}"
personalQuest4: "N/A"
personalAns1: "${data.personalAns1 || 'N/A'}"
personalAns2: "${data.personalAns2 || 'N/A'}"
personalAns3: "${data.personalAns3 || 'N/A'}"
personalAns4: "N/A"
}
financial_info: { annualIncome: ${data.annualIncome} }
address: {
addressType: ${data.addressType}
addressLine: "${data.addressLine}"
country: "${data.country}"
province: "${data.province || ''}"
town_city: "${data.town_city || ''}"
}
agent: ${data.agent || null}
proccess: {
kycStatus: VERIFIED
personalInfoStatus: VERIFIED
professionalInfoStatus: VERIFIED
fatcaStatus: VERIFIED
riskAssessmentStatus: VERIFIED
interviewStatus: VERIFIED
}
}
}
) {
customer {
id
}
}
}
`;
};
export const createCorporateGQL = (data) => {
return `
mutation {
createCustomer(
input: {
data: {
name: "${data.companyName}"
customerType: ${data.customerType}
personal_info: {
fullName: "${data.companyName}"
birthDate: "${data.birthDate.format('YYYY-MM-DD')}"
birthPlace: "${data.birthPlace || ''}"
email: "${data.email}"
mobile: "${data.mobile}"
landLine: "${data.landLine || ''}"
}
professional_info: {
idCode: ID8
idNo: "${data.idNo}"
businessNature: "${data.businessNature || ''}"
}
financial_info: {
sourceOfIncome: "${data.sourceOfIncome}"
}
address: {
addressType: OFFICE
addressLine: "${data.addressLine}"
country: "${data.country}"
province: "${data.province || ''}"
town_city: "${data.town_city || ''}"
}
signatories: ${data.signatories}
agent: ${data.agent}
proccess: {
kycStatus: VERIFIED
personalInfoStatus: VERIFIED
professionalInfoStatus: VERIFIED
fatcaStatus: VERIFIED
riskAssessmentStatus: VERIFIED
interviewStatus: VERIFIED
}
}
}
) {
customer {
id
}
}
}
`;
};
export const listClientGQL = () => {
return `
query {
customers {
id
customerType
countAccounts
archived
blocked
agent {
personalInfo {
fullName
}
}
personal_info {
id
fullName
email
mobile
}
}
}
`;
};
export const getClientGQL = (id) => {
const date = new Date();
const firstDay = new Date(date.getFullYear(), date.getMonth(), 1);
const lastDay = new Date(date.getFullYear(), date.getMonth() + 1, 0);
return `
query {
customer(id: ${id}) {
id
personal_info {
fullName
}
accounts {
transactions(
sort: "postedAt:asc"
where: {
postedAt_gte: "${firstDay.toISOString().split('T')[0]}"
postedAt_lte: "${lastDay.toISOString().split('T')[0]}"
status_ne: ["ARCHIVED", "CANCELLED"]
}
) {
id
acctNo
trxnType
trxnSubType
trxnRateAmt
postedAt
exptGrossAmt
actlGrossAmt
actlShares
source
fund {
id
description
currency
}
}
}
}
}
`;
};
export const uploadClientInterviewGQL = (data) => {
return `
mutation {
updateCustomer(
input: {
where: { id: ${data.id} }
data: {
interview: ${data.interview}
proccess: {
kycStatus: VERIFIED
personalInfoStatus: VERIFIED
professionalInfoStatus: VERIFIED
fatcaStatus: VERIFIED
riskAssessmentStatus: VERIFIED
interviewStatus: VERIFIED
}
}
}
) {
customer {
id
customerType
personal_info {
lastName
fullName
email
}
schedule {
id
}
}
}
}
`;
};
export const archivedClientGQL = (data) => {
return `
mutation {
updateCustomer(
input: {
where: { id: ${data.id} }
data: {
archived: true
blocked: true
}
}
) {
customer {
id
}
}
}
`;
};
|
be6ce21d863494461463ab50a0cb4150d8233268 | 5,299 | ts | TypeScript | src/reactivity/effect.ts | KesionX/ue3 | 4c252a3ac55d3ac28d5101b5d0bec4ffe233dfbb | [
"MIT"
] | 1 | 2022-03-09T14:36:03.000Z | 2022-03-09T14:36:03.000Z | src/reactivity/effect.ts | KesionX/mini-vue | 4c252a3ac55d3ac28d5101b5d0bec4ffe233dfbb | [
"MIT"
] | 1 | 2022-03-21T17:21:51.000Z | 2022-03-22T02:23:56.000Z | src/reactivity/effect.ts | KesionX/mini-vue | 4c252a3ac55d3ac28d5101b5d0bec4ffe233dfbb | [
"MIT"
] | null | null | null | export type EffectOptions = {
scheduler?: (fn: Function) => void;
lazy?: boolean;
};
export type EffectFunction<T> = {
(): T;
deps: Set<Function>[];
options?: EffectOptions;
};
export type TriggerType = "ADD" | "SET" | "DELETE";
export type TriggrtFunction = (
target: Record<string, any>,
key: PropertyKey,
ITERATE_KEY?: symbol,
MAP_KEY_ITERATE_KEY?: symbol,
type?: TriggerType,
newVal?: any
) => void;
let activeEffect: undefined | EffectFunction<any>;
const bucket = new WeakMap<any, Map<PropertyKey, Set<EffectFunction<any>>>>();
const effectStack: EffectFunction<any>[] = [];
export function effect<T>(fn: () => T, options?: EffectOptions) {
const effectFn: EffectFunction<T> = () => {
// 清除之前的effect
cleanup(effectFn);
activeEffect = effectFn;
// 压入栈中
effectStack.push(effectFn);
const res = fn();
effectStack.pop();
activeEffect = effectStack[effectStack.length - 1];
return res;
};
effectFn.deps = [] as Set<Function>[];
effectFn.options = options;
if (!options?.lazy) {
effectFn();
}
return effectFn;
}
/**
* 清除之前的绑定,用于刷新绑定effect
* 可解决分支切换问题、比如三元
* @param effectFn
*/
function cleanup<T>(effectFn: EffectFunction<T>) {
for (let index = 0; index < effectFn.deps.length; index++) {
const deps = effectFn.deps[index];
deps.delete(effectFn);
}
effectFn.deps.length = 0;
}
export function track(target: Record<string, any>, key: PropertyKey) {
if (!activeEffect) return;
// data or props
let depsMap = bucket.get(target);
if (!depsMap) {
bucket.set(target, (depsMap = new Map()));
}
// 属性值对应的set,set里可能存在多个effect函数
let deps: Set<EffectFunction<any>> | undefined = depsMap.get(key);
if (!deps) {
depsMap.set(key, (deps = new Set()));
}
// 属性对应的effect函数、effect可能存在多个、同个则覆盖
deps.add(activeEffect);
// 将当前effect添加依赖的effect
activeEffect.deps.push(deps);
}
export function trigger(
target: Record<string, any>,
key: PropertyKey,
ITERATE_KEY?: symbol,
MAP_KEY_ITERATE_KEY?: symbol,
type?: TriggerType,
newVal?: any
) {
const depsMap = bucket.get(target);
if (!depsMap) return;
// 获取对应值的所有 effects
const effects: Set<EffectFunction<any>> | undefined = depsMap.get(key);
// 取得与ITERATE_KEY关联的副作用函数
let iterateEffects: Set<EffectFunction<any>> | undefined;
if (ITERATE_KEY) {
iterateEffects = depsMap.get(ITERATE_KEY);
}
let mapKeyIterateEffects: Set<EffectFunction<any>> | undefined;
if (MAP_KEY_ITERATE_KEY) {
mapKeyIterateEffects = depsMap.get(MAP_KEY_ITERATE_KEY);
}
// 分支--防止无限循环
const effectsToRun = new Set<EffectFunction<any>>();
effects &&
effects.forEach(effectFn => {
if (activeEffect !== effectFn) {
effectsToRun.add(effectFn);
}
});
// set
if (
target instanceof Set &&
(type === "SET" || type === "ADD" || type === "DELETE")
) {
ITERATE_KEY &&
(iterateEffects = depsMap.get(ITERATE_KEY)) &&
iterateEffects.forEach(effectFn => {
if (activeEffect !== effectFn) {
effectsToRun.add(effectFn);
}
});
}
// map
if (
target instanceof Map &&
(type === "SET" || type === "ADD" || type === "DELETE")
) {
ITERATE_KEY &&
(iterateEffects = depsMap.get(ITERATE_KEY)) &&
iterateEffects.forEach(effectFn => {
if (activeEffect !== effectFn) {
effectsToRun.add(effectFn);
}
});
}
if (
target instanceof Map &&
(type === "ADD" || type === "DELETE")
) {
MAP_KEY_ITERATE_KEY &&
(mapKeyIterateEffects = depsMap.get(MAP_KEY_ITERATE_KEY)) &&
mapKeyIterateEffects.forEach(effectFn => {
if (activeEffect !== effectFn) {
effectsToRun.add(effectFn);
}
});
}
// array
if (type === "ADD" && Array.isArray(target)) {
const lengthEffects = depsMap.get("length");
lengthEffects &&
lengthEffects.forEach(effectFn => {
if (activeEffect !== effectFn) {
effectsToRun.add(effectFn);
}
});
}
if (Array.isArray(target) && key === "length") {
depsMap.forEach((effects, key) => {
if ((key as number) >= (newVal as number)) {
effects.forEach(effectFn => {
if (activeEffect !== effectFn) {
effectsToRun.add(effectFn);
}
});
}
});
}
// object
(type === "ADD" || type === "DELETE") &&
iterateEffects &&
iterateEffects.forEach(effectFn => {
if (activeEffect !== effectFn) {
effectsToRun.add(effectFn);
}
});
effectsToRun.forEach(effectFn => {
// 调度器执行
if (effectFn?.options?.scheduler) {
effectFn?.options.scheduler(effectFn);
} else {
effectFn();
}
});
}
| 27.889474 | 78 | 0.542178 | 155 | 14 | 0 | 21 | 15 | 4 | 2 | 17 | 12 | 4 | 6 | 11.357143 | 1,417 | 0.0247 | 0.010586 | 0.002823 | 0.002823 | 0.004234 | 0.314815 | 0.222222 | 0.261579 | export type EffectOptions = {
scheduler?;
lazy?;
};
export type EffectFunction<T> = {
();
deps;
options?;
};
export type TriggerType = "ADD" | "SET" | "DELETE";
export type TriggrtFunction = (
target,
key,
ITERATE_KEY?,
MAP_KEY_ITERATE_KEY?,
type?,
newVal?
) => void;
let activeEffect;
const bucket = new WeakMap<any, Map<PropertyKey, Set<EffectFunction<any>>>>();
const effectStack = [];
export function effect<T>(fn, options?) {
/* Example usages of 'effectFn' are shown below:
// 清除之前的effect
cleanup(effectFn);
activeEffect = effectFn;
// 压入栈中
effectStack.push(effectFn);
effectFn.deps = [] as Set<Function>[];
effectFn.options = options;
effectFn();
return effectFn;
;
index < effectFn.deps.length;
effectFn.deps[index];
deps.delete(effectFn);
effectFn.deps.length = 0;
activeEffect !== effectFn;
effectsToRun.add(effectFn);
effectFn?.options?.scheduler;
effectFn?.options.scheduler(effectFn);
*/
const effectFn = () => {
// 清除之前的effect
cleanup(effectFn);
activeEffect = effectFn;
// 压入栈中
effectStack.push(effectFn);
const res = fn();
effectStack.pop();
activeEffect = effectStack[effectStack.length - 1];
return res;
};
effectFn.deps = [] as Set<Function>[];
effectFn.options = options;
if (!options?.lazy) {
effectFn();
}
return effectFn;
}
/**
* 清除之前的绑定,用于刷新绑定effect
* 可解决分支切换问题、比如三元
* @param effectFn
*/
/* Example usages of 'cleanup' are shown below:
// 清除之前的effect
cleanup(effectFn);
*/
function cleanup<T>(effectFn) {
for (let index = 0; index < effectFn.deps.length; index++) {
const deps = effectFn.deps[index];
deps.delete(effectFn);
}
effectFn.deps.length = 0;
}
export function track(target, key) {
if (!activeEffect) return;
// data or props
let depsMap = bucket.get(target);
if (!depsMap) {
bucket.set(target, (depsMap = new Map()));
}
// 属性值对应的set,set里可能存在多个effect函数
let deps = depsMap.get(key);
if (!deps) {
depsMap.set(key, (deps = new Set()));
}
// 属性对应的effect函数、effect可能存在多个、同个则覆盖
deps.add(activeEffect);
// 将当前effect添加依赖的effect
activeEffect.deps.push(deps);
}
export function trigger(
target,
key,
ITERATE_KEY?,
MAP_KEY_ITERATE_KEY?,
type?,
newVal?
) {
const depsMap = bucket.get(target);
if (!depsMap) return;
// 获取对应值的所有 effects
const effects = depsMap.get(key);
// 取得与ITERATE_KEY关联的副作用函数
let iterateEffects;
if (ITERATE_KEY) {
iterateEffects = depsMap.get(ITERATE_KEY);
}
let mapKeyIterateEffects;
if (MAP_KEY_ITERATE_KEY) {
mapKeyIterateEffects = depsMap.get(MAP_KEY_ITERATE_KEY);
}
// 分支--防止无限循环
const effectsToRun = new Set<EffectFunction<any>>();
effects &&
effects.forEach(effectFn => {
if (activeEffect !== effectFn) {
effectsToRun.add(effectFn);
}
});
// set
if (
target instanceof Set &&
(type === "SET" || type === "ADD" || type === "DELETE")
) {
ITERATE_KEY &&
(iterateEffects = depsMap.get(ITERATE_KEY)) &&
iterateEffects.forEach(effectFn => {
if (activeEffect !== effectFn) {
effectsToRun.add(effectFn);
}
});
}
// map
if (
target instanceof Map &&
(type === "SET" || type === "ADD" || type === "DELETE")
) {
ITERATE_KEY &&
(iterateEffects = depsMap.get(ITERATE_KEY)) &&
iterateEffects.forEach(effectFn => {
if (activeEffect !== effectFn) {
effectsToRun.add(effectFn);
}
});
}
if (
target instanceof Map &&
(type === "ADD" || type === "DELETE")
) {
MAP_KEY_ITERATE_KEY &&
(mapKeyIterateEffects = depsMap.get(MAP_KEY_ITERATE_KEY)) &&
mapKeyIterateEffects.forEach(effectFn => {
if (activeEffect !== effectFn) {
effectsToRun.add(effectFn);
}
});
}
// array
if (type === "ADD" && Array.isArray(target)) {
const lengthEffects = depsMap.get("length");
lengthEffects &&
lengthEffects.forEach(effectFn => {
if (activeEffect !== effectFn) {
effectsToRun.add(effectFn);
}
});
}
if (Array.isArray(target) && key === "length") {
depsMap.forEach((effects, key) => {
if ((key as number) >= (newVal as number)) {
effects.forEach(effectFn => {
if (activeEffect !== effectFn) {
effectsToRun.add(effectFn);
}
});
}
});
}
// object
(type === "ADD" || type === "DELETE") &&
iterateEffects &&
iterateEffects.forEach(effectFn => {
if (activeEffect !== effectFn) {
effectsToRun.add(effectFn);
}
});
effectsToRun.forEach(effectFn => {
// 调度器执行
if (effectFn?.options?.scheduler) {
effectFn?.options.scheduler(effectFn);
} else {
effectFn();
}
});
}
|
be953b19d10affe746aff7e1d8e63ae9bb2f76f1 | 2,027 | ts | TypeScript | src/app/models/model-status.model.ts | os-climate/sostrades-webgui | 029dc7f13850997fb756991e98c2b6d4d837de51 | [
"MIT",
"Apache-2.0",
"BSD-3-Clause"
] | 1 | 2022-03-16T08:25:41.000Z | 2022-03-16T08:25:41.000Z | src/app/models/model-status.model.ts | os-climate/sostrades-webgui | 029dc7f13850997fb756991e98c2b6d4d837de51 | [
"MIT",
"Apache-2.0",
"BSD-3-Clause"
] | null | null | null | src/app/models/model-status.model.ts | os-climate/sostrades-webgui | 029dc7f13850997fb756991e98c2b6d4d837de51 | [
"MIT",
"Apache-2.0",
"BSD-3-Clause"
] | null | null | null | export class ModelStatus {
constructor(
public id: string,
public name: string,
public description: string,
public modelType: string,
public source: string,
public delivered: string,
public implemented: string,
public lastPublicationDate: string,
public validator: string,
public validated: string,
public discipline: string,
public processesUsingModel: number,
public processesUsingModelList: {},
public inputsParametersQuantity: number,
public outputsParametersQuantity: number) {
}
public static Create(jsonData: any): ModelStatus {
const result: ModelStatus = new ModelStatus(
jsonData[ModelStatusAttributes.ID],
jsonData[ModelStatusAttributes.NAME],
jsonData[ModelStatusAttributes.DESCRIPTION],
jsonData[ModelStatusAttributes.MODELTYPE],
jsonData[ModelStatusAttributes.SOURCE],
jsonData[ModelStatusAttributes.DELIVERED],
jsonData[ModelStatusAttributes.IMPLEMENTED],
jsonData[ModelStatusAttributes.LASTPUBLICATIONDATE],
jsonData[ModelStatusAttributes.VALIDATOR],
jsonData[ModelStatusAttributes.VALIDATED],
jsonData[ModelStatusAttributes.DISCIPLINE],
jsonData[ModelStatusAttributes.PROCESSUSINGMODEL],
jsonData[ModelStatusAttributes.PROCESSUSINGMODELLIST],
jsonData[ModelStatusAttributes.INPUTSPARAMETERSQUANTITY],
jsonData[ModelStatusAttributes.OUTPUTSPARAMETERSQUANTITY]);
return result;
}
}
export enum ModelStatusAttributes {
ID = 'id',
NAME = 'name',
DESCRIPTION = 'description',
MODELTYPE = 'model_type',
SOURCE = 'source',
DELIVERED = 'delivered',
IMPLEMENTED = 'implemented',
LASTPUBLICATIONDATE = 'last_publication_date',
VALIDATOR = 'validator',
VALIDATED = 'validated',
DISCIPLINE = 'discipline',
PROCESSUSINGMODEL = 'processes_using_model',
PROCESSUSINGMODELLIST = 'processes_using_model_list',
INPUTSPARAMETERSQUANTITY = 'inputs_parameters_quantity',
OUTPUTSPARAMETERSQUANTITY = 'outputs_parameters_quantity'
}
| 33.783333 | 65 | 0.752343 | 55 | 2 | 0 | 16 | 1 | 0 | 0 | 1 | 14 | 1 | 0 | 8.5 | 456 | 0.039474 | 0.002193 | 0 | 0.002193 | 0 | 0.052632 | 0.736842 | 0.271342 | export class ModelStatus {
constructor(
public id,
public name,
public description,
public modelType,
public source,
public delivered,
public implemented,
public lastPublicationDate,
public validator,
public validated,
public discipline,
public processesUsingModel,
public processesUsingModelList,
public inputsParametersQuantity,
public outputsParametersQuantity) {
}
public static Create(jsonData) {
const result = new ModelStatus(
jsonData[ModelStatusAttributes.ID],
jsonData[ModelStatusAttributes.NAME],
jsonData[ModelStatusAttributes.DESCRIPTION],
jsonData[ModelStatusAttributes.MODELTYPE],
jsonData[ModelStatusAttributes.SOURCE],
jsonData[ModelStatusAttributes.DELIVERED],
jsonData[ModelStatusAttributes.IMPLEMENTED],
jsonData[ModelStatusAttributes.LASTPUBLICATIONDATE],
jsonData[ModelStatusAttributes.VALIDATOR],
jsonData[ModelStatusAttributes.VALIDATED],
jsonData[ModelStatusAttributes.DISCIPLINE],
jsonData[ModelStatusAttributes.PROCESSUSINGMODEL],
jsonData[ModelStatusAttributes.PROCESSUSINGMODELLIST],
jsonData[ModelStatusAttributes.INPUTSPARAMETERSQUANTITY],
jsonData[ModelStatusAttributes.OUTPUTSPARAMETERSQUANTITY]);
return result;
}
}
export enum ModelStatusAttributes {
ID = 'id',
NAME = 'name',
DESCRIPTION = 'description',
MODELTYPE = 'model_type',
SOURCE = 'source',
DELIVERED = 'delivered',
IMPLEMENTED = 'implemented',
LASTPUBLICATIONDATE = 'last_publication_date',
VALIDATOR = 'validator',
VALIDATED = 'validated',
DISCIPLINE = 'discipline',
PROCESSUSINGMODEL = 'processes_using_model',
PROCESSUSINGMODELLIST = 'processes_using_model_list',
INPUTSPARAMETERSQUANTITY = 'inputs_parameters_quantity',
OUTPUTSPARAMETERSQUANTITY = 'outputs_parameters_quantity'
}
|
bebc63c3e75a9be3e8a91856e610b3ebd67abf68 | 2,811 | ts | TypeScript | components/layouts/Tabbed/tabbed.helper.ts | CivicDataLab/opub | c5951d14a9ceac3f2999c2d0f45b0694a8137d33 | [
"MIT"
] | 1 | 2022-03-01T14:52:35.000Z | 2022-03-01T14:52:35.000Z | components/layouts/Tabbed/tabbed.helper.ts | CivicDataLab/opub | c5951d14a9ceac3f2999c2d0f45b0694a8137d33 | [
"MIT"
] | 2 | 2022-02-09T09:23:53.000Z | 2022-03-17T15:40:12.000Z | components/layouts/Tabbed/tabbed.helper.ts | CivicDataLab/opub | c5951d14a9ceac3f2999c2d0f45b0694a8137d33 | [
"MIT"
] | 1 | 2022-02-01T09:08:03.000Z | 2022-02-01T09:08:03.000Z | export function tabbedInterface(tablist, panels) {
// Get relevant elements and collections
const tabs = tablist.querySelectorAll('a');
// The tab switching function
const switchTab = (oldTab, newTab) => {
newTab.focus();
// Make the active tab focusable by the user (Tab key)
newTab.removeAttribute('tabindex');
// Set the selected state
newTab.setAttribute('aria-selected', 'true');
oldTab.removeAttribute('aria-selected');
oldTab.setAttribute('tabindex', '-1');
// Get the indices of the new and old tabs to find the correct
// tab panels to show and hide
let index = Array.prototype.indexOf.call(tabs, newTab);
let oldIndex = Array.prototype.indexOf.call(tabs, oldTab);
panels[oldIndex].hidden = true;
panels[index].hidden = false;
};
// Add the tablist role to the first <ul> in the .tabbed container
tablist.setAttribute('role', 'tablist');
// Add semantics are remove user focusability for each tab
Array.prototype.forEach.call(tabs, (tab, i) => {
tab.setAttribute('role', 'tab');
tab.setAttribute('id', 'tab' + (i + 1));
tab.setAttribute('tabindex', '-1');
tab.parentNode.setAttribute('role', 'presentation');
// Handle clicking of tabs for mouse users
tab.addEventListener('click', (e) => {
e.preventDefault();
let currentTab = tablist.querySelector('[aria-selected]');
if (e.currentTarget !== currentTab) {
switchTab(currentTab, e.currentTarget);
}
});
// Handle keydown events for keyboard users
tab.addEventListener('keydown', (e) => {
// Get the index of the current tab in the tabs node list
let index = Array.prototype.indexOf.call(tabs, e.currentTarget);
// Work out which key the user is pressing and
// Calculate the new tab's index where appropriate
let dir =
e.which === 37
? index - 1
: e.which === 39
? index + 1
: e.which === 40
? 'down'
: null;
if (dir !== null) {
e.preventDefault();
// If the down key is pressed, move focus to the open panel,
// otherwise switch to the adjacent tab
dir === 'down'
? panels[i].focus()
: tabs[dir]
? switchTab(e.currentTarget, tabs[dir])
: void 0;
}
});
});
// Add tab panel semantics and hide them all
Array.prototype.forEach.call(panels, (panel, i) => {
panel.setAttribute('role', 'tabpanel');
panel.setAttribute('tabindex', '-1');
panel.setAttribute('aria-labelledby', tabs[i].id);
panel.hidden = true;
});
// Initially activate the first tab and reveal the first tab panel
tabs[0].removeAttribute('tabindex');
tabs[0].setAttribute('aria-selected', 'true');
panels[0].hidden = false;
}
| 34.703704 | 70 | 0.62291 | 56 | 6 | 0 | 10 | 7 | 0 | 1 | 0 | 0 | 0 | 0 | 19.833333 | 704 | 0.022727 | 0.009943 | 0 | 0 | 0 | 0 | 0 | 0.256018 | export function tabbedInterface(tablist, panels) {
// Get relevant elements and collections
const tabs = tablist.querySelectorAll('a');
// The tab switching function
/* Example usages of 'switchTab' are shown below:
switchTab(currentTab, e.currentTarget);
// If the down key is pressed, move focus to the open panel,
// otherwise switch to the adjacent tab
dir === 'down'
? panels[i].focus()
: tabs[dir]
? switchTab(e.currentTarget, tabs[dir])
: void 0;
*/
const switchTab = (oldTab, newTab) => {
newTab.focus();
// Make the active tab focusable by the user (Tab key)
newTab.removeAttribute('tabindex');
// Set the selected state
newTab.setAttribute('aria-selected', 'true');
oldTab.removeAttribute('aria-selected');
oldTab.setAttribute('tabindex', '-1');
// Get the indices of the new and old tabs to find the correct
// tab panels to show and hide
let index = Array.prototype.indexOf.call(tabs, newTab);
let oldIndex = Array.prototype.indexOf.call(tabs, oldTab);
panels[oldIndex].hidden = true;
panels[index].hidden = false;
};
// Add the tablist role to the first <ul> in the .tabbed container
tablist.setAttribute('role', 'tablist');
// Add semantics are remove user focusability for each tab
Array.prototype.forEach.call(tabs, (tab, i) => {
tab.setAttribute('role', 'tab');
tab.setAttribute('id', 'tab' + (i + 1));
tab.setAttribute('tabindex', '-1');
tab.parentNode.setAttribute('role', 'presentation');
// Handle clicking of tabs for mouse users
tab.addEventListener('click', (e) => {
e.preventDefault();
let currentTab = tablist.querySelector('[aria-selected]');
if (e.currentTarget !== currentTab) {
switchTab(currentTab, e.currentTarget);
}
});
// Handle keydown events for keyboard users
tab.addEventListener('keydown', (e) => {
// Get the index of the current tab in the tabs node list
let index = Array.prototype.indexOf.call(tabs, e.currentTarget);
// Work out which key the user is pressing and
// Calculate the new tab's index where appropriate
let dir =
e.which === 37
? index - 1
: e.which === 39
? index + 1
: e.which === 40
? 'down'
: null;
if (dir !== null) {
e.preventDefault();
// If the down key is pressed, move focus to the open panel,
// otherwise switch to the adjacent tab
dir === 'down'
? panels[i].focus()
: tabs[dir]
? switchTab(e.currentTarget, tabs[dir])
: void 0;
}
});
});
// Add tab panel semantics and hide them all
Array.prototype.forEach.call(panels, (panel, i) => {
panel.setAttribute('role', 'tabpanel');
panel.setAttribute('tabindex', '-1');
panel.setAttribute('aria-labelledby', tabs[i].id);
panel.hidden = true;
});
// Initially activate the first tab and reveal the first tab panel
tabs[0].removeAttribute('tabindex');
tabs[0].setAttribute('aria-selected', 'true');
panels[0].hidden = false;
}
|
6252bc45a1329837f6006aec73595691bf15e3b1 | 7,283 | ts | TypeScript | src/sprintf.ts | alegemaate/allegrots | b041e90198d56453afc34ec4c90b2d277d316ca1 | [
"MIT"
] | null | null | null | src/sprintf.ts | alegemaate/allegrots | b041e90198d56453afc34ec4c90b2d277d316ca1 | [
"MIT"
] | 2 | 2022-01-15T07:26:47.000Z | 2022-03-31T23:01:09.000Z | src/sprintf.ts | alegemaate/allegrots | b041e90198d56453afc34ec4c90b2d277d316ca1 | [
"MIT"
] | null | null | null | /* eslint-disable */
const re = {
not_string: /[^s]/u,
not_bool: /[^t]/u,
not_type: /[^T]/u,
not_primitive: /[^v]/u,
number: /[diefg]/u,
numeric_arg: /[bcdiefguxX]/u,
json: /[j]/u,
not_json: /[^j]/u,
text: /^[^\x25]+/u,
modulo: /^\x25{2}/u,
placeholder: /^\x25(?:([1-9]\d*)\$|\(([^)]+)\))?(\+)?(0|'[^$])?(-)?(\d+)?(?:\.(\d+))?([b-gijostTuvxX])/u,
key: /^([a-z_][a-z_\d]*)/i,
key_access: /^\.([a-z_][a-z_\d]*)/iu,
index_access: /^\[(\d+)\]/u,
sign: /^[+-]/u,
};
export function sprintf(key: string, ...args: (number | string)[]) {
// `arguments` is not an array, but should be fine for this call
return sprintf_format(sprintf_parse(key), [key, ...args]);
}
export function vsprintf(fmt: string, argv: (number | string)[]) {
return sprintf.apply(null, [fmt, ...argv]);
}
function sprintf_format(parse_tree: any, argv: (number | string)[]) {
let cursor = 1;
let tree_length = parse_tree.length;
let arg: any;
let output = "";
let i: number;
let k: number;
let ph;
let pad;
let pad_character;
let pad_length;
let is_positive;
let sign;
for (i = 0; i < tree_length; i++) {
if (typeof parse_tree[i] === "string") {
output += parse_tree[i];
} else if (typeof parse_tree[i] === "object") {
ph = parse_tree[i]; // convenience purposes only
if (ph.keys) {
// keyword argument
arg = argv[cursor];
for (k = 0; k < ph.keys.length; k++) {
if (arg == undefined) {
throw new Error(
sprintf(
'[sprintf] Cannot access property "%s" of undefined value "%s"',
ph.keys[k],
ph.keys[k - 1]
)
);
}
arg = arg[ph.keys[k]];
}
} else if (ph.param_no) {
// positional argument (explicit)
arg = argv[ph.param_no];
} else {
// positional argument (implicit)
arg = argv[cursor++];
}
if (
re.not_type.test(ph.type) &&
re.not_primitive.test(ph.type) &&
arg instanceof Function
) {
arg = arg();
}
if (
re.numeric_arg.test(ph.type) &&
typeof arg !== "number" &&
isNaN(arg)
) {
throw new TypeError(
sprintf("[sprintf] expecting number but found %T", arg)
);
}
if (re.number.test(ph.type)) {
is_positive = arg >= 0;
}
switch (ph.type) {
case "b":
arg = parseInt(arg, 10).toString(2);
break;
case "c":
arg = String.fromCharCode(parseInt(arg, 10));
break;
case "d":
case "i":
arg = parseInt(arg, 10);
break;
case "j":
arg = JSON.stringify(arg, null, ph.width ? parseInt(ph.width) : 0);
break;
case "e":
arg = ph.precision
? parseFloat(arg).toExponential(ph.precision)
: parseFloat(arg).toExponential();
break;
case "f":
arg = ph.precision
? parseFloat(arg).toFixed(ph.precision)
: parseFloat(arg);
break;
case "g":
arg = ph.precision
? String(Number(arg.toPrecision(ph.precision)))
: parseFloat(arg);
break;
case "o":
arg = (parseInt(arg, 10) >>> 0).toString(8);
break;
case "s":
arg = String(arg);
arg = ph.precision ? arg.substring(0, ph.precision) : arg;
break;
case "t":
arg = String(!!arg);
arg = ph.precision ? arg.substring(0, ph.precision) : arg;
break;
case "T":
arg = Object.prototype.toString.call(arg).slice(8, -1).toLowerCase();
arg = ph.precision ? arg.substring(0, ph.precision) : arg;
break;
case "u":
arg = parseInt(arg, 10) >>> 0;
break;
case "v":
arg = arg.valueOf();
arg = ph.precision ? arg.substring(0, ph.precision) : arg;
break;
case "x":
arg = (parseInt(arg, 10) >>> 0).toString(16);
break;
case "X":
arg = (parseInt(arg, 10) >>> 0).toString(16).toUpperCase();
break;
}
if (re.json.test(ph.type)) {
output += arg;
} else {
if (re.number.test(ph.type) && (!is_positive || ph.sign)) {
sign = is_positive ? "+" : "-";
arg = arg.toString().replace(re.sign, "");
} else {
sign = "";
}
pad_character = ph.pad_char
? ph.pad_char === "0"
? "0"
: ph.pad_char.charAt(1)
: " ";
pad_length = ph.width - (sign + arg).length;
pad = ph.width
? pad_length > 0
? pad_character.repeat(pad_length)
: ""
: "";
output += ph.align
? sign + arg + pad
: pad_character === "0"
? sign + pad + arg
: pad + sign + arg;
}
}
}
return output;
}
var sprintf_cache = Object.create(null);
function sprintf_parse(fmt: string) {
if (sprintf_cache[fmt]) {
return sprintf_cache[fmt];
}
let _fmt = fmt;
let match: any;
let parse_tree: any[] = [];
let arg_names = 0;
while (_fmt) {
if ((match = re.text.exec(_fmt)) !== null) {
parse_tree.push(match[0]);
} else if ((match = re.modulo.exec(_fmt)) !== null) {
parse_tree.push("%");
} else if ((match = re.placeholder.exec(_fmt)) !== null) {
if (match[2]) {
arg_names |= 1;
let field_list: (string | undefined)[] = [];
let replacement_field = match[2];
let field_match: RegExpExecArray | null = null;
if ((field_match = re.key.exec(replacement_field)) !== null) {
field_list.push(field_match[1]);
while (
(replacement_field = replacement_field.substring(
field_match[0]?.length ?? 0
)) !== ""
) {
if (
(field_match = re.key_access.exec(replacement_field)) !== null
) {
field_list.push(field_match[1]);
} else if (
(field_match = re.index_access.exec(replacement_field)) !== null
) {
field_list.push(field_match[1]);
} else {
throw new SyntaxError(
"[sprintf] failed to parse named argument key"
);
}
}
} else {
throw new SyntaxError("[sprintf] failed to parse named argument key");
}
match[2] = field_list;
} else {
arg_names |= 2;
}
if (arg_names === 3) {
throw new Error(
"[sprintf] mixing positional and named placeholders is not (yet) supported"
);
}
parse_tree.push({
placeholder: match[0],
param_no: match[1],
keys: match[2],
sign: match[3],
pad_char: match[4],
align: match[5],
width: match[6],
precision: match[7],
type: match[8],
});
} else {
throw new SyntaxError("[sprintf] unexpected placeholder");
}
_fmt = _fmt.substring(match[0]?.length ?? 0);
}
return (sprintf_cache[fmt] = parse_tree);
}
| 28.449219 | 107 | 0.487711 | 238 | 4 | 0 | 7 | 21 | 0 | 3 | 4 | 12 | 0 | 4 | 53 | 2,098 | 0.005243 | 0.01001 | 0 | 0 | 0.001907 | 0.125 | 0.375 | 0.213217 | /* eslint-disable */
const re = {
not_string: /[^s]/u,
not_bool: /[^t]/u,
not_type: /[^T]/u,
not_primitive: /[^v]/u,
number: /[diefg]/u,
numeric_arg: /[bcdiefguxX]/u,
json: /[j]/u,
not_json: /[^j]/u,
text: /^[^\x25]+/u,
modulo: /^\x25{2}/u,
placeholder: /^\x25(?:([1-9]\d*)\$|\(([^)]+)\))?(\+)?(0|'[^$])?(-)?(\d+)?(?:\.(\d+))?([b-gijostTuvxX])/u,
key: /^([a-z_][a-z_\d]*)/i,
key_access: /^\.([a-z_][a-z_\d]*)/iu,
index_access: /^\[(\d+)\]/u,
sign: /^[+-]/u,
};
export /* Example usages of 'sprintf' are shown below:
sprintf.apply(null, [fmt, ...argv]);
new Error(sprintf('[sprintf] Cannot access property "%s" of undefined value "%s"', ph.keys[k], ph.keys[k - 1]));
new TypeError(sprintf("[sprintf] expecting number but found %T", arg));
*/
function sprintf(key, ...args) {
// `arguments` is not an array, but should be fine for this call
return sprintf_format(sprintf_parse(key), [key, ...args]);
}
export function vsprintf(fmt, argv) {
return sprintf.apply(null, [fmt, ...argv]);
}
/* Example usages of 'sprintf_format' are shown below:
sprintf_format(sprintf_parse(key), [key, ...args]);
*/
function sprintf_format(parse_tree, argv) {
let cursor = 1;
let tree_length = parse_tree.length;
let arg;
let output = "";
let i;
let k;
let ph;
let pad;
let pad_character;
let pad_length;
let is_positive;
let sign;
for (i = 0; i < tree_length; i++) {
if (typeof parse_tree[i] === "string") {
output += parse_tree[i];
} else if (typeof parse_tree[i] === "object") {
ph = parse_tree[i]; // convenience purposes only
if (ph.keys) {
// keyword argument
arg = argv[cursor];
for (k = 0; k < ph.keys.length; k++) {
if (arg == undefined) {
throw new Error(
sprintf(
'[sprintf] Cannot access property "%s" of undefined value "%s"',
ph.keys[k],
ph.keys[k - 1]
)
);
}
arg = arg[ph.keys[k]];
}
} else if (ph.param_no) {
// positional argument (explicit)
arg = argv[ph.param_no];
} else {
// positional argument (implicit)
arg = argv[cursor++];
}
if (
re.not_type.test(ph.type) &&
re.not_primitive.test(ph.type) &&
arg instanceof Function
) {
arg = arg();
}
if (
re.numeric_arg.test(ph.type) &&
typeof arg !== "number" &&
isNaN(arg)
) {
throw new TypeError(
sprintf("[sprintf] expecting number but found %T", arg)
);
}
if (re.number.test(ph.type)) {
is_positive = arg >= 0;
}
switch (ph.type) {
case "b":
arg = parseInt(arg, 10).toString(2);
break;
case "c":
arg = String.fromCharCode(parseInt(arg, 10));
break;
case "d":
case "i":
arg = parseInt(arg, 10);
break;
case "j":
arg = JSON.stringify(arg, null, ph.width ? parseInt(ph.width) : 0);
break;
case "e":
arg = ph.precision
? parseFloat(arg).toExponential(ph.precision)
: parseFloat(arg).toExponential();
break;
case "f":
arg = ph.precision
? parseFloat(arg).toFixed(ph.precision)
: parseFloat(arg);
break;
case "g":
arg = ph.precision
? String(Number(arg.toPrecision(ph.precision)))
: parseFloat(arg);
break;
case "o":
arg = (parseInt(arg, 10) >>> 0).toString(8);
break;
case "s":
arg = String(arg);
arg = ph.precision ? arg.substring(0, ph.precision) : arg;
break;
case "t":
arg = String(!!arg);
arg = ph.precision ? arg.substring(0, ph.precision) : arg;
break;
case "T":
arg = Object.prototype.toString.call(arg).slice(8, -1).toLowerCase();
arg = ph.precision ? arg.substring(0, ph.precision) : arg;
break;
case "u":
arg = parseInt(arg, 10) >>> 0;
break;
case "v":
arg = arg.valueOf();
arg = ph.precision ? arg.substring(0, ph.precision) : arg;
break;
case "x":
arg = (parseInt(arg, 10) >>> 0).toString(16);
break;
case "X":
arg = (parseInt(arg, 10) >>> 0).toString(16).toUpperCase();
break;
}
if (re.json.test(ph.type)) {
output += arg;
} else {
if (re.number.test(ph.type) && (!is_positive || ph.sign)) {
sign = is_positive ? "+" : "-";
arg = arg.toString().replace(re.sign, "");
} else {
sign = "";
}
pad_character = ph.pad_char
? ph.pad_char === "0"
? "0"
: ph.pad_char.charAt(1)
: " ";
pad_length = ph.width - (sign + arg).length;
pad = ph.width
? pad_length > 0
? pad_character.repeat(pad_length)
: ""
: "";
output += ph.align
? sign + arg + pad
: pad_character === "0"
? sign + pad + arg
: pad + sign + arg;
}
}
}
return output;
}
var sprintf_cache = Object.create(null);
/* Example usages of 'sprintf_parse' are shown below:
sprintf_format(sprintf_parse(key), [key, ...args]);
*/
function sprintf_parse(fmt) {
if (sprintf_cache[fmt]) {
return sprintf_cache[fmt];
}
let _fmt = fmt;
let match;
let parse_tree = [];
let arg_names = 0;
while (_fmt) {
if ((match = re.text.exec(_fmt)) !== null) {
parse_tree.push(match[0]);
} else if ((match = re.modulo.exec(_fmt)) !== null) {
parse_tree.push("%");
} else if ((match = re.placeholder.exec(_fmt)) !== null) {
if (match[2]) {
arg_names |= 1;
let field_list = [];
let replacement_field = match[2];
let field_match = null;
if ((field_match = re.key.exec(replacement_field)) !== null) {
field_list.push(field_match[1]);
while (
(replacement_field = replacement_field.substring(
field_match[0]?.length ?? 0
)) !== ""
) {
if (
(field_match = re.key_access.exec(replacement_field)) !== null
) {
field_list.push(field_match[1]);
} else if (
(field_match = re.index_access.exec(replacement_field)) !== null
) {
field_list.push(field_match[1]);
} else {
throw new SyntaxError(
"[sprintf] failed to parse named argument key"
);
}
}
} else {
throw new SyntaxError("[sprintf] failed to parse named argument key");
}
match[2] = field_list;
} else {
arg_names |= 2;
}
if (arg_names === 3) {
throw new Error(
"[sprintf] mixing positional and named placeholders is not (yet) supported"
);
}
parse_tree.push({
placeholder: match[0],
param_no: match[1],
keys: match[2],
sign: match[3],
pad_char: match[4],
align: match[5],
width: match[6],
precision: match[7],
type: match[8],
});
} else {
throw new SyntaxError("[sprintf] unexpected placeholder");
}
_fmt = _fmt.substring(match[0]?.length ?? 0);
}
return (sprintf_cache[fmt] = parse_tree);
}
|
7f5712ec06dabff06003ba15417bd3dcb2d15f53 | 3,248 | ts | TypeScript | python-argparse-generator/src/index.ts | HaeckelK/python-argparse-generator | c778575c4f1985f3ac75c65aa357dd77b49cc4c1 | [
"MIT"
] | null | null | null | python-argparse-generator/src/index.ts | HaeckelK/python-argparse-generator | c778575c4f1985f3ac75c65aa357dd77b49cc4c1 | [
"MIT"
] | 5 | 2022-02-13T10:27:23.000Z | 2022-02-13T15:29:50.000Z | python-argparse-generator/src/index.ts | HaeckelK/python-argparse-generator | c778575c4f1985f3ac75c65aa357dd77b49cc4c1 | [
"MIT"
] | null | null | null | export type Settings = {
parserName: string;
typeHints: boolean;
mainContents: string;
mainName: string;
cliName: string;
argsName: string;
};
export const defaultSettings = (): Settings => {
return {
parserName: 'parser',
typeHints: true,
mainContents: '# Contents of main',
mainName: 'main',
cliName: 'cli',
argsName: 'args',
};
};
export type Argument = {
name: string;
type: string;
variableName: string;
default: string;
required: boolean;
};
export const newArgument = (
name: string,
type: string,
variableName: string = '',
defaultValue: string = '',
required: boolean = false,
): Argument => {
if (variableName === '') {
variableName = name.replace(/-/g, '');
}
return { name, type, variableName, default: defaultValue, required };
};
function argumentToText(argument: Argument, parserName: string) {
switch (argument.type) {
case 'bool':
return `${parserName}.add_argument("${argument.name}", action="store_${argument.default}")`;
default:
let defaultDisplay;
if (argument.type === 'str') {
defaultDisplay = `"${argument.default}"`;
} else {
defaultDisplay = argument.default;
}
if (argument.default === '') {
return `${parserName}.add_argument("${argument.name}", type=${argument.type})`;
} else {
return `${parserName}.add_argument("${argument.name}", type=${argument.type}, default=${defaultDisplay})`;
}
}
}
const argumentToMainParams = (argument: Argument, typeHints: boolean) => {
if (typeHints) {
return `${argument.variableName}: ${argument.type}`;
} else {
return `${argument.variableName}`;
}
};
export const argparseCode = (args: Argument[], settings: Settings = defaultSettings()) => {
const parserName: string = settings.parserName;
const argsName: string = settings.argsName;
const mainParameters: string[] = args.map((arg) => argumentToMainParams(arg, settings.typeHints));
const argumentsText: string[] = args.map((arg) => argumentToText(arg, parserName));
const returnText: string[] = args.map((x) => {
if (x.type === 'str') {
return `"${x.variableName}": ${argsName}.${x.variableName},`;
} else {
return `"${x.variableName}": ${x.type}(${argsName}.${x.variableName}),`;
}
});
const mainReturnType = settings.typeHints ? ' -> None' : '';
const cliReturnType = settings.typeHints ? ' -> Dict[str, Any]' : '';
const typeImports = settings.typeHints ? '\nfrom typing import Dict, Any' : '';
const output = `import argparse${typeImports}
def ${settings.mainName}(${mainParameters.join(', ')})${mainReturnType}:
${settings.mainContents}
return
def ${settings.cliName}()${cliReturnType}:
formatter_class = argparse.ArgumentDefaultsHelpFormatter
${parserName} = argparse.ArgumentParser(formatter_class=formatter_class)
${argumentsText.join('\n ')}
${argsName} = ${parserName}.parse_args()
return {${returnText.join('\n ').slice(0, -1)}}
if __name__ == '__main__':
${argsName} = ${settings.cliName}()
${settings.mainName}(${args.map((x) => `${x.variableName}=${argsName}["${x.variableName}"]`).join(',\n ')})
`;
return output;
};
| 28.743363 | 119 | 0.632081 | 93 | 9 | 0 | 15 | 14 | 11 | 3 | 0 | 23 | 2 | 0 | 7.777778 | 866 | 0.027714 | 0.016166 | 0.012702 | 0.002309 | 0 | 0 | 0.469388 | 0.291609 | export type Settings = {
parserName;
typeHints;
mainContents;
mainName;
cliName;
argsName;
};
export /* Example usages of 'defaultSettings' are shown below:
defaultSettings();
*/
const defaultSettings = () => {
return {
parserName: 'parser',
typeHints: true,
mainContents: '# Contents of main',
mainName: 'main',
cliName: 'cli',
argsName: 'args',
};
};
export type Argument = {
name;
type;
variableName;
default;
required;
};
export const newArgument = (
name,
type,
variableName = '',
defaultValue = '',
required = false,
) => {
if (variableName === '') {
variableName = name.replace(/-/g, '');
}
return { name, type, variableName, default: defaultValue, required };
};
/* Example usages of 'argumentToText' are shown below:
argumentToText(arg, parserName);
*/
function argumentToText(argument, parserName) {
switch (argument.type) {
case 'bool':
return `${parserName}.add_argument("${argument.name}", action="store_${argument.default}")`;
default:
let defaultDisplay;
if (argument.type === 'str') {
defaultDisplay = `"${argument.default}"`;
} else {
defaultDisplay = argument.default;
}
if (argument.default === '') {
return `${parserName}.add_argument("${argument.name}", type=${argument.type})`;
} else {
return `${parserName}.add_argument("${argument.name}", type=${argument.type}, default=${defaultDisplay})`;
}
}
}
/* Example usages of 'argumentToMainParams' are shown below:
argumentToMainParams(arg, settings.typeHints);
*/
const argumentToMainParams = (argument, typeHints) => {
if (typeHints) {
return `${argument.variableName}: ${argument.type}`;
} else {
return `${argument.variableName}`;
}
};
export const argparseCode = (args, settings = defaultSettings()) => {
const parserName = settings.parserName;
const argsName = settings.argsName;
const mainParameters = args.map((arg) => argumentToMainParams(arg, settings.typeHints));
const argumentsText = args.map((arg) => argumentToText(arg, parserName));
const returnText = args.map((x) => {
if (x.type === 'str') {
return `"${x.variableName}": ${argsName}.${x.variableName},`;
} else {
return `"${x.variableName}": ${x.type}(${argsName}.${x.variableName}),`;
}
});
const mainReturnType = settings.typeHints ? ' -> None' : '';
const cliReturnType = settings.typeHints ? ' -> Dict[str, Any]' : '';
const typeImports = settings.typeHints ? '\nfrom typing import Dict, Any' : '';
const output = `import argparse${typeImports}
def ${settings.mainName}(${mainParameters.join(', ')})${mainReturnType}:
${settings.mainContents}
return
def ${settings.cliName}()${cliReturnType}:
formatter_class = argparse.ArgumentDefaultsHelpFormatter
${parserName} = argparse.ArgumentParser(formatter_class=formatter_class)
${argumentsText.join('\n ')}
${argsName} = ${parserName}.parse_args()
return {${returnText.join('\n ').slice(0, -1)}}
if __name__ == '__main__':
${argsName} = ${settings.cliName}()
${settings.mainName}(${args.map((x) => `${x.variableName}=${argsName}["${x.variableName}"]`).join(',\n ')})
`;
return output;
};
|
7f74afe9a1b0b056999b57f142ba8053d2f19b2d | 2,211 | ts | TypeScript | src/utils/files/parsers/parserPMM.ts | I194/PMTools_2.0 | 313dea61275c5f8b875376578a65e08b9c2fd128 | [
"MIT"
] | null | null | null | src/utils/files/parsers/parserPMM.ts | I194/PMTools_2.0 | 313dea61275c5f8b875376578a65e08b9c2fd128 | [
"MIT"
] | 1 | 2022-03-17T12:50:14.000Z | 2022-03-17T12:51:57.000Z | src/utils/files/parsers/parserPMM.ts | I194/PMTools_2.0 | 313dea61275c5f8b875376578a65e08b9c2fd128 | [
"MIT"
] | null | null | null | const parsePMM = (data: string, name: string) => {
// eslint-disable-next-line no-control-regex
const eol = new RegExp("\r?\n");
// Get all lines except first and the last one (they're garbage)
const lines = data.split(eol).slice(1).filter(line => line.length > 1);
const header = lines[0].replace(/"/g, '').split(',');
// name = header[0] || name;
// Skip 1 and 2 lines 'cause they're in the header
const interpretations = lines.slice(2).map((line, index) => {
const params = line.replace(/\s+/g, '').split(',');
// ID | CODE | STEPRANGE | N | Dg | Ig | kg | a95g | Ds | Is | ks | a95s | comment
// 'kg' and 'ks' - idiotic garbage and, moreover, there is no 'a95' - there is only MAD (Maximum Angular Deviation)
const label = params[0];
const code = params[1];
const stepRange = params[2];
const stepCount = Number(params[3]);
const Dgeo = Number(params[4]);
const Igeo = Number(params[5]);
const madGeo = Number(params[7]);
const Dstrat = Number(params[8]);
const Istrat = Number(params[9]);
// const madStrat = Number(params[11]);
// but we don't need madStrat and madGeo at the same time - they must be equal, otherwise some of them is incorrect, so...
const mad = madGeo;
const k = 0;
// comment may be with spaces
let comment = '';
for (let i = 12; i < params.length; i++) comment += params[i];
comment = comment.trim();
// there is no standard for demagnetization symbol... and idk why
const demagSmbl = stepRange.split('')[0];
const thermalTypes = ['T', 't'];
const alternatingTypes = ['M', 'm'];
let demagType: 'thermal' | 'alternating field' | undefined = undefined;
if (thermalTypes.indexOf(demagSmbl) > -1) demagType = 'thermal';
else if (alternatingTypes.indexOf(demagSmbl) > -1) demagType = 'alternating field';
return {
id: index + 1,
label,
code,
demagType,
stepRange,
stepCount,
Dgeo,
Igeo,
Dstrat,
Istrat,
mad,
k,
comment
};
});
return {
name,
interpretations,
format: "PMM",
created: new Date().toISOString(),
};
}
export default parsePMM; | 30.287671 | 126 | 0.601085 | 50 | 3 | 0 | 5 | 23 | 0 | 0 | 0 | 2 | 0 | 0 | 28 | 663 | 0.012066 | 0.034691 | 0 | 0 | 0 | 0 | 0.064516 | 0.311639 | /* Example usages of 'parsePMM' are shown below:
;
*/
const parsePMM = (data, name) => {
// eslint-disable-next-line no-control-regex
const eol = new RegExp("\r?\n");
// Get all lines except first and the last one (they're garbage)
const lines = data.split(eol).slice(1).filter(line => line.length > 1);
const header = lines[0].replace(/"/g, '').split(',');
// name = header[0] || name;
// Skip 1 and 2 lines 'cause they're in the header
const interpretations = lines.slice(2).map((line, index) => {
const params = line.replace(/\s+/g, '').split(',');
// ID | CODE | STEPRANGE | N | Dg | Ig | kg | a95g | Ds | Is | ks | a95s | comment
// 'kg' and 'ks' - idiotic garbage and, moreover, there is no 'a95' - there is only MAD (Maximum Angular Deviation)
const label = params[0];
const code = params[1];
const stepRange = params[2];
const stepCount = Number(params[3]);
const Dgeo = Number(params[4]);
const Igeo = Number(params[5]);
const madGeo = Number(params[7]);
const Dstrat = Number(params[8]);
const Istrat = Number(params[9]);
// const madStrat = Number(params[11]);
// but we don't need madStrat and madGeo at the same time - they must be equal, otherwise some of them is incorrect, so...
const mad = madGeo;
const k = 0;
// comment may be with spaces
let comment = '';
for (let i = 12; i < params.length; i++) comment += params[i];
comment = comment.trim();
// there is no standard for demagnetization symbol... and idk why
const demagSmbl = stepRange.split('')[0];
const thermalTypes = ['T', 't'];
const alternatingTypes = ['M', 'm'];
let demagType = undefined;
if (thermalTypes.indexOf(demagSmbl) > -1) demagType = 'thermal';
else if (alternatingTypes.indexOf(demagSmbl) > -1) demagType = 'alternating field';
return {
id: index + 1,
label,
code,
demagType,
stepRange,
stepCount,
Dgeo,
Igeo,
Dstrat,
Istrat,
mad,
k,
comment
};
});
return {
name,
interpretations,
format: "PMM",
created: new Date().toISOString(),
};
}
export default parsePMM; |
d5a320d9afa591ebd0028bd17f5c2c381936027b | 1,561 | ts | TypeScript | src/data-structure/queue.ts | charrue/tooltik | 822bac81c011d8fa96ebbfc3f6fc315ee0feb9d1 | [
"MIT"
] | null | null | null | src/data-structure/queue.ts | charrue/tooltik | 822bac81c011d8fa96ebbfc3f6fc315ee0feb9d1 | [
"MIT"
] | null | null | null | src/data-structure/queue.ts | charrue/tooltik | 822bac81c011d8fa96ebbfc3f6fc315ee0feb9d1 | [
"MIT"
] | 1 | 2022-03-08T02:47:58.000Z | 2022-03-08T02:47:58.000Z | interface QueueNode<T> {
value: T;
next: QueueNode<T> | null;
}
interface Queue<T extends any> {
enqueue: (value: T) => void;
dequeue: () => T | undefined;
peek: () => T | undefined;
clear: () => void;
size: () => void;
forEach: (callback?: (value: T, index: number) => void) => void;
toArray: () => T[];
}
const createNode = <T>(value: T): QueueNode<T> => {
return {
value,
next: null
}
}
export const createQueue = <T extends any>(): Queue<T> => {
let head: QueueNode<T> | null = null;
let tail: QueueNode<T> | null = null;
let size = 0;
return {
enqueue(value: T) {
const node = createNode<T>(value);
if (head && tail) {
tail.next = node
tail = node
} else {
head = node
tail = node
}
size++
},
dequeue() {
const current = head
if (!current) {
return undefined
}
head = current.next
size--
return current.value
},
peek() {
if (!head) {
return
}
return head.value
},
clear() {
head = null
tail = null
size = 0
},
size() {
return size
},
forEach(callback) {
let current = head
let index = 0
while(current) {
if (typeof callback === "function") {
callback(current.value, index)
}
current = current.next
index++
}
},
toArray() {
const arr: T[] = []
this.forEach((value) => {
arr.push(value)
})
return arr
}
}
} | 19.5125 | 66 | 0.484946 | 78 | 10 | 0 | 4 | 10 | 9 | 2 | 2 | 6 | 2 | 1 | 10 | 435 | 0.032184 | 0.022989 | 0.02069 | 0.004598 | 0.002299 | 0.060606 | 0.181818 | 0.326876 | interface QueueNode<T> {
value;
next;
}
interface Queue<T extends any> {
enqueue;
dequeue;
peek;
clear;
size;
forEach;
toArray;
}
/* Example usages of 'createNode' are shown below:
createNode<T>(value);
*/
const createNode = <T>(value) => {
return {
value,
next: null
}
}
export const createQueue = <T extends any>() => {
let head = null;
let tail = null;
let size = 0;
return {
enqueue(value) {
const node = createNode<T>(value);
if (head && tail) {
tail.next = node
tail = node
} else {
head = node
tail = node
}
size++
},
dequeue() {
const current = head
if (!current) {
return undefined
}
head = current.next
size--
return current.value
},
peek() {
if (!head) {
return
}
return head.value
},
clear() {
head = null
tail = null
size = 0
},
size() {
return size
},
forEach(callback) {
let current = head
let index = 0
while(current) {
if (typeof callback === "function") {
callback(current.value, index)
}
current = current.next
index++
}
},
toArray() {
const arr = []
this.forEach((value) => {
arr.push(value)
})
return arr
}
}
} |
d5ff2fa2b6826801f70c82d95dcdfcf780c62790 | 3,305 | ts | TypeScript | challenges/day11.ts | Ldoppea/advent-of-code-2020-typescript | 608c15619b9cae3bbc65d2d5d42455710d517221 | [
"MIT"
] | null | null | null | challenges/day11.ts | Ldoppea/advent-of-code-2020-typescript | 608c15619b9cae3bbc65d2d5d42455710d517221 | [
"MIT"
] | null | null | null | challenges/day11.ts | Ldoppea/advent-of-code-2020-typescript | 608c15619b9cae3bbc65d2d5d42455710d517221 | [
"MIT"
] | 1 | 2022-01-28T17:21:42.000Z | 2022-01-28T17:21:42.000Z | const OCCUPIED_SEAT = '#';
const EMPTY_SEAT = 'L';
const FLOOR = '.';
interface Position {
x: number,
y: number
}
interface Vector {
x: number,
y: number
}
type AdjacentSeatFinder = (input: string[], position: Position, direction: Vector) => string;
export function getAdjacentSeat(input: string[], position: Position, direction: Vector): string {
const adjacentLineIndex = position.y + direction.y;
const adjacentColumnIndex = position.x + direction.x;
const newPosition = {
x: position.x + direction.x,
y: position.y + direction.y
}
if(newPosition.y < 0 || newPosition.y >= input.length || newPosition.x < 0 || newPosition.x >= input[newPosition.y].length){
return FLOOR;
}
return input[adjacentLineIndex][adjacentColumnIndex];
}
export function getFirstSeatAtDirection(input: string[], position: Position, direction: Vector): string {
let seat: string = FLOOR;
let newPosition = position;
while(true) {
newPosition = {
x: newPosition.x + direction.x,
y: newPosition.y + direction.y
}
if(newPosition.y < 0 || newPosition.y >= input.length || newPosition.x < 0 || newPosition.x >= input[newPosition.y].length) break;
const place = input[newPosition.y][newPosition.x];
if (place !== FLOOR) {
seat = place;
break;
}
}
return seat;
}
export function computeRound(input: string[], adjacentSeatFinder: AdjacentSeatFinder, maximumAdjacentOccupiedSeats: number): string[] {
return input.map((line, lineIndex) => {
return line
.split('')
.map((seat, seatIndex) => {
if (seat === FLOOR) {
return seat;
}
let numberOfAdjacentOccupiedSeat = 0;
for (let iLine = -1; iLine <= 1; iLine++) {
for (let iColumn = -1; iColumn <= 1; iColumn ++) {
if(iLine === 0 && iColumn === 0) continue;
const position = { x: seatIndex, y: lineIndex};
const direction = { x: iColumn, y: iLine }
const adjacentSeat = adjacentSeatFinder(input, position, direction);
if (adjacentSeat === OCCUPIED_SEAT) {
numberOfAdjacentOccupiedSeat++;
}
}
}
if (numberOfAdjacentOccupiedSeat === 0) {
return OCCUPIED_SEAT;
} else if (numberOfAdjacentOccupiedSeat >= maximumAdjacentOccupiedSeats) {
return EMPTY_SEAT;
} else {
return seat;
}
})
.join('');
})
}
export function countNumberOfOccupiedSeatsAfterStabilization(input: string[]): number {
let lastMap: string[] = [];
let newMap: string[] = input;
while(JSON.stringify(lastMap) !== JSON.stringify(newMap)) {
lastMap = [...newMap];
newMap = computeRound(lastMap, getAdjacentSeat, 4);
}
return newMap
.join('')
.split('')
.filter(seat => seat === OCCUPIED_SEAT)
.length;
}
export function countNumberOfOccupiedSeatsAfterStabilizationWithRayCast(input: string[]): number {
let lastMap: string[] = [];
let newMap: string[] = input;
while(JSON.stringify(lastMap) !== JSON.stringify(newMap)) {
lastMap = [...newMap];
newMap = computeRound(lastMap, getFirstSeatAtDirection, 5);
}
return newMap
.join('')
.split('')
.filter(seat => seat === OCCUPIED_SEAT)
.length;
}
| 26.653226 | 135 | 0.622088 | 98 | 9 | 0 | 17 | 19 | 4 | 1 | 0 | 22 | 3 | 0 | 14.111111 | 906 | 0.028698 | 0.020971 | 0.004415 | 0.003311 | 0 | 0 | 0.44898 | 0.310777 | const OCCUPIED_SEAT = '#';
const EMPTY_SEAT = 'L';
const FLOOR = '.';
interface Position {
x,
y
}
interface Vector {
x,
y
}
type AdjacentSeatFinder = (input, position, direction) => string;
export /* Example usages of 'getAdjacentSeat' are shown below:
newMap = computeRound(lastMap, getAdjacentSeat, 4);
*/
function getAdjacentSeat(input, position, direction) {
const adjacentLineIndex = position.y + direction.y;
const adjacentColumnIndex = position.x + direction.x;
const newPosition = {
x: position.x + direction.x,
y: position.y + direction.y
}
if(newPosition.y < 0 || newPosition.y >= input.length || newPosition.x < 0 || newPosition.x >= input[newPosition.y].length){
return FLOOR;
}
return input[adjacentLineIndex][adjacentColumnIndex];
}
export /* Example usages of 'getFirstSeatAtDirection' are shown below:
newMap = computeRound(lastMap, getFirstSeatAtDirection, 5);
*/
function getFirstSeatAtDirection(input, position, direction) {
let seat = FLOOR;
let newPosition = position;
while(true) {
newPosition = {
x: newPosition.x + direction.x,
y: newPosition.y + direction.y
}
if(newPosition.y < 0 || newPosition.y >= input.length || newPosition.x < 0 || newPosition.x >= input[newPosition.y].length) break;
const place = input[newPosition.y][newPosition.x];
if (place !== FLOOR) {
seat = place;
break;
}
}
return seat;
}
export /* Example usages of 'computeRound' are shown below:
newMap = computeRound(lastMap, getAdjacentSeat, 4);
newMap = computeRound(lastMap, getFirstSeatAtDirection, 5);
*/
function computeRound(input, adjacentSeatFinder, maximumAdjacentOccupiedSeats) {
return input.map((line, lineIndex) => {
return line
.split('')
.map((seat, seatIndex) => {
if (seat === FLOOR) {
return seat;
}
let numberOfAdjacentOccupiedSeat = 0;
for (let iLine = -1; iLine <= 1; iLine++) {
for (let iColumn = -1; iColumn <= 1; iColumn ++) {
if(iLine === 0 && iColumn === 0) continue;
const position = { x: seatIndex, y: lineIndex};
const direction = { x: iColumn, y: iLine }
const adjacentSeat = adjacentSeatFinder(input, position, direction);
if (adjacentSeat === OCCUPIED_SEAT) {
numberOfAdjacentOccupiedSeat++;
}
}
}
if (numberOfAdjacentOccupiedSeat === 0) {
return OCCUPIED_SEAT;
} else if (numberOfAdjacentOccupiedSeat >= maximumAdjacentOccupiedSeats) {
return EMPTY_SEAT;
} else {
return seat;
}
})
.join('');
})
}
export function countNumberOfOccupiedSeatsAfterStabilization(input) {
let lastMap = [];
let newMap = input;
while(JSON.stringify(lastMap) !== JSON.stringify(newMap)) {
lastMap = [...newMap];
newMap = computeRound(lastMap, getAdjacentSeat, 4);
}
return newMap
.join('')
.split('')
.filter(seat => seat === OCCUPIED_SEAT)
.length;
}
export function countNumberOfOccupiedSeatsAfterStabilizationWithRayCast(input) {
let lastMap = [];
let newMap = input;
while(JSON.stringify(lastMap) !== JSON.stringify(newMap)) {
lastMap = [...newMap];
newMap = computeRound(lastMap, getFirstSeatAtDirection, 5);
}
return newMap
.join('')
.split('')
.filter(seat => seat === OCCUPIED_SEAT)
.length;
}
|
827363613ce8b25b320df2a9f97559bc4db11fc5 | 9,967 | ts | TypeScript | integration_tests/fetch.pb.ts | cresta/protoc-gen-grpc-gateway-ts | 082c5227b5f0f90a10cd4a593f02b397afaec472 | [
"Apache-2.0"
] | null | null | null | integration_tests/fetch.pb.ts | cresta/protoc-gen-grpc-gateway-ts | 082c5227b5f0f90a10cd4a593f02b397afaec472 | [
"Apache-2.0"
] | 1 | 2022-01-07T19:47:59.000Z | 2022-01-07T19:47:59.000Z | integration_tests/fetch.pb.ts | cresta/protoc-gen-grpc-gateway-ts | 082c5227b5f0f90a10cd4a593f02b397afaec472 | [
"Apache-2.0"
] | null | null | null | /* eslint-disable */
// @ts-nocheck
/*
* This file is a generated Typescript file for GRPC Gateway, DO NOT MODIFY
*/
/**
* base64 encoder and decoder
* Copied and adapted from https://github.com/protobufjs/protobuf.js/blob/master/lib/base64/index.js
*/
// Base64 encoding table
const b64 = new Array(64);
// Base64 decoding table
const s64 = new Array(123);
// 65..90, 97..122, 48..57, 43, 47
for (let i = 0; i < 64;)
s64[b64[i] = i < 26 ? i + 65 : i < 52 ? i + 71 : i < 62 ? i - 4 : i - 59 | 43] = i++;
export function b64Encode(buffer: Uint8Array, start: number, end: number): string {
let parts: string[] = null;
const chunk = [];
let i = 0, // output index
j = 0, // goto index
t; // temporary
while (start < end) {
const b = buffer[start++];
switch (j) {
case 0:
chunk[i++] = b64[b >> 2];
t = (b & 3) << 4;
j = 1;
break;
case 1:
chunk[i++] = b64[t | b >> 4];
t = (b & 15) << 2;
j = 2;
break;
case 2:
chunk[i++] = b64[t | b >> 6];
chunk[i++] = b64[b & 63];
j = 0;
break;
}
if (i > 8191) {
(parts || (parts = [])).push(String.fromCharCode.apply(String, chunk));
i = 0;
}
}
if (j) {
chunk[i++] = b64[t];
chunk[i++] = 61;
if (j === 1)
chunk[i++] = 61;
}
if (parts) {
if (i)
parts.push(String.fromCharCode.apply(String, chunk.slice(0, i)));
return parts.join("");
}
return String.fromCharCode.apply(String, chunk.slice(0, i));
}
const invalidEncoding = "invalid encoding";
export function b64Decode(s: string): Uint8Array {
const buffer = [];
let offset = 0;
let j = 0, // goto index
t; // temporary
for (let i = 0; i < s.length;) {
let c = s.charCodeAt(i++);
if (c === 61 && j > 1)
break;
if ((c = s64[c]) === undefined)
throw Error(invalidEncoding);
switch (j) {
case 0:
t = c;
j = 1;
break;
case 1:
buffer[offset++] = t << 2 | (c & 48) >> 4;
t = c;
j = 2;
break;
case 2:
buffer[offset++] = (t & 15) << 4 | (c & 60) >> 2;
t = c;
j = 3;
break;
case 3:
buffer[offset++] = (t & 3) << 6 | c;
j = 0;
break;
}
}
if (j === 1)
throw Error(invalidEncoding);
return new Uint8Array(buffer);
}
function b64Test(s: string): boolean {
return /^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/.test(s);
}
export interface InitReq extends RequestInit {
pathPrefix?: string
}
export function replacer(key: any, value: any): any {
if(value && value.constructor === Uint8Array) {
return b64Encode(value, 0, value.length);
}
return value;
}
export function fetchReq<I, O>(path: string, init?: InitReq): Promise<O> {
const {pathPrefix, ...req} = init || {}
const url = pathPrefix ? `${pathPrefix}${path}` : path
return fetch(url, req).then(r => r.json().then((body: O) => {
if (!r.ok) { throw body; }
return body;
})) as Promise<O>
}
// NotifyStreamEntityArrival is a callback that will be called on streaming entity arrival
export type NotifyStreamEntityArrival<T> = (resp: T) => void
/**
* fetchStreamingRequest is able to handle grpc-gateway server side streaming call
* it takes NotifyStreamEntityArrival that lets users respond to entity arrival during the call
* all entities will be returned as an array after the call finishes.
**/
export async function fetchStreamingRequest<S, R>(path: string, callback?: NotifyStreamEntityArrival<R>, init?: InitReq) {
const {pathPrefix, ...req} = init || {}
const url = pathPrefix ?`${pathPrefix}${path}` : path
const result = await fetch(url, req)
// needs to use the .ok to check the status of HTTP status code
// http other than 200 will not throw an error, instead the .ok will become false.
// see https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API/Using_Fetch#
if (!result.ok) {
const resp = await result.json()
const errMsg = resp.error && resp.error.message ? resp.error.message : ""
throw new Error(errMsg)
}
if (!result.body) {
throw new Error("response doesnt have a body")
}
await result.body
.pipeThrough(new TextDecoderStream())
.pipeThrough<R>(getNewLineDelimitedJSONDecodingStream<R>())
.pipeTo(getNotifyEntityArrivalSink((e: R) => {
if (callback) {
callback(e)
}
}))
// wait for the streaming to finish and return the success respond
return
}
/**
* JSONStringStreamController represents the transform controller that's able to transform the incoming
* new line delimited json content stream into entities and able to push the entity to the down stream
*/
interface JSONStringStreamController<T> extends TransformStreamDefaultController {
buf?: string
pos?: number
enqueue: (s: T) => void
}
/**
* getNewLineDelimitedJSONDecodingStream returns a TransformStream that's able to handle new line delimited json stream content into parsed entities
*/
function getNewLineDelimitedJSONDecodingStream<T>(): TransformStream<string, T> {
return new TransformStream({
start(controller: JSONStringStreamController<T>) {
controller.buf = ''
controller.pos = 0
},
transform(chunk: string, controller: JSONStringStreamController<T>) {
if (controller.buf === undefined) {
controller.buf = ''
}
if (controller.pos === undefined) {
controller.pos = 0
}
controller.buf += chunk
while (controller.pos < controller.buf.length) {
if (controller.buf[controller.pos] === '\n') {
const line = controller.buf.substring(0, controller.pos)
const response = JSON.parse(line)
controller.enqueue(response.result)
controller.buf = controller.buf.substring(controller.pos + 1)
controller.pos = 0
} else {
++controller.pos
}
}
}
})
}
/**
* getNotifyEntityArrivalSink takes the NotifyStreamEntityArrival callback and return
* a sink that will call the callback on entity arrival
* @param notifyCallback
*/
function getNotifyEntityArrivalSink<T>(notifyCallback: NotifyStreamEntityArrival<T>) {
return new WritableStream<T>({
write(entity: T) {
notifyCallback(entity)
}
})
}
type Primitive = string | boolean | number;
type RequestPayload = Record<string, unknown>;
type FlattenedRequestPayload = Record<string, Primitive | Array<Primitive>>;
/**
* Checks if given value is a plain object
* Logic copied and adapted from below source:
* https://github.com/char0n/ramda-adjunct/blob/master/src/isPlainObj.js
* @param {unknown} value
* @return {boolean}
*/
function isPlainObject(value: unknown): boolean {
const isObject =
Object.prototype.toString.call(value).slice(8, -1) === "Object";
const isObjLike = value !== null && isObject;
if (!isObjLike || !isObject) {
return false;
}
const proto = Object.getPrototypeOf(value);
const hasObjectConstructor =
typeof proto === "object" &&
proto.constructor === Object.prototype.constructor;
return hasObjectConstructor;
}
/**
* Checks if given value is of a primitive type
* @param {unknown} value
* @return {boolean}
*/
function isPrimitive(value: unknown): boolean {
return ["string", "number", "boolean"].some(t => typeof value === t);
}
/**
* Checks if given primitive is zero-value
* @param {Primitive} value
* @return {boolean}
*/
function isZeroValuePrimitive(value: Primitive): boolean {
return value === false || value === 0 || value === "";
}
/**
* Flattens a deeply nested request payload and returns an object
* with only primitive values and non-empty array of primitive values
* as per https://github.com/googleapis/googleapis/blob/master/google/api/http.proto
* @param {RequestPayload} requestPayload
* @param {String} path
* @return {FlattenedRequestPayload>}
*/
function flattenRequestPayload<T extends RequestPayload>(
requestPayload: T,
path: string = ""
): FlattenedRequestPayload {
return Object.keys(requestPayload).reduce(
(acc: T, key: string): T => {
const value = requestPayload[key];
const newPath = path ? [path, key].join(".") : key;
const isNonEmptyPrimitiveArray =
Array.isArray(value) &&
value.every(v => isPrimitive(v)) &&
value.length > 0;
const isNonZeroValuePrimitive =
isPrimitive(value) && !isZeroValuePrimitive(value as Primitive);
let objectToMerge = {};
if (isPlainObject(value)) {
objectToMerge = flattenRequestPayload(value as RequestPayload, newPath);
} else if (isNonZeroValuePrimitive || isNonEmptyPrimitiveArray) {
objectToMerge = { [newPath]: value };
}
return { ...acc, ...objectToMerge };
},
{} as T
) as FlattenedRequestPayload;
}
/**
* Renders a deeply nested request payload into a string of URL search
* parameters by first flattening the request payload and then removing keys
* which are already present in the URL path.
* @param {RequestPayload} requestPayload
* @param {string[]} urlPathParams
* @return {string}
*/
export function renderURLSearchParams<T extends RequestPayload>(
requestPayload: T,
urlPathParams: string[] = []
): string {
const flattenedRequestPayload = flattenRequestPayload(requestPayload);
const urlSearchParams = Object.keys(flattenedRequestPayload).reduce(
(acc: string[][], key: string): string[][] => {
// key should not be present in the url path as a parameter
const value = flattenedRequestPayload[key];
if (urlPathParams.find(f => f === key)) {
return acc;
}
return Array.isArray(value)
? [...acc, ...value.map(m => [key, m.toString()])]
: (acc = [...acc, [key, value.toString()]]);
},
[] as string[][]
);
return new URLSearchParams(urlSearchParams).toString();
} | 29.228739 | 148 | 0.629176 | 233 | 25 | 0 | 35 | 37 | 4 | 7 | 3 | 35 | 6 | 8 | 9.6 | 2,862 | 0.020964 | 0.012928 | 0.001398 | 0.002096 | 0.002795 | 0.029703 | 0.346535 | 0.265178 | /* eslint-disable */
// @ts-nocheck
/*
* This file is a generated Typescript file for GRPC Gateway, DO NOT MODIFY
*/
/**
* base64 encoder and decoder
* Copied and adapted from https://github.com/protobufjs/protobuf.js/blob/master/lib/base64/index.js
*/
// Base64 encoding table
const b64 = new Array(64);
// Base64 decoding table
const s64 = new Array(123);
// 65..90, 97..122, 48..57, 43, 47
for (let i = 0; i < 64;)
s64[b64[i] = i < 26 ? i + 65 : i < 52 ? i + 71 : i < 62 ? i - 4 : i - 59 | 43] = i++;
export /* Example usages of 'b64Encode' are shown below:
b64Encode(value, 0, value.length);
*/
function b64Encode(buffer, start, end) {
let parts = null;
const chunk = [];
let i = 0, // output index
j = 0, // goto index
t; // temporary
while (start < end) {
const b = buffer[start++];
switch (j) {
case 0:
chunk[i++] = b64[b >> 2];
t = (b & 3) << 4;
j = 1;
break;
case 1:
chunk[i++] = b64[t | b >> 4];
t = (b & 15) << 2;
j = 2;
break;
case 2:
chunk[i++] = b64[t | b >> 6];
chunk[i++] = b64[b & 63];
j = 0;
break;
}
if (i > 8191) {
(parts || (parts = [])).push(String.fromCharCode.apply(String, chunk));
i = 0;
}
}
if (j) {
chunk[i++] = b64[t];
chunk[i++] = 61;
if (j === 1)
chunk[i++] = 61;
}
if (parts) {
if (i)
parts.push(String.fromCharCode.apply(String, chunk.slice(0, i)));
return parts.join("");
}
return String.fromCharCode.apply(String, chunk.slice(0, i));
}
const invalidEncoding = "invalid encoding";
export function b64Decode(s) {
const buffer = [];
let offset = 0;
let j = 0, // goto index
t; // temporary
for (let i = 0; i < s.length;) {
let c = s.charCodeAt(i++);
if (c === 61 && j > 1)
break;
if ((c = s64[c]) === undefined)
throw Error(invalidEncoding);
switch (j) {
case 0:
t = c;
j = 1;
break;
case 1:
buffer[offset++] = t << 2 | (c & 48) >> 4;
t = c;
j = 2;
break;
case 2:
buffer[offset++] = (t & 15) << 4 | (c & 60) >> 2;
t = c;
j = 3;
break;
case 3:
buffer[offset++] = (t & 3) << 6 | c;
j = 0;
break;
}
}
if (j === 1)
throw Error(invalidEncoding);
return new Uint8Array(buffer);
}
function b64Test(s) {
return /^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/.test(s);
}
export interface InitReq extends RequestInit {
pathPrefix?
}
export function replacer(key, value) {
if(value && value.constructor === Uint8Array) {
return b64Encode(value, 0, value.length);
}
return value;
}
export function fetchReq<I, O>(path, init?) {
const {pathPrefix, ...req} = init || {}
const url = pathPrefix ? `${pathPrefix}${path}` : path
return fetch(url, req).then(r => r.json().then((body) => {
if (!r.ok) { throw body; }
return body;
})) as Promise<O>
}
// NotifyStreamEntityArrival is a callback that will be called on streaming entity arrival
export type NotifyStreamEntityArrival<T> = (resp) => void
/**
* fetchStreamingRequest is able to handle grpc-gateway server side streaming call
* it takes NotifyStreamEntityArrival that lets users respond to entity arrival during the call
* all entities will be returned as an array after the call finishes.
**/
export async function fetchStreamingRequest<S, R>(path, callback?, init?) {
const {pathPrefix, ...req} = init || {}
const url = pathPrefix ?`${pathPrefix}${path}` : path
const result = await fetch(url, req)
// needs to use the .ok to check the status of HTTP status code
// http other than 200 will not throw an error, instead the .ok will become false.
// see https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API/Using_Fetch#
if (!result.ok) {
const resp = await result.json()
const errMsg = resp.error && resp.error.message ? resp.error.message : ""
throw new Error(errMsg)
}
if (!result.body) {
throw new Error("response doesnt have a body")
}
await result.body
.pipeThrough(new TextDecoderStream())
.pipeThrough<R>(getNewLineDelimitedJSONDecodingStream<R>())
.pipeTo(getNotifyEntityArrivalSink((e) => {
if (callback) {
callback(e)
}
}))
// wait for the streaming to finish and return the success respond
return
}
/**
* JSONStringStreamController represents the transform controller that's able to transform the incoming
* new line delimited json content stream into entities and able to push the entity to the down stream
*/
interface JSONStringStreamController<T> extends TransformStreamDefaultController {
buf?
pos?
enqueue
}
/**
* getNewLineDelimitedJSONDecodingStream returns a TransformStream that's able to handle new line delimited json stream content into parsed entities
*/
/* Example usages of 'getNewLineDelimitedJSONDecodingStream' are shown below:
result.body
.pipeThrough(new TextDecoderStream())
.pipeThrough<R>(getNewLineDelimitedJSONDecodingStream<R>())
.pipeTo(getNotifyEntityArrivalSink((e) => {
if (callback) {
callback(e);
}
}));
*/
function getNewLineDelimitedJSONDecodingStream<T>() {
return new TransformStream({
start(controller) {
controller.buf = ''
controller.pos = 0
},
transform(chunk, controller) {
if (controller.buf === undefined) {
controller.buf = ''
}
if (controller.pos === undefined) {
controller.pos = 0
}
controller.buf += chunk
while (controller.pos < controller.buf.length) {
if (controller.buf[controller.pos] === '\n') {
const line = controller.buf.substring(0, controller.pos)
const response = JSON.parse(line)
controller.enqueue(response.result)
controller.buf = controller.buf.substring(controller.pos + 1)
controller.pos = 0
} else {
++controller.pos
}
}
}
})
}
/**
* getNotifyEntityArrivalSink takes the NotifyStreamEntityArrival callback and return
* a sink that will call the callback on entity arrival
* @param notifyCallback
*/
/* Example usages of 'getNotifyEntityArrivalSink' are shown below:
result.body
.pipeThrough(new TextDecoderStream())
.pipeThrough<R>(getNewLineDelimitedJSONDecodingStream<R>())
.pipeTo(getNotifyEntityArrivalSink((e) => {
if (callback) {
callback(e);
}
}));
*/
function getNotifyEntityArrivalSink<T>(notifyCallback) {
return new WritableStream<T>({
write(entity) {
notifyCallback(entity)
}
})
}
type Primitive = string | boolean | number;
type RequestPayload = Record<string, unknown>;
type FlattenedRequestPayload = Record<string, Primitive | Array<Primitive>>;
/**
* Checks if given value is a plain object
* Logic copied and adapted from below source:
* https://github.com/char0n/ramda-adjunct/blob/master/src/isPlainObj.js
* @param {unknown} value
* @return {boolean}
*/
/* Example usages of 'isPlainObject' are shown below:
isPlainObject(value);
*/
function isPlainObject(value) {
const isObject =
Object.prototype.toString.call(value).slice(8, -1) === "Object";
const isObjLike = value !== null && isObject;
if (!isObjLike || !isObject) {
return false;
}
const proto = Object.getPrototypeOf(value);
const hasObjectConstructor =
typeof proto === "object" &&
proto.constructor === Object.prototype.constructor;
return hasObjectConstructor;
}
/**
* Checks if given value is of a primitive type
* @param {unknown} value
* @return {boolean}
*/
/* Example usages of 'isPrimitive' are shown below:
isPrimitive(v);
isPrimitive(value) && !isZeroValuePrimitive(value as Primitive);
*/
function isPrimitive(value) {
return ["string", "number", "boolean"].some(t => typeof value === t);
}
/**
* Checks if given primitive is zero-value
* @param {Primitive} value
* @return {boolean}
*/
/* Example usages of 'isZeroValuePrimitive' are shown below:
isPrimitive(value) && !isZeroValuePrimitive(value as Primitive);
*/
function isZeroValuePrimitive(value) {
return value === false || value === 0 || value === "";
}
/**
* Flattens a deeply nested request payload and returns an object
* with only primitive values and non-empty array of primitive values
* as per https://github.com/googleapis/googleapis/blob/master/google/api/http.proto
* @param {RequestPayload} requestPayload
* @param {String} path
* @return {FlattenedRequestPayload>}
*/
/* Example usages of 'flattenRequestPayload' are shown below:
objectToMerge = flattenRequestPayload(value as RequestPayload, newPath);
flattenRequestPayload(requestPayload);
*/
function flattenRequestPayload<T extends RequestPayload>(
requestPayload,
path = ""
) {
return Object.keys(requestPayload).reduce(
(acc, key) => {
const value = requestPayload[key];
const newPath = path ? [path, key].join(".") : key;
const isNonEmptyPrimitiveArray =
Array.isArray(value) &&
value.every(v => isPrimitive(v)) &&
value.length > 0;
const isNonZeroValuePrimitive =
isPrimitive(value) && !isZeroValuePrimitive(value as Primitive);
let objectToMerge = {};
if (isPlainObject(value)) {
objectToMerge = flattenRequestPayload(value as RequestPayload, newPath);
} else if (isNonZeroValuePrimitive || isNonEmptyPrimitiveArray) {
objectToMerge = { [newPath]: value };
}
return { ...acc, ...objectToMerge };
},
{} as T
) as FlattenedRequestPayload;
}
/**
* Renders a deeply nested request payload into a string of URL search
* parameters by first flattening the request payload and then removing keys
* which are already present in the URL path.
* @param {RequestPayload} requestPayload
* @param {string[]} urlPathParams
* @return {string}
*/
export function renderURLSearchParams<T extends RequestPayload>(
requestPayload,
urlPathParams = []
) {
const flattenedRequestPayload = flattenRequestPayload(requestPayload);
const urlSearchParams = Object.keys(flattenedRequestPayload).reduce(
(acc, key) => {
// key should not be present in the url path as a parameter
const value = flattenedRequestPayload[key];
if (urlPathParams.find(f => f === key)) {
return acc;
}
return Array.isArray(value)
? [...acc, ...value.map(m => [key, m.toString()])]
: (acc = [...acc, [key, value.toString()]]);
},
[] as string[][]
);
return new URLSearchParams(urlSearchParams).toString();
} |
fc4626992b4f5c7c1281ee50f1a8c5edc16ed4fd | 1,993 | ts | TypeScript | src/models/Provider.ts | api-client/core | aa157d09b39efa77d49f2d425e7b37828abe0c5b | [
"Apache-2.0"
] | null | null | null | src/models/Provider.ts | api-client/core | aa157d09b39efa77d49f2d425e7b37828abe0c5b | [
"Apache-2.0"
] | 1 | 2022-02-14T00:01:04.000Z | 2022-02-14T00:04:07.000Z | src/models/Provider.ts | advanced-rest-client/core | 2efb946f786d8b46e7131c62e0011f6e090ddec3 | [
"Apache-2.0"
] | null | null | null | /**
* An interface describing a provider of a thing.
*/
export declare interface IProvider {
/**
* The data kind. The application ignores the input with an unknown `kind`, unless it can be determined from the context.
*/
kind: typeof Kind;
/**
* The URL to the provider
*/
url?: string;
/**
* The name to the provider
*/
name?: string;
/**
* The email to the provider
*/
email?: string;
}
export const Kind = 'Core#Provider';
export class Provider {
kind = Kind;
/**
* The URL to the provider
*/
url?: string;
/**
* The name to the provider
*/
name?: string;
/**
* The email to the provider
*/
email?: string;
/**
* @param input The provider definition used to restore the state.
*/
constructor(input?: string|IProvider) {
let init: IProvider;
if (typeof input === 'string') {
init = JSON.parse(input);
} else if (typeof input === 'object') {
init = input;
} else {
init = {
kind: Kind,
};
}
this.new(init);
}
/**
* Creates a new provider clearing anything that is so far defined.
*
* Note, this throws an error when the provider is not a provider object.
*/
new(init: IProvider): void {
if (!Provider.isProvider(init)) {
throw new Error(`Not a provider.`);
}
const { url, email, name } = init;
this.kind = Kind;
this.name = name;
this.email = email;
this.url = url;
}
/**
* Checks whether the input is a definition of a provider.
*/
static isProvider(input: unknown): boolean {
const typed = input as IProvider;
if (input && typed.kind === Kind) {
return true;
}
return false;
}
toJSON(): IProvider {
const result:IProvider = {
kind: Kind,
};
if (this.url) {
result.url = this.url;
}
if (this.email) {
result.email = this.email;
}
if (this.name) {
result.name = this.name;
}
return result;
}
}
| 20.131313 | 123 | 0.5715 | 58 | 4 | 0 | 3 | 5 | 8 | 2 | 0 | 10 | 2 | 3 | 9.25 | 534 | 0.013109 | 0.009363 | 0.014981 | 0.003745 | 0.005618 | 0 | 0.5 | 0.236369 | /**
* An interface describing a provider of a thing.
*/
export declare interface IProvider {
/**
* The data kind. The application ignores the input with an unknown `kind`, unless it can be determined from the context.
*/
kind;
/**
* The URL to the provider
*/
url?;
/**
* The name to the provider
*/
name?;
/**
* The email to the provider
*/
email?;
}
export const Kind = 'Core#Provider';
export class Provider {
kind = Kind;
/**
* The URL to the provider
*/
url?;
/**
* The name to the provider
*/
name?;
/**
* The email to the provider
*/
email?;
/**
* @param input The provider definition used to restore the state.
*/
constructor(input?) {
let init;
if (typeof input === 'string') {
init = JSON.parse(input);
} else if (typeof input === 'object') {
init = input;
} else {
init = {
kind: Kind,
};
}
this.new(init);
}
/**
* Creates a new provider clearing anything that is so far defined.
*
* Note, this throws an error when the provider is not a provider object.
*/
new(init) {
if (!Provider.isProvider(init)) {
throw new Error(`Not a provider.`);
}
const { url, email, name } = init;
this.kind = Kind;
this.name = name;
this.email = email;
this.url = url;
}
/**
* Checks whether the input is a definition of a provider.
*/
static isProvider(input) {
const typed = input as IProvider;
if (input && typed.kind === Kind) {
return true;
}
return false;
}
toJSON() {
const result = {
kind: Kind,
};
if (this.url) {
result.url = this.url;
}
if (this.email) {
result.email = this.email;
}
if (this.name) {
result.name = this.name;
}
return result;
}
}
|
fc832edeb15dad5bbbb1d0919a43bc88272e65e4 | 3,020 | ts | TypeScript | src/RomanNumerals.ts | runesam/roman-numerals-converter | db60370c02a39535d0d9834a0b59f40fd25d697f | [
"MIT"
] | null | null | null | src/RomanNumerals.ts | runesam/roman-numerals-converter | db60370c02a39535d0d9834a0b59f40fd25d697f | [
"MIT"
] | 3 | 2022-02-13T20:34:53.000Z | 2022-02-27T10:28:15.000Z | src/RomanNumerals.ts | runesam/roman-numerals-converter | db60370c02a39535d0d9834a0b59f40fd25d697f | [
"MIT"
] | null | null | null | class RomanNumerals {
public maxRoman = 1000000;
toRoman(arabic: number) {
const romanNumList = [
{ roman: '_M', value: 1000000 },
{ roman: '_C_M', value: 900000 },
{ roman: '_D', value: 500000 },
{ roman: '_C_D', value: 400000 },
{ roman: '_C', value: 100000 },
{ roman: '_X_C', value: 90000 },
{ roman: '_L', value: 50000 },
{ roman: '_X_L', value: 40000 },
{ roman: '_X', value: 10000 },
{ roman: '_I_X', value: 9000 },
{ roman: '_V', value: 5000 },
{ roman: '_I_V', value: 4000 },
{ roman: 'M', value: 1000 },
{ roman: 'CM', value: 900 },
{ roman: 'D', value: 500 },
{ roman: 'CD', value: 400 },
{ roman: 'C', value: 100 },
{ roman: 'XC', value: 90 },
{ roman: 'L', value: 50 },
{ roman: 'XV', value: 40 },
{ roman: 'X', value: 10 },
{ roman: 'IX', value: 9 },
{ roman: 'V', value: 5 },
{ roman: 'IV', value: 4 },
{ roman: 'I', value: 1 },
];
return romanNumList.reduce((acc, romanNum) => {
const count = Math.floor(arabic / romanNum.value);
acc += count ? Array(count).fill(romanNum.roman).join('') : '';
arabic = arabic % romanNum.value;
return acc;
}, '');
}
fromRoman(roman: string) {
const romanNumList = [
{ roman: '_C_M', value: 900000 },
{ roman: '_M', value: 1000000 },
{ roman: '_C_D', value: 400000 },
{ roman: '_D', value: 500000 },
{ roman: '_X_C', value: 90000 },
{ roman: '_C', value: 100000 },
{ roman: '_X_L', value: 40000 },
{ roman: '_L', value: 50000 },
{ roman: '_I_X', value: 9000 },
{ roman: '_X', value: 10000 },
{ roman: '_I_V', value: 4000 },
{ roman: '_V', value: 5000 },
{ roman: 'CM', value: 900 },
{ roman: 'M', value: 1000 },
{ roman: 'CD', value: 400 },
{ roman: 'D', value: 500 },
{ roman: 'XC', value: 90 },
{ roman: 'C', value: 100 },
{ roman: 'XV', value: 40 },
{ roman: 'L', value: 50 },
{ roman: 'IX', value: 9 },
{ roman: 'X', value: 10 },
{ roman: 'IV', value: 4 },
{ roman: 'V', value: 5 },
{ roman: 'I', value: 1 },
];
return romanNumList.reduce((acc, romanNum) => {
let romanNumberExists = roman.includes(romanNum.roman);
while (romanNumberExists) {
acc += romanNum.value;
roman = roman.replace(romanNum.roman, '');
romanNumberExists = roman.includes(romanNum.roman);
}
return acc;
}, 0);
}
}
export default new RomanNumerals();
| 32.12766 | 75 | 0.424172 | 77 | 4 | 0 | 6 | 4 | 1 | 0 | 0 | 2 | 1 | 0 | 20 | 1,049 | 0.009533 | 0.003813 | 0.000953 | 0.000953 | 0 | 0 | 0.133333 | 0.20621 | class RomanNumerals {
public maxRoman = 1000000;
toRoman(arabic) {
const romanNumList = [
{ roman: '_M', value: 1000000 },
{ roman: '_C_M', value: 900000 },
{ roman: '_D', value: 500000 },
{ roman: '_C_D', value: 400000 },
{ roman: '_C', value: 100000 },
{ roman: '_X_C', value: 90000 },
{ roman: '_L', value: 50000 },
{ roman: '_X_L', value: 40000 },
{ roman: '_X', value: 10000 },
{ roman: '_I_X', value: 9000 },
{ roman: '_V', value: 5000 },
{ roman: '_I_V', value: 4000 },
{ roman: 'M', value: 1000 },
{ roman: 'CM', value: 900 },
{ roman: 'D', value: 500 },
{ roman: 'CD', value: 400 },
{ roman: 'C', value: 100 },
{ roman: 'XC', value: 90 },
{ roman: 'L', value: 50 },
{ roman: 'XV', value: 40 },
{ roman: 'X', value: 10 },
{ roman: 'IX', value: 9 },
{ roman: 'V', value: 5 },
{ roman: 'IV', value: 4 },
{ roman: 'I', value: 1 },
];
return romanNumList.reduce((acc, romanNum) => {
const count = Math.floor(arabic / romanNum.value);
acc += count ? Array(count).fill(romanNum.roman).join('') : '';
arabic = arabic % romanNum.value;
return acc;
}, '');
}
fromRoman(roman) {
const romanNumList = [
{ roman: '_C_M', value: 900000 },
{ roman: '_M', value: 1000000 },
{ roman: '_C_D', value: 400000 },
{ roman: '_D', value: 500000 },
{ roman: '_X_C', value: 90000 },
{ roman: '_C', value: 100000 },
{ roman: '_X_L', value: 40000 },
{ roman: '_L', value: 50000 },
{ roman: '_I_X', value: 9000 },
{ roman: '_X', value: 10000 },
{ roman: '_I_V', value: 4000 },
{ roman: '_V', value: 5000 },
{ roman: 'CM', value: 900 },
{ roman: 'M', value: 1000 },
{ roman: 'CD', value: 400 },
{ roman: 'D', value: 500 },
{ roman: 'XC', value: 90 },
{ roman: 'C', value: 100 },
{ roman: 'XV', value: 40 },
{ roman: 'L', value: 50 },
{ roman: 'IX', value: 9 },
{ roman: 'X', value: 10 },
{ roman: 'IV', value: 4 },
{ roman: 'V', value: 5 },
{ roman: 'I', value: 1 },
];
return romanNumList.reduce((acc, romanNum) => {
let romanNumberExists = roman.includes(romanNum.roman);
while (romanNumberExists) {
acc += romanNum.value;
roman = roman.replace(romanNum.roman, '');
romanNumberExists = roman.includes(romanNum.roman);
}
return acc;
}, 0);
}
}
export default new RomanNumerals();
|
fcdbbcb545071af17a684020e478305f1e8d06c9 | 3,697 | ts | TypeScript | packages/plexus-core/src/helpers.ts | PlexusJS/plexus | cc02cebcf49c7f9aecff2102ed095d7e5bbb1d37 | [
"MIT"
] | 8 | 2022-01-12T01:19:10.000Z | 2022-03-14T22:00:01.000Z | packages/plexus-core/src/helpers.ts | PlexusJS/plexus | cc02cebcf49c7f9aecff2102ed095d7e5bbb1d37 | [
"MIT"
] | 1 | 2022-01-20T22:59:26.000Z | 2022-02-23T05:21:16.000Z | packages/plexus-core/src/helpers.ts | PlexusJS/plexus | cc02cebcf49c7f9aecff2102ed095d7e5bbb1d37 | [
"MIT"
] | null | null | null | export type AlmostAnything = string | number | symbol | Record<any, any> | Array<any> | Object
export function isObject(item: any): item is Object {
return item && item !== null && typeof item === "object" && !Array.isArray(item)
}
export function deepMerge<Thing extends Object>(target: Thing, source: Thing): Thing {
let output = Object.assign({}, target)
if ((isObject(target) && isObject(source)) || (Array.isArray(target) && Array.isArray(source))) {
for (const key in source) {
if (isObject(source[key])) {
if (!(key in target)) {
Object.assign(output, { [key]: source[key] })
} else {
output[key] = deepMerge(target[key], source[key])
}
} else {
Object.assign(output, { [key]: source[key] })
}
}
}
// if it was originally an array, return an array
if (Array.isArray(target) && Array.isArray(source)) {
return Object.values(output) as any as Thing
}
return output
}
// a deep clone of anything
export function deepClone<Type = AlmostAnything>(thing: Type): Type {
if (thing instanceof Date) {
return new Date(thing.getTime()) as any as Type
}
if (thing instanceof RegExp) {
return new RegExp(thing) as any as Type
}
// must be an object
if (isObject(thing)) {
const cloned: Type = Object.create(thing as Object)
for (const key in thing) {
if ((thing as Object).hasOwnProperty(key)) {
cloned[key] = deepClone(thing[key])
}
}
if (Array.isArray(thing)) {
return Object.values(cloned) as any as Type
}
// if it was originally an array, return an array
if (Array.isArray(thing)) {
return Object.values(cloned) as any as Type
}
// if it was originally an object, return an object
return cloned
}
return thing
}
export function isEqual(a: AlmostAnything, b: AlmostAnything): boolean {
if (a === b) {
return true
}
if (a instanceof Date && b instanceof Date) {
return a.getTime() === b.getTime()
}
if (a instanceof RegExp && b instanceof RegExp) {
return a.toString() === b.toString()
}
if (Array.isArray(a) && Array.isArray(b)) {
if (a.length !== b.length) {
return false
}
for (let i = 0; i < a.length; i++) {
if (!isEqual(a[i], b[i])) {
return false
}
}
return true
}
if (isObject(a) && isObject(b)) {
const aKeys = Object.keys(a)
const bKeys = Object.keys(b)
if (aKeys.length !== bKeys.length) {
return false
}
for (const key of aKeys) {
if (!isEqual(a[key], b[key])) {
return false
}
}
return true
}
return false
}
export const convertToString = (input: any) =>
typeof input === "object" ? JSON.stringify(input) : typeof input === "function" ? input.toString() : String(input)
export const hash = function (input: string) {
/* Simple hash function. */
let a = 1,
c = 0,
h,
o
if (input) {
a = 0
/*jshint plusplus:false bitwise:false*/
for (h = input.length - 1; h >= 0; h--) {
o = input.charCodeAt(h)
a = ((a << 6) & 268435455) + o + (o << 14)
c = a & 266338304
a = c !== 0 ? a ^ (c >> 21) : a
}
}
return String(a)
}
export const convertStringToType = (inp: string) => {
try {
// try to parse it as JSON (array or object)
return JSON.parse(inp)
} catch (e) {
// if that fails, try...
// ...as a number
const num = Number(inp)
if (!isNaN(num)) {
return num
}
// ...as a boolean
if (inp === "true") {
return true
}
if (inp === "false") {
return false
}
// ...as a string
return inp
}
}
export const genUID = () => Math.random().toString(36).substring(2, 15) + Math.random().toString(36).substring(2, 15)
export const isAsyncFunction = (fn: (...args: any[]) => any | Promise<any>) => typeof fn === "function" && fn.constructor.name === "AsyncFunction"
| 25.673611 | 146 | 0.61861 | 121 | 9 | 0 | 10 | 15 | 0 | 4 | 13 | 6 | 1 | 22 | 11.888889 | 1,280 | 0.014844 | 0.011719 | 0 | 0.000781 | 0.017188 | 0.382353 | 0.176471 | 0.236459 | export type AlmostAnything = string | number | symbol | Record<any, any> | Array<any> | Object
export /* Example usages of 'isObject' are shown below:
isObject(target) && isObject(source);
isObject(source[key]);
isObject(thing);
isObject(a) && isObject(b);
*/
function isObject(item): item is Object {
return item && item !== null && typeof item === "object" && !Array.isArray(item)
}
export /* Example usages of 'deepMerge' are shown below:
output[key] = deepMerge(target[key], source[key]);
*/
function deepMerge<Thing extends Object>(target, source) {
let output = Object.assign({}, target)
if ((isObject(target) && isObject(source)) || (Array.isArray(target) && Array.isArray(source))) {
for (const key in source) {
if (isObject(source[key])) {
if (!(key in target)) {
Object.assign(output, { [key]: source[key] })
} else {
output[key] = deepMerge(target[key], source[key])
}
} else {
Object.assign(output, { [key]: source[key] })
}
}
}
// if it was originally an array, return an array
if (Array.isArray(target) && Array.isArray(source)) {
return Object.values(output) as any as Thing
}
return output
}
// a deep clone of anything
export /* Example usages of 'deepClone' are shown below:
cloned[key] = deepClone(thing[key]);
*/
function deepClone<Type = AlmostAnything>(thing) {
if (thing instanceof Date) {
return new Date(thing.getTime()) as any as Type
}
if (thing instanceof RegExp) {
return new RegExp(thing) as any as Type
}
// must be an object
if (isObject(thing)) {
const cloned = Object.create(thing as Object)
for (const key in thing) {
if ((thing as Object).hasOwnProperty(key)) {
cloned[key] = deepClone(thing[key])
}
}
if (Array.isArray(thing)) {
return Object.values(cloned) as any as Type
}
// if it was originally an array, return an array
if (Array.isArray(thing)) {
return Object.values(cloned) as any as Type
}
// if it was originally an object, return an object
return cloned
}
return thing
}
export /* Example usages of 'isEqual' are shown below:
!isEqual(a[i], b[i]);
!isEqual(a[key], b[key]);
*/
function isEqual(a, b) {
if (a === b) {
return true
}
if (a instanceof Date && b instanceof Date) {
return a.getTime() === b.getTime()
}
if (a instanceof RegExp && b instanceof RegExp) {
return a.toString() === b.toString()
}
if (Array.isArray(a) && Array.isArray(b)) {
if (a.length !== b.length) {
return false
}
for (let i = 0; i < a.length; i++) {
if (!isEqual(a[i], b[i])) {
return false
}
}
return true
}
if (isObject(a) && isObject(b)) {
const aKeys = Object.keys(a)
const bKeys = Object.keys(b)
if (aKeys.length !== bKeys.length) {
return false
}
for (const key of aKeys) {
if (!isEqual(a[key], b[key])) {
return false
}
}
return true
}
return false
}
export const convertToString = (input) =>
typeof input === "object" ? JSON.stringify(input) : typeof input === "function" ? input.toString() : String(input)
export const hash = function (input) {
/* Simple hash function. */
let a = 1,
c = 0,
h,
o
if (input) {
a = 0
/*jshint plusplus:false bitwise:false*/
for (h = input.length - 1; h >= 0; h--) {
o = input.charCodeAt(h)
a = ((a << 6) & 268435455) + o + (o << 14)
c = a & 266338304
a = c !== 0 ? a ^ (c >> 21) : a
}
}
return String(a)
}
export const convertStringToType = (inp) => {
try {
// try to parse it as JSON (array or object)
return JSON.parse(inp)
} catch (e) {
// if that fails, try...
// ...as a number
const num = Number(inp)
if (!isNaN(num)) {
return num
}
// ...as a boolean
if (inp === "true") {
return true
}
if (inp === "false") {
return false
}
// ...as a string
return inp
}
}
export const genUID = () => Math.random().toString(36).substring(2, 15) + Math.random().toString(36).substring(2, 15)
export const isAsyncFunction = (fn) => typeof fn === "function" && fn.constructor.name === "AsyncFunction"
|
fcf89e7f430f91244271b24bde6681c58f4579cd | 1,533 | ts | TypeScript | src/api/graphql/schedule.graphql.ts | joker-crypto/PUP-Facuty-Workload | 3840e2833c5f50fbdbf9b13ae6214fbb81e8c157 | [
"MIT"
] | null | null | null | src/api/graphql/schedule.graphql.ts | joker-crypto/PUP-Facuty-Workload | 3840e2833c5f50fbdbf9b13ae6214fbb81e8c157 | [
"MIT"
] | null | null | null | src/api/graphql/schedule.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 listScheduleGQL = () => {
return `
query {
schedules(where: { status: "FOR_REVIEW" }) {
id
customer {
customerType
personal_info {
fullName
}
}
agent {
personalInfo {
fullName
}
}
comment
scheduleDate
created_at
status
}
}
`;
};
export const assignAgentGQL = (data: any) => {
return `
mutation {
updateSchedule(
input: {
where: { id: ${data.id} }
data: { agent: ${data.agent}, comment: "${data.comment || ''}" }
}
) {
schedule {
id
scheduleDate
agent {
personalInfo {
lastName
email
}
}
customer {
customerType
personal_info {
lastName
fullName
email
}
}
}
}
}
`;
};
export const approvedScheduleGQL = (id: any) => {
return `
mutation {
updateSchedule(input: { where: { id: ${id} }, data: { status: APPROVED } }) {
schedule {
id
}
}
}
`;
};
export const archivedScheduleGQL = (data: any) => {
return `
mutation {
updateSchedule(input: { where: { id: ${data.id} }, data: { status: CANCELLED } }) {
schedule {
id
}
}
}
`;
};
| 18.46988 | 89 | 0.448141 | 77 | 4 | 0 | 3 | 4 | 0 | 0 | 3 | 0 | 0 | 0 | 17.25 | 364 | 0.019231 | 0.010989 | 0 | 0 | 0 | 0.272727 | 0 | 0.246646 | /* eslint-disable @typescript-eslint/no-explicit-any */
/* eslint-disable import/prefer-default-export */
export const listScheduleGQL = () => {
return `
query {
schedules(where: { status: "FOR_REVIEW" }) {
id
customer {
customerType
personal_info {
fullName
}
}
agent {
personalInfo {
fullName
}
}
comment
scheduleDate
created_at
status
}
}
`;
};
export const assignAgentGQL = (data) => {
return `
mutation {
updateSchedule(
input: {
where: { id: ${data.id} }
data: { agent: ${data.agent}, comment: "${data.comment || ''}" }
}
) {
schedule {
id
scheduleDate
agent {
personalInfo {
lastName
email
}
}
customer {
customerType
personal_info {
lastName
fullName
email
}
}
}
}
}
`;
};
export const approvedScheduleGQL = (id) => {
return `
mutation {
updateSchedule(input: { where: { id: ${id} }, data: { status: APPROVED } }) {
schedule {
id
}
}
}
`;
};
export const archivedScheduleGQL = (data) => {
return `
mutation {
updateSchedule(input: { where: { id: ${data.id} }, data: { status: CANCELLED } }) {
schedule {
id
}
}
}
`;
};
|
932e51cd21f1d2efd6a4f09d6a844736f3d3340b | 4,082 | ts | TypeScript | src/videodownlinkbandwidthpolicy/VideoPriorityBasedPolicyConfig.ts | MasahiroHanawa/amazon-chime-sdk-js | ebb4b85d66a8f9d4db62213829ba5e3375f984d6 | [
"Apache-2.0"
] | 1 | 2022-03-01T10:59:52.000Z | 2022-03-01T10:59:52.000Z | src/videodownlinkbandwidthpolicy/VideoPriorityBasedPolicyConfig.ts | mesahni1/amazon-chime-sdk-js | a9148707019c4932b56cf5b1a86f85687bbbf382 | [
"Apache-2.0"
] | null | null | null | src/videodownlinkbandwidthpolicy/VideoPriorityBasedPolicyConfig.ts | mesahni1/amazon-chime-sdk-js | a9148707019c4932b56cf5b1a86f85687bbbf382 | [
"Apache-2.0"
] | null | null | null | // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
/** @internal */
const enum NetworkEvent {
Stable,
Decrease,
Increase,
}
/**
* [[VideoPriorityBasedPolicyConfig]] contains the network issue response delay and network issue recovery delay.
*/
export default class VideoPriorityBasedPolicyConfig {
private static readonly MINIMUM_DELAY_MS = 2000;
private static readonly MAXIMUM_DELAY_MS = 8000;
// presets
static readonly Default = new VideoPriorityBasedPolicyConfig(0, 0);
static readonly UnstableNetworkPreset = new VideoPriorityBasedPolicyConfig(0, 1);
static readonly StableNetworkPreset = new VideoPriorityBasedPolicyConfig(1, 0);
private currentNetworkEvent: NetworkEvent = NetworkEvent.Stable;
private bandwidthDecreaseTimestamp: number = 0; // the last time bandwidth decreases
private referenceBitrate: number = 0;
/** Initializes a [[VideoPriorityBasedPolicyConfig]] with the network event delays.
*
* @param networkIssueResponseDelayFactor Delays before reducing subscribed video bitrate. Input should be a value between 0 and 1.
* @param networkIssueRecoveryDelayFactor Delays before starting to increase bitrates after a network event and
* delays between increasing video bitrates on each individual stream. Input should be a value between 0 and 1.
*/
constructor(
public networkIssueResponseDelayFactor: number = 0,
public networkIssueRecoveryDelayFactor: number = 0
) {
if (networkIssueResponseDelayFactor < 0) {
networkIssueResponseDelayFactor = 0;
} else if (networkIssueResponseDelayFactor > 1) {
networkIssueResponseDelayFactor = 1;
}
this.networkIssueResponseDelayFactor = networkIssueResponseDelayFactor;
if (networkIssueRecoveryDelayFactor < 0) {
networkIssueRecoveryDelayFactor = 0;
} else if (networkIssueRecoveryDelayFactor > 1) {
networkIssueRecoveryDelayFactor = 1;
}
this.networkIssueRecoveryDelayFactor = networkIssueRecoveryDelayFactor;
}
// determine if subscribe is allowed based on network issue/recovery delays
allowSubscribe(numberOfParticipants: number, currentEstimated: number): boolean {
let timeBeforeAllowSubscribeMs = 0;
const previousNetworkEvent = this.currentNetworkEvent;
if (currentEstimated > this.referenceBitrate) {
// if bw increases
this.currentNetworkEvent = NetworkEvent.Increase;
this.referenceBitrate = currentEstimated;
return true;
} else if (currentEstimated < this.referenceBitrate) {
// if bw decreases, we use response delay
this.currentNetworkEvent = NetworkEvent.Decrease;
timeBeforeAllowSubscribeMs = this.getSubscribeDelay(
this.currentNetworkEvent,
numberOfParticipants
);
if (previousNetworkEvent !== NetworkEvent.Decrease) {
this.bandwidthDecreaseTimestamp = Date.now();
} else if (Date.now() - this.bandwidthDecreaseTimestamp > timeBeforeAllowSubscribeMs) {
this.referenceBitrate = currentEstimated;
return true;
}
return false;
} else {
this.currentNetworkEvent = NetworkEvent.Stable;
return false;
}
}
// convert network event delay factor to actual delay in ms
private getSubscribeDelay(event: NetworkEvent, numberOfParticipants: number): number {
// left and right boundary of the delay
let subscribeDelay = VideoPriorityBasedPolicyConfig.MINIMUM_DELAY_MS;
const range =
VideoPriorityBasedPolicyConfig.MAXIMUM_DELAY_MS -
VideoPriorityBasedPolicyConfig.MINIMUM_DELAY_MS;
const responseFactor = this.networkIssueResponseDelayFactor;
switch (event) {
case NetworkEvent.Decrease:
// we include number of participants here since bigger size of the meeting will generate higher bitrate
subscribeDelay += range * responseFactor * (1 + numberOfParticipants / 10);
subscribeDelay = Math.min(VideoPriorityBasedPolicyConfig.MAXIMUM_DELAY_MS, subscribeDelay);
break;
}
return subscribeDelay;
}
}
| 39.25 | 133 | 0.745468 | 71 | 3 | 0 | 6 | 5 | 8 | 1 | 0 | 9 | 1 | 0 | 15.666667 | 936 | 0.009615 | 0.005342 | 0.008547 | 0.001068 | 0 | 0 | 0.409091 | 0.211467 | // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
/** @internal */
const enum NetworkEvent {
Stable,
Decrease,
Increase,
}
/**
* [[VideoPriorityBasedPolicyConfig]] contains the network issue response delay and network issue recovery delay.
*/
export default class VideoPriorityBasedPolicyConfig {
private static readonly MINIMUM_DELAY_MS = 2000;
private static readonly MAXIMUM_DELAY_MS = 8000;
// presets
static readonly Default = new VideoPriorityBasedPolicyConfig(0, 0);
static readonly UnstableNetworkPreset = new VideoPriorityBasedPolicyConfig(0, 1);
static readonly StableNetworkPreset = new VideoPriorityBasedPolicyConfig(1, 0);
private currentNetworkEvent = NetworkEvent.Stable;
private bandwidthDecreaseTimestamp = 0; // the last time bandwidth decreases
private referenceBitrate = 0;
/** Initializes a [[VideoPriorityBasedPolicyConfig]] with the network event delays.
*
* @param networkIssueResponseDelayFactor Delays before reducing subscribed video bitrate. Input should be a value between 0 and 1.
* @param networkIssueRecoveryDelayFactor Delays before starting to increase bitrates after a network event and
* delays between increasing video bitrates on each individual stream. Input should be a value between 0 and 1.
*/
constructor(
public networkIssueResponseDelayFactor = 0,
public networkIssueRecoveryDelayFactor = 0
) {
if (networkIssueResponseDelayFactor < 0) {
networkIssueResponseDelayFactor = 0;
} else if (networkIssueResponseDelayFactor > 1) {
networkIssueResponseDelayFactor = 1;
}
this.networkIssueResponseDelayFactor = networkIssueResponseDelayFactor;
if (networkIssueRecoveryDelayFactor < 0) {
networkIssueRecoveryDelayFactor = 0;
} else if (networkIssueRecoveryDelayFactor > 1) {
networkIssueRecoveryDelayFactor = 1;
}
this.networkIssueRecoveryDelayFactor = networkIssueRecoveryDelayFactor;
}
// determine if subscribe is allowed based on network issue/recovery delays
allowSubscribe(numberOfParticipants, currentEstimated) {
let timeBeforeAllowSubscribeMs = 0;
const previousNetworkEvent = this.currentNetworkEvent;
if (currentEstimated > this.referenceBitrate) {
// if bw increases
this.currentNetworkEvent = NetworkEvent.Increase;
this.referenceBitrate = currentEstimated;
return true;
} else if (currentEstimated < this.referenceBitrate) {
// if bw decreases, we use response delay
this.currentNetworkEvent = NetworkEvent.Decrease;
timeBeforeAllowSubscribeMs = this.getSubscribeDelay(
this.currentNetworkEvent,
numberOfParticipants
);
if (previousNetworkEvent !== NetworkEvent.Decrease) {
this.bandwidthDecreaseTimestamp = Date.now();
} else if (Date.now() - this.bandwidthDecreaseTimestamp > timeBeforeAllowSubscribeMs) {
this.referenceBitrate = currentEstimated;
return true;
}
return false;
} else {
this.currentNetworkEvent = NetworkEvent.Stable;
return false;
}
}
// convert network event delay factor to actual delay in ms
private getSubscribeDelay(event, numberOfParticipants) {
// left and right boundary of the delay
let subscribeDelay = VideoPriorityBasedPolicyConfig.MINIMUM_DELAY_MS;
const range =
VideoPriorityBasedPolicyConfig.MAXIMUM_DELAY_MS -
VideoPriorityBasedPolicyConfig.MINIMUM_DELAY_MS;
const responseFactor = this.networkIssueResponseDelayFactor;
switch (event) {
case NetworkEvent.Decrease:
// we include number of participants here since bigger size of the meeting will generate higher bitrate
subscribeDelay += range * responseFactor * (1 + numberOfParticipants / 10);
subscribeDelay = Math.min(VideoPriorityBasedPolicyConfig.MAXIMUM_DELAY_MS, subscribeDelay);
break;
}
return subscribeDelay;
}
}
|
93ad0b082dc15c2a5290772654207b031b7d41ea | 3,579 | ts | TypeScript | problemset/valid-number/index.ts | OUDUIDUI/leet-code | 50e61ce16d1c419ccefc075ae9ead721cdd1cdbb | [
"MIT"
] | 6 | 2022-01-17T03:19:56.000Z | 2022-01-17T05:45:39.000Z | problemset/valid-number/index.ts | OUDUIDUI/leet-code | 50e61ce16d1c419ccefc075ae9ead721cdd1cdbb | [
"MIT"
] | null | null | null | problemset/valid-number/index.ts | OUDUIDUI/leet-code | 50e61ce16d1c419ccefc075ae9ead721cdd1cdbb | [
"MIT"
] | null | null | null | /**
* 正则
* @desc 时间复杂度 O(N) 空间复杂度 O(1)
* @param s {string}
* @return {boolean}
*/
export function isNumber(s: string): boolean {
const regExp = /^[+-]?((\d+(\.\d*)?)|\.\d+)([eE][-+]?\d+)?$/
return regExp.test(s)
}
/**
* 确定有限状态自动机
* @desc 时间复杂度 O(N) 空间复杂度 O(1)
* @param s {string}
* @return {boolean}
*/
export function isNumber2(s: string): boolean {
enum State {
STATE_INITIAL = 'STATE_INITIAL', // 初始状态
STATE_INT_SIGN = 'STATE_INT_SIGN', // 符号位
STATE_INTEGER = 'STATE_INTEGER', // 整数部分
STATE_POINT = 'STATE_POINT', // 左侧有整数的小数点
STATE_POINT_WITHOUT_INT = 'STATE_POINT_WITHOUT_INT', // 左侧无整数的小数点
STATE_FRACTION = 'STATE_FRACTION', // 小数部分
STATE_EXP = 'STATE_EXP', // 字符 e
STATE_EXP_SIGN = 'STATE_EXP_SIGN', // 指数部分的符号位
STATE_EXP_NUMBER = 'STATE_EXP_NUMBER', // 指数部分的整数部分
}
enum CharType {
CHAR_NUMBER = 'CHAR_NUMBER', // 数值
CHAR_EXP = 'CHAR_EXP', // e 指数
CHAR_POINT = 'CHAR_POINT', // 小数点
CHAR_SIGN = 'CHAR_SIGN', // 正负符号
CHAR_ILLEGAL = 'CHAR_ILLEGAL', // 特殊状态
}
// 判断单个字符串类型
const toCharType = (ch: string) => {
if (!isNaN(Number(ch)))
return CharType.CHAR_NUMBER
else if (ch.toLowerCase() === 'e')
return CharType.CHAR_EXP
else if (ch === '.')
return CharType.CHAR_POINT
else if (ch === '+' || ch === '-')
return CharType.CHAR_SIGN
else
return CharType.CHAR_ILLEGAL
}
const initialMap = new Map<CharType, State>([
[CharType.CHAR_NUMBER, State.STATE_INTEGER],
[CharType.CHAR_POINT, State.STATE_POINT_WITHOUT_INT],
[CharType.CHAR_SIGN, State.STATE_INT_SIGN],
])
const intSignMap = new Map<CharType, State>([
[CharType.CHAR_NUMBER, State.STATE_INTEGER],
[CharType.CHAR_POINT, State.STATE_POINT_WITHOUT_INT],
])
const integerMap = new Map<CharType, State>([
[CharType.CHAR_NUMBER, State.STATE_INTEGER],
[CharType.CHAR_EXP, State.STATE_EXP],
[CharType.CHAR_POINT, State.STATE_POINT],
])
const pointMap = new Map<CharType, State>([
[CharType.CHAR_NUMBER, State.STATE_FRACTION],
[CharType.CHAR_EXP, State.STATE_EXP],
])
const pointWithoutIntMap = new Map<CharType, State>([
[CharType.CHAR_NUMBER, State.STATE_FRACTION],
])
const fractionMap = new Map<CharType, State>([
[CharType.CHAR_NUMBER, State.STATE_FRACTION],
[CharType.CHAR_EXP, State.STATE_EXP],
])
const expMap = new Map<CharType, State>([
[CharType.CHAR_NUMBER, State.STATE_EXP_NUMBER],
[CharType.CHAR_SIGN, State.STATE_EXP_SIGN],
])
const expSignMap = new Map<CharType, State>([
[CharType.CHAR_NUMBER, State.STATE_EXP_NUMBER],
])
const expNumberMap = new Map<CharType, State>([
[CharType.CHAR_NUMBER, State.STATE_EXP_NUMBER],
])
const transfer = new Map<State, Map<CharType, State>>([
[State.STATE_INITIAL, initialMap],
[State.STATE_INT_SIGN, intSignMap],
[State.STATE_INTEGER, integerMap],
[State.STATE_POINT, pointMap],
[State.STATE_POINT_WITHOUT_INT, pointWithoutIntMap],
[State.STATE_FRACTION, fractionMap],
[State.STATE_EXP, expMap],
[State.STATE_EXP_SIGN, expSignMap],
[State.STATE_EXP_NUMBER, expNumberMap],
])
const length = s.length
let state: State = State.STATE_INITIAL
for (let i = 0; i < length; i++) {
const type = toCharType(s[i])
const map: Map<CharType, State> = transfer.get(state)!
if (map.has(type))
state = map.get(type)!
else
return false
}
return [
State.STATE_INTEGER,
State.STATE_POINT,
State.STATE_FRACTION,
State.STATE_EXP_NUMBER,
].includes(state)
}
| 30.07563 | 69 | 0.661917 | 98 | 3 | 0 | 3 | 17 | 0 | 1 | 0 | 5 | 0 | 0 | 34.666667 | 1,213 | 0.004946 | 0.014015 | 0 | 0 | 0 | 0 | 0.217391 | 0.227492 | /**
* 正则
* @desc 时间复杂度 O(N) 空间复杂度 O(1)
* @param s {string}
* @return {boolean}
*/
export function isNumber(s) {
const regExp = /^[+-]?((\d+(\.\d*)?)|\.\d+)([eE][-+]?\d+)?$/
return regExp.test(s)
}
/**
* 确定有限状态自动机
* @desc 时间复杂度 O(N) 空间复杂度 O(1)
* @param s {string}
* @return {boolean}
*/
export function isNumber2(s) {
enum State {
STATE_INITIAL = 'STATE_INITIAL', // 初始状态
STATE_INT_SIGN = 'STATE_INT_SIGN', // 符号位
STATE_INTEGER = 'STATE_INTEGER', // 整数部分
STATE_POINT = 'STATE_POINT', // 左侧有整数的小数点
STATE_POINT_WITHOUT_INT = 'STATE_POINT_WITHOUT_INT', // 左侧无整数的小数点
STATE_FRACTION = 'STATE_FRACTION', // 小数部分
STATE_EXP = 'STATE_EXP', // 字符 e
STATE_EXP_SIGN = 'STATE_EXP_SIGN', // 指数部分的符号位
STATE_EXP_NUMBER = 'STATE_EXP_NUMBER', // 指数部分的整数部分
}
enum CharType {
CHAR_NUMBER = 'CHAR_NUMBER', // 数值
CHAR_EXP = 'CHAR_EXP', // e 指数
CHAR_POINT = 'CHAR_POINT', // 小数点
CHAR_SIGN = 'CHAR_SIGN', // 正负符号
CHAR_ILLEGAL = 'CHAR_ILLEGAL', // 特殊状态
}
// 判断单个字符串类型
/* Example usages of 'toCharType' are shown below:
toCharType(s[i]);
*/
const toCharType = (ch) => {
if (!isNaN(Number(ch)))
return CharType.CHAR_NUMBER
else if (ch.toLowerCase() === 'e')
return CharType.CHAR_EXP
else if (ch === '.')
return CharType.CHAR_POINT
else if (ch === '+' || ch === '-')
return CharType.CHAR_SIGN
else
return CharType.CHAR_ILLEGAL
}
const initialMap = new Map<CharType, State>([
[CharType.CHAR_NUMBER, State.STATE_INTEGER],
[CharType.CHAR_POINT, State.STATE_POINT_WITHOUT_INT],
[CharType.CHAR_SIGN, State.STATE_INT_SIGN],
])
const intSignMap = new Map<CharType, State>([
[CharType.CHAR_NUMBER, State.STATE_INTEGER],
[CharType.CHAR_POINT, State.STATE_POINT_WITHOUT_INT],
])
const integerMap = new Map<CharType, State>([
[CharType.CHAR_NUMBER, State.STATE_INTEGER],
[CharType.CHAR_EXP, State.STATE_EXP],
[CharType.CHAR_POINT, State.STATE_POINT],
])
const pointMap = new Map<CharType, State>([
[CharType.CHAR_NUMBER, State.STATE_FRACTION],
[CharType.CHAR_EXP, State.STATE_EXP],
])
const pointWithoutIntMap = new Map<CharType, State>([
[CharType.CHAR_NUMBER, State.STATE_FRACTION],
])
const fractionMap = new Map<CharType, State>([
[CharType.CHAR_NUMBER, State.STATE_FRACTION],
[CharType.CHAR_EXP, State.STATE_EXP],
])
const expMap = new Map<CharType, State>([
[CharType.CHAR_NUMBER, State.STATE_EXP_NUMBER],
[CharType.CHAR_SIGN, State.STATE_EXP_SIGN],
])
const expSignMap = new Map<CharType, State>([
[CharType.CHAR_NUMBER, State.STATE_EXP_NUMBER],
])
const expNumberMap = new Map<CharType, State>([
[CharType.CHAR_NUMBER, State.STATE_EXP_NUMBER],
])
const transfer = new Map<State, Map<CharType, State>>([
[State.STATE_INITIAL, initialMap],
[State.STATE_INT_SIGN, intSignMap],
[State.STATE_INTEGER, integerMap],
[State.STATE_POINT, pointMap],
[State.STATE_POINT_WITHOUT_INT, pointWithoutIntMap],
[State.STATE_FRACTION, fractionMap],
[State.STATE_EXP, expMap],
[State.STATE_EXP_SIGN, expSignMap],
[State.STATE_EXP_NUMBER, expNumberMap],
])
const length = s.length
let state = State.STATE_INITIAL
for (let i = 0; i < length; i++) {
const type = toCharType(s[i])
const map = transfer.get(state)!
if (map.has(type))
state = map.get(type)!
else
return false
}
return [
State.STATE_INTEGER,
State.STATE_POINT,
State.STATE_FRACTION,
State.STATE_EXP_NUMBER,
].includes(state)
}
|
93e4c92cb6fa4c1a76b92200a9db5527df477966 | 8,442 | ts | TypeScript | packages/mona-commands/mona-build/src/utils/md5.ts | xwchris/mona | 2933e5ab7a64c8be8e7fdf5f212cd6f9b00be57e | [
"MIT"
] | null | null | null | packages/mona-commands/mona-build/src/utils/md5.ts | xwchris/mona | 2933e5ab7a64c8be8e7fdf5f212cd6f9b00be57e | [
"MIT"
] | null | null | null | packages/mona-commands/mona-build/src/utils/md5.ts | xwchris/mona | 2933e5ab7a64c8be8e7fdf5f212cd6f9b00be57e | [
"MIT"
] | 1 | 2022-01-05T03:43:01.000Z | 2022-01-05T03:43:01.000Z |
/**
* Add integers, wrapping at 2^32.
* This uses 16-bit operations internally to work around bugs in interpreters.
*
* @param {number} x First integer
* @param {number} y Second integer
* @returns {number} Sum
*/
function safeAdd(x: number, y: number) {
const lsw = (x & 0xffff) + (y & 0xffff);
const msw = (x >> 16) + (y >> 16) + (lsw >> 16);
return (msw << 16) | (lsw & 0xffff);
}
/**
* Bitwise rotate a 32-bit number to the left.
*
* @param {number} num 32-bit number
* @param {number} cnt Rotation count
* @returns {number} Rotated number
*/
function bitRotateLeft(num: number, cnt: number) {
return (num << cnt) | (num >>> (32 - cnt));
}
/**
* Basic operation the algorithm uses.
*
* @param {number} q q
* @param {number} a a
* @param {number} b b
* @param {number} x x
* @param {number} s s
* @param {number} t t
* @returns {number} Result
*/
function md5cmn(q: number, a: any, b: any, x: any, s: any, t: any) {
return safeAdd(bitRotateLeft(safeAdd(safeAdd(a, q), safeAdd(x, t)), s), b);
}
/**
* Basic operation the algorithm uses.
*
* @param {number} a a
* @param {number} b b
* @param {number} c c
* @param {number} d d
* @param {number} x x
* @param {number} s s
* @param {number} t t
* @returns {number} Result
*/
function md5ff(a: number, b: number, c: number, d: number, x: any, s: number, t: number) {
return md5cmn((b & c) | (~b & d), a, b, x, s, t);
}
/**
* Basic operation the algorithm uses.
*
* @param {number} a a
* @param {number} b b
* @param {number} c c
* @param {number} d d
* @param {number} x x
* @param {number} s s
* @param {number} t t
* @returns {number} Result
*/
function md5gg(a: number, b: number, c: number, d: number, x: any, s: number, t: number) {
return md5cmn((b & d) | (c & ~d), a, b, x, s, t);
}
/**
* Basic operation the algorithm uses.
*
* @param {number} a a
* @param {number} b b
* @param {number} c c
* @param {number} d d
* @param {number} x x
* @param {number} s s
* @param {number} t t
* @returns {number} Result
*/
function md5hh(a: number, b: number, c: number, d: number, x: any, s: number, t: number) {
return md5cmn(b ^ c ^ d, a, b, x, s, t);
}
/**
* Basic operation the algorithm uses.
*
* @param {number} a a
* @param {number} b b
* @param {number} c c
* @param {number} d d
* @param {number} x x
* @param {number} s s
* @param {number} t t
* @returns {number} Result
*/
function md5ii(a: number, b: number, c: number, d: number, x: any, s: number, t: number) {
return md5cmn(c ^ (b | ~d), a, b, x, s, t);
}
/**
* Calculate the MD5 of an array of little-endian words, and a bit length.
*
* @param {Array} x Array of little-endian words
* @param {number} len Bit length
* @returns {Array<number>} MD5 Array
*/
function binlMD5(x: any, len: number) {
/* append padding */
x[len >> 5] |= 0x80 << len % 32;
x[(((len + 64) >>> 9) << 4) + 14] = len;
let i, olda, oldb, oldc, oldd;
let a = 1732584193;
let b = -271733879;
let c = -1732584194;
let d = 271733878;
for (i = 0; i < x.length; i += 16) {
olda = a;
oldb = b;
oldc = c;
oldd = d;
a = md5ff(a, b, c, d, x[i], 7, -680876936);
d = md5ff(d, a, b, c, x[i + 1], 12, -389564586);
c = md5ff(c, d, a, b, x[i + 2], 17, 606105819);
b = md5ff(b, c, d, a, x[i + 3], 22, -1044525330);
a = md5ff(a, b, c, d, x[i + 4], 7, -176418897);
d = md5ff(d, a, b, c, x[i + 5], 12, 1200080426);
c = md5ff(c, d, a, b, x[i + 6], 17, -1473231341);
b = md5ff(b, c, d, a, x[i + 7], 22, -45705983);
a = md5ff(a, b, c, d, x[i + 8], 7, 1770035416);
d = md5ff(d, a, b, c, x[i + 9], 12, -1958414417);
c = md5ff(c, d, a, b, x[i + 10], 17, -42063);
b = md5ff(b, c, d, a, x[i + 11], 22, -1990404162);
a = md5ff(a, b, c, d, x[i + 12], 7, 1804603682);
d = md5ff(d, a, b, c, x[i + 13], 12, -40341101);
c = md5ff(c, d, a, b, x[i + 14], 17, -1502002290);
b = md5ff(b, c, d, a, x[i + 15], 22, 1236535329);
a = md5gg(a, b, c, d, x[i + 1], 5, -165796510);
d = md5gg(d, a, b, c, x[i + 6], 9, -1069501632);
c = md5gg(c, d, a, b, x[i + 11], 14, 643717713);
b = md5gg(b, c, d, a, x[i], 20, -373897302);
a = md5gg(a, b, c, d, x[i + 5], 5, -701558691);
d = md5gg(d, a, b, c, x[i + 10], 9, 38016083);
c = md5gg(c, d, a, b, x[i + 15], 14, -660478335);
b = md5gg(b, c, d, a, x[i + 4], 20, -405537848);
a = md5gg(a, b, c, d, x[i + 9], 5, 568446438);
d = md5gg(d, a, b, c, x[i + 14], 9, -1019803690);
c = md5gg(c, d, a, b, x[i + 3], 14, -187363961);
b = md5gg(b, c, d, a, x[i + 8], 20, 1163531501);
a = md5gg(a, b, c, d, x[i + 13], 5, -1444681467);
d = md5gg(d, a, b, c, x[i + 2], 9, -51403784);
c = md5gg(c, d, a, b, x[i + 7], 14, 1735328473);
b = md5gg(b, c, d, a, x[i + 12], 20, -1926607734);
a = md5hh(a, b, c, d, x[i + 5], 4, -378558);
d = md5hh(d, a, b, c, x[i + 8], 11, -2022574463);
c = md5hh(c, d, a, b, x[i + 11], 16, 1839030562);
b = md5hh(b, c, d, a, x[i + 14], 23, -35309556);
a = md5hh(a, b, c, d, x[i + 1], 4, -1530992060);
d = md5hh(d, a, b, c, x[i + 4], 11, 1272893353);
c = md5hh(c, d, a, b, x[i + 7], 16, -155497632);
b = md5hh(b, c, d, a, x[i + 10], 23, -1094730640);
a = md5hh(a, b, c, d, x[i + 13], 4, 681279174);
d = md5hh(d, a, b, c, x[i], 11, -358537222);
c = md5hh(c, d, a, b, x[i + 3], 16, -722521979);
b = md5hh(b, c, d, a, x[i + 6], 23, 76029189);
a = md5hh(a, b, c, d, x[i + 9], 4, -640364487);
d = md5hh(d, a, b, c, x[i + 12], 11, -421815835);
c = md5hh(c, d, a, b, x[i + 15], 16, 530742520);
b = md5hh(b, c, d, a, x[i + 2], 23, -995338651);
a = md5ii(a, b, c, d, x[i], 6, -198630844);
d = md5ii(d, a, b, c, x[i + 7], 10, 1126891415);
c = md5ii(c, d, a, b, x[i + 14], 15, -1416354905);
b = md5ii(b, c, d, a, x[i + 5], 21, -57434055);
a = md5ii(a, b, c, d, x[i + 12], 6, 1700485571);
d = md5ii(d, a, b, c, x[i + 3], 10, -1894986606);
c = md5ii(c, d, a, b, x[i + 10], 15, -1051523);
b = md5ii(b, c, d, a, x[i + 1], 21, -2054922799);
a = md5ii(a, b, c, d, x[i + 8], 6, 1873313359);
d = md5ii(d, a, b, c, x[i + 15], 10, -30611744);
c = md5ii(c, d, a, b, x[i + 6], 15, -1560198380);
b = md5ii(b, c, d, a, x[i + 13], 21, 1309151649);
a = md5ii(a, b, c, d, x[i + 4], 6, -145523070);
d = md5ii(d, a, b, c, x[i + 11], 10, -1120210379);
c = md5ii(c, d, a, b, x[i + 2], 15, 718787259);
b = md5ii(b, c, d, a, x[i + 9], 21, -343485551);
a = safeAdd(a, olda);
b = safeAdd(b, oldb);
c = safeAdd(c, oldc);
d = safeAdd(d, oldd);
}
return [a, b, c, d];
}
/**
* Convert an array of little-endian words to a string
*
* @param {Array<number>} input MD5 Array
* @returns {string} MD5 string
*/
function binl2rstr(input: string | any[]) {
let i;
let output = '';
const length32 = input.length * 32;
for (i = 0; i < length32; i += 8) {
output += String.fromCharCode((input[i >> 5] >>> i % 32) & 0xff);
}
return output;
}
/**
* Convert a raw string to an array of little-endian words
* Characters >255 have their high-byte silently ignored.
*
* @param {string} input Raw input string
* @returns {Array<number>} Array of little-endian words
*/
function rstr2binl(input: string) {
let i;
const output: any[] = [];
output[(input.length >> 2) - 1] = undefined;
for (i = 0; i < output.length; i += 1) {
output[i] = 0;
}
const length8 = input.length * 8;
for (i = 0; i < length8; i += 8) {
output[i >> 5] |= (input.charCodeAt(i / 8) & 0xff) << i % 32;
}
return output;
}
/**
* Calculate the MD5 of a raw string
*
* @param {string} s Input string
* @returns {string} Raw MD5 string
*/
function rstrMD5(s: string) {
return binl2rstr(binlMD5(rstr2binl(s), s.length * 8));
}
function str2rstrUTF8(input: string | number | boolean) {
return unescape(encodeURIComponent(input));
}
function rawMD5(s: string) {
return rstrMD5(str2rstrUTF8(s));
}
function rstr2hex(input: string) {
const hexTab = '0123456789abcdef';
let output = '';
let x, i;
for (i = 0; i < input.length; i += 1) {
x = input.charCodeAt(i);
output += hexTab.charAt((x >>> 4) & 0x0f) + hexTab.charAt(x & 0x0f);
}
return output;
}
/**
* Encodes input string as Hex encoded string
*
* @param {string} s Input string
* @returns {string} Hex encoded string
*/
export function hexMD5(s: string) {
return rstr2hex(rawMD5(s));
}
| 30.476534 | 90 | 0.541815 | 151 | 15 | 0 | 47 | 21 | 0 | 14 | 12 | 39 | 0 | 0 | 8.066667 | 4,316 | 0.014365 | 0.004866 | 0 | 0 | 0 | 0.144578 | 0.46988 | 0.220217 |
/**
* Add integers, wrapping at 2^32.
* This uses 16-bit operations internally to work around bugs in interpreters.
*
* @param {number} x First integer
* @param {number} y Second integer
* @returns {number} Sum
*/
/* Example usages of 'safeAdd' are shown below:
safeAdd(bitRotateLeft(safeAdd(safeAdd(a, q), safeAdd(x, t)), s), b);
a = safeAdd(a, olda);
b = safeAdd(b, oldb);
c = safeAdd(c, oldc);
d = safeAdd(d, oldd);
*/
function safeAdd(x, y) {
const lsw = (x & 0xffff) + (y & 0xffff);
const msw = (x >> 16) + (y >> 16) + (lsw >> 16);
return (msw << 16) | (lsw & 0xffff);
}
/**
* Bitwise rotate a 32-bit number to the left.
*
* @param {number} num 32-bit number
* @param {number} cnt Rotation count
* @returns {number} Rotated number
*/
/* Example usages of 'bitRotateLeft' are shown below:
safeAdd(bitRotateLeft(safeAdd(safeAdd(a, q), safeAdd(x, t)), s), b);
*/
function bitRotateLeft(num, cnt) {
return (num << cnt) | (num >>> (32 - cnt));
}
/**
* Basic operation the algorithm uses.
*
* @param {number} q q
* @param {number} a a
* @param {number} b b
* @param {number} x x
* @param {number} s s
* @param {number} t t
* @returns {number} Result
*/
/* Example usages of 'md5cmn' are shown below:
md5cmn((b & c) | (~b & d), a, b, x, s, t);
md5cmn((b & d) | (c & ~d), a, b, x, s, t);
md5cmn(b ^ c ^ d, a, b, x, s, t);
md5cmn(c ^ (b | ~d), a, b, x, s, t);
*/
function md5cmn(q, a, b, x, s, t) {
return safeAdd(bitRotateLeft(safeAdd(safeAdd(a, q), safeAdd(x, t)), s), b);
}
/**
* Basic operation the algorithm uses.
*
* @param {number} a a
* @param {number} b b
* @param {number} c c
* @param {number} d d
* @param {number} x x
* @param {number} s s
* @param {number} t t
* @returns {number} Result
*/
/* Example usages of 'md5ff' are shown below:
a = md5ff(a, b, c, d, x[i], 7, -680876936);
d = md5ff(d, a, b, c, x[i + 1], 12, -389564586);
c = md5ff(c, d, a, b, x[i + 2], 17, 606105819);
b = md5ff(b, c, d, a, x[i + 3], 22, -1044525330);
a = md5ff(a, b, c, d, x[i + 4], 7, -176418897);
d = md5ff(d, a, b, c, x[i + 5], 12, 1200080426);
c = md5ff(c, d, a, b, x[i + 6], 17, -1473231341);
b = md5ff(b, c, d, a, x[i + 7], 22, -45705983);
a = md5ff(a, b, c, d, x[i + 8], 7, 1770035416);
d = md5ff(d, a, b, c, x[i + 9], 12, -1958414417);
c = md5ff(c, d, a, b, x[i + 10], 17, -42063);
b = md5ff(b, c, d, a, x[i + 11], 22, -1990404162);
a = md5ff(a, b, c, d, x[i + 12], 7, 1804603682);
d = md5ff(d, a, b, c, x[i + 13], 12, -40341101);
c = md5ff(c, d, a, b, x[i + 14], 17, -1502002290);
b = md5ff(b, c, d, a, x[i + 15], 22, 1236535329);
*/
function md5ff(a, b, c, d, x, s, t) {
return md5cmn((b & c) | (~b & d), a, b, x, s, t);
}
/**
* Basic operation the algorithm uses.
*
* @param {number} a a
* @param {number} b b
* @param {number} c c
* @param {number} d d
* @param {number} x x
* @param {number} s s
* @param {number} t t
* @returns {number} Result
*/
/* Example usages of 'md5gg' are shown below:
a = md5gg(a, b, c, d, x[i + 1], 5, -165796510);
d = md5gg(d, a, b, c, x[i + 6], 9, -1069501632);
c = md5gg(c, d, a, b, x[i + 11], 14, 643717713);
b = md5gg(b, c, d, a, x[i], 20, -373897302);
a = md5gg(a, b, c, d, x[i + 5], 5, -701558691);
d = md5gg(d, a, b, c, x[i + 10], 9, 38016083);
c = md5gg(c, d, a, b, x[i + 15], 14, -660478335);
b = md5gg(b, c, d, a, x[i + 4], 20, -405537848);
a = md5gg(a, b, c, d, x[i + 9], 5, 568446438);
d = md5gg(d, a, b, c, x[i + 14], 9, -1019803690);
c = md5gg(c, d, a, b, x[i + 3], 14, -187363961);
b = md5gg(b, c, d, a, x[i + 8], 20, 1163531501);
a = md5gg(a, b, c, d, x[i + 13], 5, -1444681467);
d = md5gg(d, a, b, c, x[i + 2], 9, -51403784);
c = md5gg(c, d, a, b, x[i + 7], 14, 1735328473);
b = md5gg(b, c, d, a, x[i + 12], 20, -1926607734);
*/
function md5gg(a, b, c, d, x, s, t) {
return md5cmn((b & d) | (c & ~d), a, b, x, s, t);
}
/**
* Basic operation the algorithm uses.
*
* @param {number} a a
* @param {number} b b
* @param {number} c c
* @param {number} d d
* @param {number} x x
* @param {number} s s
* @param {number} t t
* @returns {number} Result
*/
/* Example usages of 'md5hh' are shown below:
a = md5hh(a, b, c, d, x[i + 5], 4, -378558);
d = md5hh(d, a, b, c, x[i + 8], 11, -2022574463);
c = md5hh(c, d, a, b, x[i + 11], 16, 1839030562);
b = md5hh(b, c, d, a, x[i + 14], 23, -35309556);
a = md5hh(a, b, c, d, x[i + 1], 4, -1530992060);
d = md5hh(d, a, b, c, x[i + 4], 11, 1272893353);
c = md5hh(c, d, a, b, x[i + 7], 16, -155497632);
b = md5hh(b, c, d, a, x[i + 10], 23, -1094730640);
a = md5hh(a, b, c, d, x[i + 13], 4, 681279174);
d = md5hh(d, a, b, c, x[i], 11, -358537222);
c = md5hh(c, d, a, b, x[i + 3], 16, -722521979);
b = md5hh(b, c, d, a, x[i + 6], 23, 76029189);
a = md5hh(a, b, c, d, x[i + 9], 4, -640364487);
d = md5hh(d, a, b, c, x[i + 12], 11, -421815835);
c = md5hh(c, d, a, b, x[i + 15], 16, 530742520);
b = md5hh(b, c, d, a, x[i + 2], 23, -995338651);
*/
function md5hh(a, b, c, d, x, s, t) {
return md5cmn(b ^ c ^ d, a, b, x, s, t);
}
/**
* Basic operation the algorithm uses.
*
* @param {number} a a
* @param {number} b b
* @param {number} c c
* @param {number} d d
* @param {number} x x
* @param {number} s s
* @param {number} t t
* @returns {number} Result
*/
/* Example usages of 'md5ii' are shown below:
a = md5ii(a, b, c, d, x[i], 6, -198630844);
d = md5ii(d, a, b, c, x[i + 7], 10, 1126891415);
c = md5ii(c, d, a, b, x[i + 14], 15, -1416354905);
b = md5ii(b, c, d, a, x[i + 5], 21, -57434055);
a = md5ii(a, b, c, d, x[i + 12], 6, 1700485571);
d = md5ii(d, a, b, c, x[i + 3], 10, -1894986606);
c = md5ii(c, d, a, b, x[i + 10], 15, -1051523);
b = md5ii(b, c, d, a, x[i + 1], 21, -2054922799);
a = md5ii(a, b, c, d, x[i + 8], 6, 1873313359);
d = md5ii(d, a, b, c, x[i + 15], 10, -30611744);
c = md5ii(c, d, a, b, x[i + 6], 15, -1560198380);
b = md5ii(b, c, d, a, x[i + 13], 21, 1309151649);
a = md5ii(a, b, c, d, x[i + 4], 6, -145523070);
d = md5ii(d, a, b, c, x[i + 11], 10, -1120210379);
c = md5ii(c, d, a, b, x[i + 2], 15, 718787259);
b = md5ii(b, c, d, a, x[i + 9], 21, -343485551);
*/
function md5ii(a, b, c, d, x, s, t) {
return md5cmn(c ^ (b | ~d), a, b, x, s, t);
}
/**
* Calculate the MD5 of an array of little-endian words, and a bit length.
*
* @param {Array} x Array of little-endian words
* @param {number} len Bit length
* @returns {Array<number>} MD5 Array
*/
/* Example usages of 'binlMD5' are shown below:
binl2rstr(binlMD5(rstr2binl(s), s.length * 8));
*/
function binlMD5(x, len) {
/* append padding */
x[len >> 5] |= 0x80 << len % 32;
x[(((len + 64) >>> 9) << 4) + 14] = len;
let i, olda, oldb, oldc, oldd;
let a = 1732584193;
let b = -271733879;
let c = -1732584194;
let d = 271733878;
for (i = 0; i < x.length; i += 16) {
olda = a;
oldb = b;
oldc = c;
oldd = d;
a = md5ff(a, b, c, d, x[i], 7, -680876936);
d = md5ff(d, a, b, c, x[i + 1], 12, -389564586);
c = md5ff(c, d, a, b, x[i + 2], 17, 606105819);
b = md5ff(b, c, d, a, x[i + 3], 22, -1044525330);
a = md5ff(a, b, c, d, x[i + 4], 7, -176418897);
d = md5ff(d, a, b, c, x[i + 5], 12, 1200080426);
c = md5ff(c, d, a, b, x[i + 6], 17, -1473231341);
b = md5ff(b, c, d, a, x[i + 7], 22, -45705983);
a = md5ff(a, b, c, d, x[i + 8], 7, 1770035416);
d = md5ff(d, a, b, c, x[i + 9], 12, -1958414417);
c = md5ff(c, d, a, b, x[i + 10], 17, -42063);
b = md5ff(b, c, d, a, x[i + 11], 22, -1990404162);
a = md5ff(a, b, c, d, x[i + 12], 7, 1804603682);
d = md5ff(d, a, b, c, x[i + 13], 12, -40341101);
c = md5ff(c, d, a, b, x[i + 14], 17, -1502002290);
b = md5ff(b, c, d, a, x[i + 15], 22, 1236535329);
a = md5gg(a, b, c, d, x[i + 1], 5, -165796510);
d = md5gg(d, a, b, c, x[i + 6], 9, -1069501632);
c = md5gg(c, d, a, b, x[i + 11], 14, 643717713);
b = md5gg(b, c, d, a, x[i], 20, -373897302);
a = md5gg(a, b, c, d, x[i + 5], 5, -701558691);
d = md5gg(d, a, b, c, x[i + 10], 9, 38016083);
c = md5gg(c, d, a, b, x[i + 15], 14, -660478335);
b = md5gg(b, c, d, a, x[i + 4], 20, -405537848);
a = md5gg(a, b, c, d, x[i + 9], 5, 568446438);
d = md5gg(d, a, b, c, x[i + 14], 9, -1019803690);
c = md5gg(c, d, a, b, x[i + 3], 14, -187363961);
b = md5gg(b, c, d, a, x[i + 8], 20, 1163531501);
a = md5gg(a, b, c, d, x[i + 13], 5, -1444681467);
d = md5gg(d, a, b, c, x[i + 2], 9, -51403784);
c = md5gg(c, d, a, b, x[i + 7], 14, 1735328473);
b = md5gg(b, c, d, a, x[i + 12], 20, -1926607734);
a = md5hh(a, b, c, d, x[i + 5], 4, -378558);
d = md5hh(d, a, b, c, x[i + 8], 11, -2022574463);
c = md5hh(c, d, a, b, x[i + 11], 16, 1839030562);
b = md5hh(b, c, d, a, x[i + 14], 23, -35309556);
a = md5hh(a, b, c, d, x[i + 1], 4, -1530992060);
d = md5hh(d, a, b, c, x[i + 4], 11, 1272893353);
c = md5hh(c, d, a, b, x[i + 7], 16, -155497632);
b = md5hh(b, c, d, a, x[i + 10], 23, -1094730640);
a = md5hh(a, b, c, d, x[i + 13], 4, 681279174);
d = md5hh(d, a, b, c, x[i], 11, -358537222);
c = md5hh(c, d, a, b, x[i + 3], 16, -722521979);
b = md5hh(b, c, d, a, x[i + 6], 23, 76029189);
a = md5hh(a, b, c, d, x[i + 9], 4, -640364487);
d = md5hh(d, a, b, c, x[i + 12], 11, -421815835);
c = md5hh(c, d, a, b, x[i + 15], 16, 530742520);
b = md5hh(b, c, d, a, x[i + 2], 23, -995338651);
a = md5ii(a, b, c, d, x[i], 6, -198630844);
d = md5ii(d, a, b, c, x[i + 7], 10, 1126891415);
c = md5ii(c, d, a, b, x[i + 14], 15, -1416354905);
b = md5ii(b, c, d, a, x[i + 5], 21, -57434055);
a = md5ii(a, b, c, d, x[i + 12], 6, 1700485571);
d = md5ii(d, a, b, c, x[i + 3], 10, -1894986606);
c = md5ii(c, d, a, b, x[i + 10], 15, -1051523);
b = md5ii(b, c, d, a, x[i + 1], 21, -2054922799);
a = md5ii(a, b, c, d, x[i + 8], 6, 1873313359);
d = md5ii(d, a, b, c, x[i + 15], 10, -30611744);
c = md5ii(c, d, a, b, x[i + 6], 15, -1560198380);
b = md5ii(b, c, d, a, x[i + 13], 21, 1309151649);
a = md5ii(a, b, c, d, x[i + 4], 6, -145523070);
d = md5ii(d, a, b, c, x[i + 11], 10, -1120210379);
c = md5ii(c, d, a, b, x[i + 2], 15, 718787259);
b = md5ii(b, c, d, a, x[i + 9], 21, -343485551);
a = safeAdd(a, olda);
b = safeAdd(b, oldb);
c = safeAdd(c, oldc);
d = safeAdd(d, oldd);
}
return [a, b, c, d];
}
/**
* Convert an array of little-endian words to a string
*
* @param {Array<number>} input MD5 Array
* @returns {string} MD5 string
*/
/* Example usages of 'binl2rstr' are shown below:
binl2rstr(binlMD5(rstr2binl(s), s.length * 8));
*/
function binl2rstr(input) {
let i;
let output = '';
const length32 = input.length * 32;
for (i = 0; i < length32; i += 8) {
output += String.fromCharCode((input[i >> 5] >>> i % 32) & 0xff);
}
return output;
}
/**
* Convert a raw string to an array of little-endian words
* Characters >255 have their high-byte silently ignored.
*
* @param {string} input Raw input string
* @returns {Array<number>} Array of little-endian words
*/
/* Example usages of 'rstr2binl' are shown below:
binl2rstr(binlMD5(rstr2binl(s), s.length * 8));
*/
function rstr2binl(input) {
let i;
const output = [];
output[(input.length >> 2) - 1] = undefined;
for (i = 0; i < output.length; i += 1) {
output[i] = 0;
}
const length8 = input.length * 8;
for (i = 0; i < length8; i += 8) {
output[i >> 5] |= (input.charCodeAt(i / 8) & 0xff) << i % 32;
}
return output;
}
/**
* Calculate the MD5 of a raw string
*
* @param {string} s Input string
* @returns {string} Raw MD5 string
*/
/* Example usages of 'rstrMD5' are shown below:
rstrMD5(str2rstrUTF8(s));
*/
function rstrMD5(s) {
return binl2rstr(binlMD5(rstr2binl(s), s.length * 8));
}
/* Example usages of 'str2rstrUTF8' are shown below:
rstrMD5(str2rstrUTF8(s));
*/
function str2rstrUTF8(input) {
return unescape(encodeURIComponent(input));
}
/* Example usages of 'rawMD5' are shown below:
rstr2hex(rawMD5(s));
*/
function rawMD5(s) {
return rstrMD5(str2rstrUTF8(s));
}
/* Example usages of 'rstr2hex' are shown below:
rstr2hex(rawMD5(s));
*/
function rstr2hex(input) {
const hexTab = '0123456789abcdef';
let output = '';
let x, i;
for (i = 0; i < input.length; i += 1) {
x = input.charCodeAt(i);
output += hexTab.charAt((x >>> 4) & 0x0f) + hexTab.charAt(x & 0x0f);
}
return output;
}
/**
* Encodes input string as Hex encoded string
*
* @param {string} s Input string
* @returns {string} Hex encoded string
*/
export function hexMD5(s) {
return rstr2hex(rawMD5(s));
}
|
5f4331d71bd3a3b9feb32f1905784845f7a42a0f | 2,683 | ts | TypeScript | src/Stepper/utils.ts | lilian-han/ant-design-mini | 049dc7cf6b79d2618fd889db6ea43799c84bdcbf | [
"MIT"
] | 105 | 2022-02-15T09:01:53.000Z | 2022-03-30T08:39:56.000Z | src/Stepper/utils.ts | Alpsli/ant-design-mini | dd84b68388d2943e360a1b1ca8f4e8c8889a705e | [
"MIT"
] | 5 | 2022-02-25T09:39:02.000Z | 2022-03-29T01:54:05.000Z | src/Stepper/utils.ts | Alpsli/ant-design-mini | dd84b68388d2943e360a1b1ca8f4e8c8889a705e | [
"MIT"
] | 17 | 2022-02-15T09:12:22.000Z | 2022-03-28T09:21:23.000Z | /* eslint-disable @typescript-eslint/explicit-module-boundary-types */
/* eslint-disable @typescript-eslint/no-explicit-any */
// '1.' '1x' 'xx' '' => are not complete numbers
export function isNotCompleteNumber(num: any): boolean {
return (
isNaN(num) ||
num === '' ||
num === null ||
(num && num.toString().indexOf('.') === num.toString().length - 1)
);
}
export function toNumber(num: string, precision?: number): undefined | number {
// num.length > 16 => This is to prevent input of large numbers
const numberIsTooLarge = num && num.length > 16;
if (isNotCompleteNumber(num) || numberIsTooLarge) {
return undefined;
}
if (precision != null) {
return Math.round(+num * Math.pow(10, precision) / Math.pow(10, precision));
}
return Number(num);
}
export function getPrecision(value: any, precision?: number): number {
if (precision != null) {
return precision;
}
const valueString = String(value);
if (valueString.indexOf('e-') >= 0) {
return parseInt(valueString.slice(valueString.indexOf('e-') + 2), 10);
}
let p = 0;
if (valueString.indexOf('.') >= 0) {
p = valueString.length - valueString.indexOf('.') - 1;
}
return p;
}
// step={1.0} value={1.51}
// press +
// then value should be 2.51, rather than 2.5
// if this.props.precision is undefined
// https://github.com/react-component/input-number/issues/39
export function getMaxPrecision(
currentValue: any,
step?: number,
precision?: number,
): number {
if (precision != null) {
return precision;
}
const stepPrecision = getPrecision(step, precision);
const currentValuePrecision = getPrecision(currentValue, precision);
if (!currentValue) {
return stepPrecision;
}
return Math.max(currentValuePrecision, stepPrecision);
}
export function getPrecisionFactor(currentValue: any, precision?: number): number {
const p = getMaxPrecision(currentValue, undefined, precision);
return Math.pow(10, p);
}
export function upStep(val: any, step?: number, precision?: number): number {
const precisionFactor = getPrecisionFactor(val, precision);
const p = Math.abs(getMaxPrecision(val, step, precision));
const result = (
(precisionFactor * val + precisionFactor * (step as number)) /
precisionFactor
).toFixed(p);
return toNumber(result, precision);
}
export function downStep(val: any, step?: number, precision?: number): number {
const precisionFactor = getPrecisionFactor(val, precision);
const p = Math.abs(getMaxPrecision(val, step, precision));
const result = (
(precisionFactor * val - precisionFactor * (step as number)) /
precisionFactor
).toFixed(p);
return toNumber(result);
}
| 30.83908 | 83 | 0.682445 | 69 | 7 | 0 | 16 | 12 | 0 | 5 | 6 | 19 | 0 | 2 | 7.285714 | 740 | 0.031081 | 0.016216 | 0 | 0 | 0.002703 | 0.171429 | 0.542857 | 0.293209 | /* eslint-disable @typescript-eslint/explicit-module-boundary-types */
/* eslint-disable @typescript-eslint/no-explicit-any */
// '1.' '1x' 'xx' '' => are not complete numbers
export /* Example usages of 'isNotCompleteNumber' are shown below:
isNotCompleteNumber(num) || numberIsTooLarge;
*/
function isNotCompleteNumber(num) {
return (
isNaN(num) ||
num === '' ||
num === null ||
(num && num.toString().indexOf('.') === num.toString().length - 1)
);
}
export /* Example usages of 'toNumber' are shown below:
toNumber(result, precision);
toNumber(result);
*/
function toNumber(num, precision?) {
// num.length > 16 => This is to prevent input of large numbers
const numberIsTooLarge = num && num.length > 16;
if (isNotCompleteNumber(num) || numberIsTooLarge) {
return undefined;
}
if (precision != null) {
return Math.round(+num * Math.pow(10, precision) / Math.pow(10, precision));
}
return Number(num);
}
export /* Example usages of 'getPrecision' are shown below:
getPrecision(step, precision);
getPrecision(currentValue, precision);
*/
function getPrecision(value, precision?) {
if (precision != null) {
return precision;
}
const valueString = String(value);
if (valueString.indexOf('e-') >= 0) {
return parseInt(valueString.slice(valueString.indexOf('e-') + 2), 10);
}
let p = 0;
if (valueString.indexOf('.') >= 0) {
p = valueString.length - valueString.indexOf('.') - 1;
}
return p;
}
// step={1.0} value={1.51}
// press +
// then value should be 2.51, rather than 2.5
// if this.props.precision is undefined
// https://github.com/react-component/input-number/issues/39
export /* Example usages of 'getMaxPrecision' are shown below:
getMaxPrecision(currentValue, undefined, precision);
Math.abs(getMaxPrecision(val, step, precision));
*/
function getMaxPrecision(
currentValue,
step?,
precision?,
) {
if (precision != null) {
return precision;
}
const stepPrecision = getPrecision(step, precision);
const currentValuePrecision = getPrecision(currentValue, precision);
if (!currentValue) {
return stepPrecision;
}
return Math.max(currentValuePrecision, stepPrecision);
}
export /* Example usages of 'getPrecisionFactor' are shown below:
getPrecisionFactor(val, precision);
*/
function getPrecisionFactor(currentValue, precision?) {
const p = getMaxPrecision(currentValue, undefined, precision);
return Math.pow(10, p);
}
export function upStep(val, step?, precision?) {
const precisionFactor = getPrecisionFactor(val, precision);
const p = Math.abs(getMaxPrecision(val, step, precision));
const result = (
(precisionFactor * val + precisionFactor * (step as number)) /
precisionFactor
).toFixed(p);
return toNumber(result, precision);
}
export function downStep(val, step?, precision?) {
const precisionFactor = getPrecisionFactor(val, precision);
const p = Math.abs(getMaxPrecision(val, step, precision));
const result = (
(precisionFactor * val - precisionFactor * (step as number)) /
precisionFactor
).toFixed(p);
return toNumber(result);
}
|
5f85bcb27bbbf0d9004df93a0368e03fe1b794cd | 2,012 | ts | TypeScript | src/model/ImgParams.ts | aleksei-berezkin/code-art | b807425370e55486d177e660bb5671c892d9b3be | [
"MIT"
] | null | null | null | src/model/ImgParams.ts | aleksei-berezkin/code-art | b807425370e55486d177e660bb5671c892d9b3be | [
"MIT"
] | 1 | 2022-02-21T16:58:13.000Z | 2022-03-01T16:05:30.000Z | src/model/ImgParams.ts | aleksei-berezkin/code-art | b807425370e55486d177e660bb5671c892d9b3be | [
"MIT"
] | null | null | null | type Unit = 'rad' | '%' | 'log10' | 'log10%';
export type SliderVal = {
type: 'slider',
min: number,
val: number,
max: number,
unit?: Unit,
}
type ChoicesVal = {
type: 'choices',
val: string,
choices: string[],
}
type ColorVal = {
type: 'color',
val: string,
}
export type ImgParams = {
angle: {
x: SliderVal,
y: SliderVal,
z: SliderVal,
},
scroll: {
v: SliderVal,
h: SliderVal,
},
font: {
face: ChoicesVal,
size: SliderVal,
},
source: {
source: ChoicesVal,
},
'main color': {
scheme: ChoicesVal,
brightness: SliderVal,
},
glow: {
radius: SliderVal,
brightness: SliderVal,
recolor: SliderVal,
to: ColorVal,
},
fade: {
blur: SliderVal,
fade: SliderVal,
recolor: SliderVal,
near: ColorVal,
far: ColorVal,
},
'output image': {
ratio: ChoicesVal,
size: SliderVal,
attribution: ChoicesVal,
},
}
export type ParamGroup = keyof ImgParams;
export function getSliderLabel(sv: SliderVal, which: 'min' | 'val' | 'max') {
const u = sv.unit;
const v = sv[which];
let s;
if (u === 'rad') {
s = `${roundTo2(v / Math.PI * 180)}\u00B0`;
} else if (u === '%') {
s = `${roundTo2(v)}%`;
} else if (u === 'log10') {
s = String(roundTo2(10 ** v));
} else if (u === 'log10%') {
s = `${roundTo2(10 ** v)}%`;
} else {
s = String(roundTo2(v));
}
return s.replace(/-/, '\u2212');
}
function roundTo2(n: number) {
return Math.round(n * 100) / 100;
}
export function getSliderVal(sv: SliderVal) {
const u = sv.unit;
const v = sv.val;
if (u === 'rad') {
return v;
}
if (u === '%') {
return v / 100;
}
if (u === 'log10') {
return 10**v;
}
if (u === 'log10%') {
return 10**(v - 2);
}
return v;
}
| 19.346154 | 77 | 0.477634 | 95 | 3 | 0 | 4 | 5 | 18 | 1 | 0 | 7 | 6 | 0 | 10.333333 | 660 | 0.010606 | 0.007576 | 0.027273 | 0.009091 | 0 | 0 | 0.233333 | 0.234235 | type Unit = 'rad' | '%' | 'log10' | 'log10%';
export type SliderVal = {
type,
min,
val,
max,
unit?,
}
type ChoicesVal = {
type,
val,
choices,
}
type ColorVal = {
type,
val,
}
export type ImgParams = {
angle,
scroll,
font,
source,
'main color',
glow,
fade,
'output image',
}
export type ParamGroup = keyof ImgParams;
export function getSliderLabel(sv, which) {
const u = sv.unit;
const v = sv[which];
let s;
if (u === 'rad') {
s = `${roundTo2(v / Math.PI * 180)}\u00B0`;
} else if (u === '%') {
s = `${roundTo2(v)}%`;
} else if (u === 'log10') {
s = String(roundTo2(10 ** v));
} else if (u === 'log10%') {
s = `${roundTo2(10 ** v)}%`;
} else {
s = String(roundTo2(v));
}
return s.replace(/-/, '\u2212');
}
/* Example usages of 'roundTo2' are shown below:
roundTo2(v / Math.PI * 180);
roundTo2(v);
s = String(roundTo2(10 ** v));
roundTo2(10 ** v);
s = String(roundTo2(v));
*/
function roundTo2(n) {
return Math.round(n * 100) / 100;
}
export function getSliderVal(sv) {
const u = sv.unit;
const v = sv.val;
if (u === 'rad') {
return v;
}
if (u === '%') {
return v / 100;
}
if (u === 'log10') {
return 10**v;
}
if (u === 'log10%') {
return 10**(v - 2);
}
return v;
}
|
5fafa925db5300d7efc61fdfb4e3a78827576a98 | 1,521 | ts | TypeScript | src/utils/cluster/fileImport.ts | lk2684754/sd-cloud | 86ab38ee9cfd76ca15f15cf12932f2decaf9bbe8 | [
"Apache-2.0"
] | 9 | 2022-01-25T07:32:11.000Z | 2022-03-15T07:03:15.000Z | src/utils/cluster/fileImport.ts | lk2684754/sd-cloud | 86ab38ee9cfd76ca15f15cf12932f2decaf9bbe8 | [
"Apache-2.0"
] | 1 | 2022-03-04T09:46:34.000Z | 2022-03-07T01:31:05.000Z | src/utils/cluster/fileImport.ts | lk2684754/sd-cloud | 86ab38ee9cfd76ca15f15cf12932f2decaf9bbe8 | [
"Apache-2.0"
] | 1 | 2022-03-25T01:58:50.000Z | 2022-03-25T01:58:50.000Z | let done = false;
let queue: any[] = [];
let pending: any[] = [];
export class Channel {
constructor() {
done = false;
/** @type {T[]} */
queue = [];
/** @type {{resolve(value:IteratorResult<T, void>):void, reject(error:any):void}[]} */
pending = [];
}
[Symbol.asyncIterator]() {
return this;
}
/**
* @returns {Promise<IteratorResult<T, void>>}
*/
async next() {
// const { done, queue, pending }:any = this
if (done) {
return { done, value: undefined };
} else if (queue.length > 0) {
const value = queue[queue.length - 1];
queue.pop();
return { done, value };
} else {
return await new Promise((resolve, reject) => {
pending.unshift({ resolve, reject });
});
}
}
/**
* @param {T} value
*/
send(value: any) {
// const { done, pending, queue }:any = this
if (done) {
throw Error('Channel is closed');
} else if (pending.length) {
const promise = pending[pending.length - 1];
pending.pop();
promise.resolve({ done, value });
} else {
queue.unshift(value);
}
}
/**
* @param {Error|void} error
*/
close(error: any) {
if (done) {
throw Error('Channel is already closed');
} else {
done = true;
for (const promise of pending) {
if (error) {
promise.reject(error);
} else {
promise.resolve({ done: true, value: undefined });
}
}
pending.length = 0;
}
}
}
| 21.728571 | 90 | 0.514793 | 52 | 6 | 0 | 4 | 5 | 0 | 0 | 4 | 0 | 1 | 0 | 6.333333 | 422 | 0.023697 | 0.011848 | 0 | 0.00237 | 0 | 0.266667 | 0 | 0.263778 | let done = false;
let queue = [];
let pending = [];
export class Channel {
constructor() {
done = false;
/** @type {T[]} */
queue = [];
/** @type {{resolve(value:IteratorResult<T, void>):void, reject(error:any):void}[]} */
pending = [];
}
[Symbol.asyncIterator]() {
return this;
}
/**
* @returns {Promise<IteratorResult<T, void>>}
*/
async next() {
// const { done, queue, pending }:any = this
if (done) {
return { done, value: undefined };
} else if (queue.length > 0) {
const value = queue[queue.length - 1];
queue.pop();
return { done, value };
} else {
return await new Promise((resolve, reject) => {
pending.unshift({ resolve, reject });
});
}
}
/**
* @param {T} value
*/
send(value) {
// const { done, pending, queue }:any = this
if (done) {
throw Error('Channel is closed');
} else if (pending.length) {
const promise = pending[pending.length - 1];
pending.pop();
promise.resolve({ done, value });
} else {
queue.unshift(value);
}
}
/**
* @param {Error|void} error
*/
close(error) {
if (done) {
throw Error('Channel is already closed');
} else {
done = true;
for (const promise of pending) {
if (error) {
promise.reject(error);
} else {
promise.resolve({ done: true, value: undefined });
}
}
pending.length = 0;
}
}
}
|
5fd43f3348645e6b8a9151b5b658d4100fbf09cb | 4,907 | ts | TypeScript | packages/icon/scripts/shape2path.ts | ielgnaw/bkui-vue3 | e349dbc0dfdb521282ffb4f4110f4a2d45e804a2 | [
"MIT"
] | 8 | 2022-02-24T07:37:55.000Z | 2022-03-28T11:14:33.000Z | packages/icon/scripts/shape2path.ts | ielgnaw/bkui-vue3 | e349dbc0dfdb521282ffb4f4110f4a2d45e804a2 | [
"MIT"
] | 5 | 2022-03-25T02:30:01.000Z | 2022-03-29T11:37:29.000Z | packages/icon/scripts/shape2path.ts | ielgnaw/bkui-vue3 | e349dbc0dfdb521282ffb4f4110f4a2d45e804a2 | [
"MIT"
] | 26 | 2022-02-24T02:26:58.000Z | 2022-03-30T08:12:44.000Z | /*
* Tencent is pleased to support the open source community by making
* 蓝鲸智云PaaS平台社区版 (BlueKing PaaS Community Edition) available.
*
* Copyright (C) 2021 THL A29 Limited, a Tencent company. All rights reserved.
*
* 蓝鲸智云PaaS平台社区版 (BlueKing PaaS Community Edition) is licensed under the MIT License.
*
* License for 蓝鲸智云PaaS平台社区版 (BlueKing PaaS Community Edition):
*
* ---------------------------------------------------
* 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.
*/
interface IRectAttrs {
width: number | string;
height: number | string;
x: number | string;
y: number | string;
rx: number | string;
ry: number | string;
}
interface ICircleAttrs {
cx: number | string;
cy: number | string;
rx: number | string;
ry: number | string;
r: number | string;
}
interface ILineAttrs {
x1: number | string;
y1: number | string;
x2: number | string;
y2: number | string;
}
interface IPolyAttrs {
points: string;
}
const chunkArray = (arr: string[], size = 2) => {
const results = [];
while (arr.length) {
results.push(arr.splice(0, size));
}
return results;
};
const calcValue = (val: string, base: number) => (/%$/.test(val) ? (Number(val.replace('%', '')) * 100) / base : +val);
const rect = (attrs: IRectAttrs) => {
const w = +attrs.width;
const h = +attrs.height;
const x = attrs.x ? +attrs.x : 0;
const y = attrs.y ? +attrs.y : 0;
let rx = attrs.rx || 'auto';
let ry = attrs.ry || 'auto';
if (rx === 'auto' && ry === 'auto') {
rx = 0;
ry = 0;
} else if (rx !== 'auto' && ry === 'auto') {
rx = calcValue(rx.toString(), w);
ry = rx;
} else if (ry !== 'auto' && rx === 'auto') {
ry = calcValue(ry.toString(), h);
rx = ry;
} else {
rx = calcValue(rx.toString(), w);
ry = calcValue(ry.toString(), h);
}
if (rx > w / 2) {
rx = w / 2;
}
if (ry > h / 2) {
ry = h / 2;
}
const hasCurves = rx > 0 && ry > 0;
return [
`M${x + rx} ${y}`,
`H${x + w - rx}`,
...(hasCurves ? [`A${rx} ${ry} 0 0 1 ${x + w} ${y + ry}`] : []),
`V${y + h - ry}`,
...(hasCurves ? [`A${rx} ${ry} 0 0 1 ${x + w - rx} ${y + h}`] : []),
`H${x + rx}`,
...(hasCurves ? [`A${rx} ${ry} 0 0 1 ${x} ${y + h - ry}`] : []),
`V${y + ry}`,
...(hasCurves ? [`A${rx} ${ry} 0 0 1 ${x + rx} ${y}`] : []),
'z',
];
};
const ellipse = (attrs: ICircleAttrs) => {
const cx = +attrs.cx;
const cy = +attrs.cy;
const rx = attrs.rx ? +attrs.rx : +attrs.r;
const ry = attrs.ry ? +attrs.ry : +attrs.r;
return [
`M${cx + rx} ${cy}`,
`A${rx} ${ry} 0 0 1 ${cx} ${cy + ry}`,
`A${rx} ${ry} 0 0 1 ${cx - rx} ${cy}`,
`A${rx} ${ry} 0 0 1 ${cx + rx} ${cy}`,
'z',
];
};
const line = ({ x1, y1, x2, y2 }: ILineAttrs) => [`M${+x1} ${+y1}`, `L${+x2} ${+y2}`];
const poly = (attrs: IPolyAttrs) => {
const { points } = attrs;
const pointsArray = points
.trim()
.split(' ')
.reduce((arr: string[], point: string) => [...arr, ...(point.includes(',') ? point.split(',') : [point])], []);
const pairs = chunkArray(pointsArray, 2);
return pairs.map(([x, y], i) => `${i === 0 ? 'M' : 'L'}${x} ${y}`);
};
const toPathString = (d: string[] | string) => (Array.isArray(d) ? d.join(' ') : '');
const convertShapeToPath = (
node: Record<string, any>,
{
nodeName = 'name',
nodeAttrs = 'attributes',
} = {},
) => {
const name = node[nodeName];
const attributes = node[nodeAttrs];
let d;
if (name === 'rect') {
d = rect(attributes);
}
if (name === 'circle' || name === 'ellipse') {
d = ellipse(attributes);
}
if (name === 'line') {
d = line(attributes);
}
if (name === 'polyline') {
d = poly(attributes);
}
if (name === 'polygon') {
d = [...poly(attributes), 'Z'];
}
if (name === 'path') {
return attributes.d;
}
return toPathString(d || '');
};
export default convertShapeToPath;
| 29.035503 | 119 | 0.570817 | 127 | 10 | 0 | 15 | 26 | 16 | 7 | 1 | 39 | 4 | 0 | 8.8 | 1,610 | 0.015528 | 0.016149 | 0.009938 | 0.002484 | 0 | 0.014925 | 0.58209 | 0.263956 | /*
* Tencent is pleased to support the open source community by making
* 蓝鲸智云PaaS平台社区版 (BlueKing PaaS Community Edition) available.
*
* Copyright (C) 2021 THL A29 Limited, a Tencent company. All rights reserved.
*
* 蓝鲸智云PaaS平台社区版 (BlueKing PaaS Community Edition) is licensed under the MIT License.
*
* License for 蓝鲸智云PaaS平台社区版 (BlueKing PaaS Community Edition):
*
* ---------------------------------------------------
* 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.
*/
interface IRectAttrs {
width;
height;
x;
y;
rx;
ry;
}
interface ICircleAttrs {
cx;
cy;
rx;
ry;
r;
}
interface ILineAttrs {
x1;
y1;
x2;
y2;
}
interface IPolyAttrs {
points;
}
/* Example usages of 'chunkArray' are shown below:
chunkArray(pointsArray, 2);
*/
const chunkArray = (arr, size = 2) => {
const results = [];
while (arr.length) {
results.push(arr.splice(0, size));
}
return results;
};
/* Example usages of 'calcValue' are shown below:
rx = calcValue(rx.toString(), w);
ry = calcValue(ry.toString(), h);
*/
const calcValue = (val, base) => (/%$/.test(val) ? (Number(val.replace('%', '')) * 100) / base : +val);
/* Example usages of 'rect' are shown below:
d = rect(attributes);
*/
const rect = (attrs) => {
const w = +attrs.width;
const h = +attrs.height;
const x = attrs.x ? +attrs.x : 0;
const y = attrs.y ? +attrs.y : 0;
let rx = attrs.rx || 'auto';
let ry = attrs.ry || 'auto';
if (rx === 'auto' && ry === 'auto') {
rx = 0;
ry = 0;
} else if (rx !== 'auto' && ry === 'auto') {
rx = calcValue(rx.toString(), w);
ry = rx;
} else if (ry !== 'auto' && rx === 'auto') {
ry = calcValue(ry.toString(), h);
rx = ry;
} else {
rx = calcValue(rx.toString(), w);
ry = calcValue(ry.toString(), h);
}
if (rx > w / 2) {
rx = w / 2;
}
if (ry > h / 2) {
ry = h / 2;
}
const hasCurves = rx > 0 && ry > 0;
return [
`M${x + rx} ${y}`,
`H${x + w - rx}`,
...(hasCurves ? [`A${rx} ${ry} 0 0 1 ${x + w} ${y + ry}`] : []),
`V${y + h - ry}`,
...(hasCurves ? [`A${rx} ${ry} 0 0 1 ${x + w - rx} ${y + h}`] : []),
`H${x + rx}`,
...(hasCurves ? [`A${rx} ${ry} 0 0 1 ${x} ${y + h - ry}`] : []),
`V${y + ry}`,
...(hasCurves ? [`A${rx} ${ry} 0 0 1 ${x + rx} ${y}`] : []),
'z',
];
};
/* Example usages of 'ellipse' are shown below:
d = ellipse(attributes);
*/
const ellipse = (attrs) => {
const cx = +attrs.cx;
const cy = +attrs.cy;
const rx = attrs.rx ? +attrs.rx : +attrs.r;
const ry = attrs.ry ? +attrs.ry : +attrs.r;
return [
`M${cx + rx} ${cy}`,
`A${rx} ${ry} 0 0 1 ${cx} ${cy + ry}`,
`A${rx} ${ry} 0 0 1 ${cx - rx} ${cy}`,
`A${rx} ${ry} 0 0 1 ${cx + rx} ${cy}`,
'z',
];
};
/* Example usages of 'line' are shown below:
d = line(attributes);
*/
const line = ({ x1, y1, x2, y2 }) => [`M${+x1} ${+y1}`, `L${+x2} ${+y2}`];
/* Example usages of 'poly' are shown below:
d = poly(attributes);
poly(attributes);
*/
const poly = (attrs) => {
const { points } = attrs;
const pointsArray = points
.trim()
.split(' ')
.reduce((arr, point) => [...arr, ...(point.includes(',') ? point.split(',') : [point])], []);
const pairs = chunkArray(pointsArray, 2);
return pairs.map(([x, y], i) => `${i === 0 ? 'M' : 'L'}${x} ${y}`);
};
/* Example usages of 'toPathString' are shown below:
toPathString(d || '');
*/
const toPathString = (d) => (Array.isArray(d) ? d.join(' ') : '');
/* Example usages of 'convertShapeToPath' are shown below:
;
*/
const convertShapeToPath = (
node,
{
nodeName = 'name',
nodeAttrs = 'attributes',
} = {},
) => {
const name = node[nodeName];
const attributes = node[nodeAttrs];
let d;
if (name === 'rect') {
d = rect(attributes);
}
if (name === 'circle' || name === 'ellipse') {
d = ellipse(attributes);
}
if (name === 'line') {
d = line(attributes);
}
if (name === 'polyline') {
d = poly(attributes);
}
if (name === 'polygon') {
d = [...poly(attributes), 'Z'];
}
if (name === 'path') {
return attributes.d;
}
return toPathString(d || '');
};
export default convertShapeToPath;
|
523e70b67737ed0370575cf49b57f86c4911f302 | 4,263 | ts | TypeScript | src/common/ChatGroup.ts | AsteriskZuo/react-native-easemob | 53763d1926344837979600c3f73b5b3e1bbc4ac6 | [
"MIT"
] | null | null | null | src/common/ChatGroup.ts | AsteriskZuo/react-native-easemob | 53763d1926344837979600c3f73b5b3e1bbc4ac6 | [
"MIT"
] | null | null | null | src/common/ChatGroup.ts | AsteriskZuo/react-native-easemob | 53763d1926344837979600c3f73b5b3e1bbc4ac6 | [
"MIT"
] | 2 | 2022-03-23T07:31:14.000Z | 2022-03-25T07:45:38.000Z | export enum ChatGroupStyle {
PrivateOnlyOwnerInvite = 0, // 私有群,只有群主能邀请他人进群,被邀请人会收到邀请信息,同意后可入群;
PrivateMemberCanInvite = 1, // 私有群,所有人都可以邀请他人进群,被邀请人会收到邀请信息,同意后可入群;
PublicJoinNeedApproval = 2, // 公开群,可以通过获取公开群列表api取的,申请加入时需要管理员以上权限用户同意;
PublicOpenJoin = 3, // 公开群,可以通过获取公开群列表api取的,可以直接进入;
}
export enum ChatGroupPermissionType {
None = -1,
Member = 0,
Admin = 1,
Owner = 2,
}
export function ChatGroupStyleFromNumber(params: number): ChatGroupStyle {
switch (params) {
case 0:
return ChatGroupStyle.PrivateOnlyOwnerInvite;
case 1:
return ChatGroupStyle.PrivateMemberCanInvite;
case 2:
return ChatGroupStyle.PublicJoinNeedApproval;
case 3:
return ChatGroupStyle.PublicOpenJoin;
default:
throw new Error(`not exist this type: ${params}`);
}
}
export function ChatConversationTypeToString(params: ChatGroupStyle): string {
return ChatGroupStyle[params];
}
export function ChatGroupPermissionTypeFromNumber(
params: number
): ChatGroupPermissionType {
switch (params) {
case -1:
return ChatGroupPermissionType.None;
case 0:
return ChatGroupPermissionType.Member;
case 1:
return ChatGroupPermissionType.Admin;
case 2:
return ChatGroupPermissionType.Owner;
default:
throw new Error(`not exist this type: ${params}`);
}
}
export function ChatGroupPermissionTypeToString(
params: ChatGroupPermissionType
): string {
return ChatGroupPermissionType[params];
}
export class ChatGroupMessageAck {
msg_id: string;
from: string;
count: number;
timestamp: number;
content?: string;
constructor(params: {
msg_id: string;
from: string;
count: number;
timestamp: number;
ext?: { content: string };
}) {
this.msg_id = params.msg_id;
this.from = params.from;
this.count = params.count;
this.timestamp = params.timestamp;
if (params.ext) {
this.content = params.ext.content;
}
}
}
export class ChatGroup {
groupId: string;
name: string;
desc: string;
owner: string;
announcement: string;
memberCount: number;
memberList: Array<string>;
adminList: Array<string>;
blockList: Array<string>;
muteList: Array<string>;
noticeEnable: boolean;
messageBlocked: boolean;
isAllMemberMuted: boolean;
options: ChatGroupOptions;
permissionType: ChatGroupPermissionType;
constructor(params: {
groupId: string;
name: string;
desc: string;
owner: string;
announcement: string;
memberCount: number;
memberList: Array<string>;
adminList: Array<string>;
blockList: Array<string>;
muteList: Array<string>;
noticeEnable: boolean;
messageBlocked: boolean;
isAllMemberMuted: boolean;
options: ChatGroupOptions;
permissionType: number;
}) {
this.groupId = params.groupId;
this.name = params.name;
this.desc = params.desc;
this.owner = params.owner;
this.announcement = params.announcement;
this.memberCount = params.memberCount;
this.memberList = params.memberList;
this.adminList = params.adminList;
this.blockList = params.blockList;
this.muteList = params.muteList;
this.noticeEnable = params.noticeEnable;
this.messageBlocked = params.messageBlocked;
this.isAllMemberMuted = params.isAllMemberMuted;
this.options = params.options;
this.permissionType = ChatGroupPermissionTypeFromNumber(
params.permissionType
);
}
}
export class ChatGroupOptions {
style: ChatGroupStyle;
maxCount: number;
inviteNeedConfirm: boolean;
ext: string;
constructor(params: {
style: number;
maxCount: number;
inviteNeedConfirm: boolean;
ext: string;
}) {
this.style = ChatGroupStyleFromNumber(params.style);
this.maxCount = params.maxCount;
this.inviteNeedConfirm = params.inviteNeedConfirm;
this.ext = params.ext;
}
}
export class ChatGroupSharedFile {
fileId: string;
name: string;
owner: string;
createTime: number;
fileSize: number;
constructor(
fileId: string,
name: string,
owner: string,
createTime: number,
fileSize: number
) {
this.fileId = fileId;
this.name = name;
this.owner = owner;
this.createTime = createTime;
this.fileSize = fileSize;
}
}
| 25.224852 | 78 | 0.701149 | 161 | 8 | 0 | 12 | 0 | 29 | 2 | 0 | 58 | 4 | 0 | 7.375 | 1,216 | 0.016447 | 0 | 0.023849 | 0.003289 | 0 | 0 | 1.183673 | 0.212811 | export enum ChatGroupStyle {
PrivateOnlyOwnerInvite = 0, // 私有群,只有群主能邀请他人进群,被邀请人会收到邀请信息,同意后可入群;
PrivateMemberCanInvite = 1, // 私有群,所有人都可以邀请他人进群,被邀请人会收到邀请信息,同意后可入群;
PublicJoinNeedApproval = 2, // 公开群,可以通过获取公开群列表api取的,申请加入时需要管理员以上权限用户同意;
PublicOpenJoin = 3, // 公开群,可以通过获取公开群列表api取的,可以直接进入;
}
export enum ChatGroupPermissionType {
None = -1,
Member = 0,
Admin = 1,
Owner = 2,
}
export /* Example usages of 'ChatGroupStyleFromNumber' are shown below:
this.style = ChatGroupStyleFromNumber(params.style);
*/
function ChatGroupStyleFromNumber(params) {
switch (params) {
case 0:
return ChatGroupStyle.PrivateOnlyOwnerInvite;
case 1:
return ChatGroupStyle.PrivateMemberCanInvite;
case 2:
return ChatGroupStyle.PublicJoinNeedApproval;
case 3:
return ChatGroupStyle.PublicOpenJoin;
default:
throw new Error(`not exist this type: ${params}`);
}
}
export function ChatConversationTypeToString(params) {
return ChatGroupStyle[params];
}
export /* Example usages of 'ChatGroupPermissionTypeFromNumber' are shown below:
this.permissionType = ChatGroupPermissionTypeFromNumber(params.permissionType);
*/
function ChatGroupPermissionTypeFromNumber(
params
) {
switch (params) {
case -1:
return ChatGroupPermissionType.None;
case 0:
return ChatGroupPermissionType.Member;
case 1:
return ChatGroupPermissionType.Admin;
case 2:
return ChatGroupPermissionType.Owner;
default:
throw new Error(`not exist this type: ${params}`);
}
}
export function ChatGroupPermissionTypeToString(
params
) {
return ChatGroupPermissionType[params];
}
export class ChatGroupMessageAck {
msg_id;
from;
count;
timestamp;
content?;
constructor(params) {
this.msg_id = params.msg_id;
this.from = params.from;
this.count = params.count;
this.timestamp = params.timestamp;
if (params.ext) {
this.content = params.ext.content;
}
}
}
export class ChatGroup {
groupId;
name;
desc;
owner;
announcement;
memberCount;
memberList;
adminList;
blockList;
muteList;
noticeEnable;
messageBlocked;
isAllMemberMuted;
options;
permissionType;
constructor(params) {
this.groupId = params.groupId;
this.name = params.name;
this.desc = params.desc;
this.owner = params.owner;
this.announcement = params.announcement;
this.memberCount = params.memberCount;
this.memberList = params.memberList;
this.adminList = params.adminList;
this.blockList = params.blockList;
this.muteList = params.muteList;
this.noticeEnable = params.noticeEnable;
this.messageBlocked = params.messageBlocked;
this.isAllMemberMuted = params.isAllMemberMuted;
this.options = params.options;
this.permissionType = ChatGroupPermissionTypeFromNumber(
params.permissionType
);
}
}
export class ChatGroupOptions {
style;
maxCount;
inviteNeedConfirm;
ext;
constructor(params) {
this.style = ChatGroupStyleFromNumber(params.style);
this.maxCount = params.maxCount;
this.inviteNeedConfirm = params.inviteNeedConfirm;
this.ext = params.ext;
}
}
export class ChatGroupSharedFile {
fileId;
name;
owner;
createTime;
fileSize;
constructor(
fileId,
name,
owner,
createTime,
fileSize
) {
this.fileId = fileId;
this.name = name;
this.owner = owner;
this.createTime = createTime;
this.fileSize = fileSize;
}
}
|
5275915be28a7233f2250b8e6406109e2ae78980 | 4,371 | ts | TypeScript | src/utils/querybuilder.ts | laurence702/darkgold_wallet_V2 | 86c82f24ed2b567e1d131da54159ee5c2ee4f2e3 | [
"MIT"
] | 1 | 2022-02-02T11:08:39.000Z | 2022-02-02T11:08:39.000Z | src/utils/querybuilder.ts | laurence702/darkgold_wallet_V2 | 86c82f24ed2b567e1d131da54159ee5c2ee4f2e3 | [
"MIT"
] | null | null | null | src/utils/querybuilder.ts | laurence702/darkgold_wallet_V2 | 86c82f24ed2b567e1d131da54159ee5c2ee4f2e3 | [
"MIT"
] | null | null | null | class QueryBuilder {
private queryBuild: any;
public query: any;
private hasFiltered = false;
private hasSort = false;
private hasSelect = false;
private hasPaginate = false;
constructor(query?: string) {
this.query = query || {};
}
filter() {
const filterObj = this.excludeFields(this.query, [
'sort',
'select',
'page',
'perPage',
'populate',
]);
let where = this.normalizeMathOperatorsRecursive(filterObj);
where = this.filterRecursive(where);
const filtered = { where };
this.queryBuild = { ...this.queryBuild, ...filtered };
this.hasFiltered = true;
return this;
}
sort() {
const sort =
this.selectOnlyFields(this.query, ['sort']).sort || '-created_at';
const orderBy = sort.split(',').map((s: string) => ({
[s.startsWith('-') ? s.slice(1, s.length) : s]: s.startsWith('-')
? 'desc'
: 'asc',
}));
this.queryBuild = { ...this.queryBuild, orderBy };
this.hasSort = true;
return this;
}
select() {
const selectFields = this.selectOnlyFields(this.query, ['select']).select;
const selections = this.getRecursiveSelection(selectFields);
this.queryBuild = {
...this.queryBuild,
...selections,
};
this.hasSelect = true;
return this;
}
paginate() {
let { page, perPage } = this.selectOnlyFields(this.query, [
'page',
'perPage',
]);
page = parseInt(page) || 1;
perPage = parseInt(perPage) || 10;
this.queryBuild = {
...this.queryBuild,
skip: perPage * (page - 1),
take: perPage,
};
this.hasPaginate = true;
return this;
}
build(actions?: string[]) {
if (!this.hasFiltered && actions?.includes('filter')) {
this.filter();
}
if (!this.hasSort && actions?.includes('sort')) {
this.sort();
}
if (!this.hasSelect && actions?.includes('select')) {
this.select();
}
if (!this.hasPaginate && actions?.includes('paginate')) {
this.paginate();
}
return this.queryBuild;
}
private excludeFields(o: Record<string, unknown>, ex: string[]) {
const e = { ...o };
for (const t in e) {
if (ex.includes(t)) delete e[t];
}
return e;
}
private selectOnlyFields(o: Record<string, unknown>, ex: string[]) {
const e: any = {};
ex.forEach((i) => (e[i] = o[i]));
return e;
}
private normalizeMathOperatorsRecursive(filters: any) {
if (!filters || Object.keys(filters).length < 1) return {};
let normalized = {};
for (const key in filters) {
const value = filters[key];
if (typeof value !== 'string')
normalized = {
...normalized,
[key]: this.normalizeMathOperatorsRecursive(value),
};
else if (!isNaN(value as any))
normalized = { ...normalized, [key]: parseInt(value) };
else normalized = { ...normalized, [key]: value };
}
return normalized;
}
private filterRecursive(filters: any) {
if (!filters || Object.keys(filters).length < 1) return {};
let normalized = {};
for (const key in filters) {
const value = filters[key];
if (key.includes('.')) {
const [parent, child] = key.split('.');
normalized = {
...normalized,
[parent]: { [child]: value },
};
} else {
normalized = { ...normalized, [key]: value };
}
}
return normalized;
}
private getRecursiveSelection(selectClause: string): Record<string, unknown> {
if (!selectClause) return {};
if (selectClause.includes(',')) {
let r = {};
const s = selectClause.split(',');
for (const i of s) {
r = { ...r, ...this.getRecursiveSelection(i) };
}
return { select: r };
}
if (selectClause.includes('.')) {
const [c, ...rest] = selectClause.split('.');
const rj = rest.join();
const sd = rj.slice(1, rj.length - 1);
return {
[c]: { ...this.getRecursiveSelection(sd) },
};
}
if (selectClause.includes('|')) {
let r = {};
const s = selectClause.split('|');
for (const i of s) {
r = { ...r, ...this.getRecursiveSelection(i) };
}
return { select: r };
}
return {
[selectClause]: true,
};
}
}
export default QueryBuilder;
| 23.005263 | 80 | 0.550217 | 154 | 13 | 0 | 11 | 22 | 6 | 9 | 6 | 12 | 1 | 2 | 9.923077 | 1,165 | 0.020601 | 0.018884 | 0.00515 | 0.000858 | 0.001717 | 0.115385 | 0.230769 | 0.281256 | class QueryBuilder {
private queryBuild;
public query;
private hasFiltered = false;
private hasSort = false;
private hasSelect = false;
private hasPaginate = false;
constructor(query?) {
this.query = query || {};
}
filter() {
const filterObj = this.excludeFields(this.query, [
'sort',
'select',
'page',
'perPage',
'populate',
]);
let where = this.normalizeMathOperatorsRecursive(filterObj);
where = this.filterRecursive(where);
const filtered = { where };
this.queryBuild = { ...this.queryBuild, ...filtered };
this.hasFiltered = true;
return this;
}
sort() {
const sort =
this.selectOnlyFields(this.query, ['sort']).sort || '-created_at';
const orderBy = sort.split(',').map((s) => ({
[s.startsWith('-') ? s.slice(1, s.length) : s]: s.startsWith('-')
? 'desc'
: 'asc',
}));
this.queryBuild = { ...this.queryBuild, orderBy };
this.hasSort = true;
return this;
}
select() {
const selectFields = this.selectOnlyFields(this.query, ['select']).select;
const selections = this.getRecursiveSelection(selectFields);
this.queryBuild = {
...this.queryBuild,
...selections,
};
this.hasSelect = true;
return this;
}
paginate() {
let { page, perPage } = this.selectOnlyFields(this.query, [
'page',
'perPage',
]);
page = parseInt(page) || 1;
perPage = parseInt(perPage) || 10;
this.queryBuild = {
...this.queryBuild,
skip: perPage * (page - 1),
take: perPage,
};
this.hasPaginate = true;
return this;
}
build(actions?) {
if (!this.hasFiltered && actions?.includes('filter')) {
this.filter();
}
if (!this.hasSort && actions?.includes('sort')) {
this.sort();
}
if (!this.hasSelect && actions?.includes('select')) {
this.select();
}
if (!this.hasPaginate && actions?.includes('paginate')) {
this.paginate();
}
return this.queryBuild;
}
private excludeFields(o, ex) {
const e = { ...o };
for (const t in e) {
if (ex.includes(t)) delete e[t];
}
return e;
}
private selectOnlyFields(o, ex) {
const e = {};
ex.forEach((i) => (e[i] = o[i]));
return e;
}
private normalizeMathOperatorsRecursive(filters) {
if (!filters || Object.keys(filters).length < 1) return {};
let normalized = {};
for (const key in filters) {
const value = filters[key];
if (typeof value !== 'string')
normalized = {
...normalized,
[key]: this.normalizeMathOperatorsRecursive(value),
};
else if (!isNaN(value as any))
normalized = { ...normalized, [key]: parseInt(value) };
else normalized = { ...normalized, [key]: value };
}
return normalized;
}
private filterRecursive(filters) {
if (!filters || Object.keys(filters).length < 1) return {};
let normalized = {};
for (const key in filters) {
const value = filters[key];
if (key.includes('.')) {
const [parent, child] = key.split('.');
normalized = {
...normalized,
[parent]: { [child]: value },
};
} else {
normalized = { ...normalized, [key]: value };
}
}
return normalized;
}
private getRecursiveSelection(selectClause) {
if (!selectClause) return {};
if (selectClause.includes(',')) {
let r = {};
const s = selectClause.split(',');
for (const i of s) {
r = { ...r, ...this.getRecursiveSelection(i) };
}
return { select: r };
}
if (selectClause.includes('.')) {
const [c, ...rest] = selectClause.split('.');
const rj = rest.join();
const sd = rj.slice(1, rj.length - 1);
return {
[c]: { ...this.getRecursiveSelection(sd) },
};
}
if (selectClause.includes('|')) {
let r = {};
const s = selectClause.split('|');
for (const i of s) {
r = { ...r, ...this.getRecursiveSelection(i) };
}
return { select: r };
}
return {
[selectClause]: true,
};
}
}
export default QueryBuilder;
|
Subsets and Splits