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
|
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
a602d09d6492b568180b56a8fff0ba51ab32f708 | 10,977 | ts | TypeScript | libs/amyr-ts-lib/src/lib/libs/tsmt/utils/string-utils.ts | theAlgorithmist/AMYR | db4141d7e545b94a5c98fc5430a065e2ba229e75 | [
"Apache-2.0"
] | 3 | 2022-01-17T21:31:47.000Z | 2022-03-04T20:16:21.000Z | libs/amyr-ts-lib/src/lib/libs/tsmt/utils/string-utils.ts | theAlgorithmist/AMYR | db4141d7e545b94a5c98fc5430a065e2ba229e75 | [
"Apache-2.0"
] | null | null | null | libs/amyr-ts-lib/src/lib/libs/tsmt/utils/string-utils.ts | theAlgorithmist/AMYR | db4141d7e545b94a5c98fc5430a065e2ba229e75 | [
"Apache-2.0"
] | null | null | null | /**
* Copyright 2016 Jim Armstrong (www.algorithmist.net)
*
* 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.
*/
/**
* AMYR Library: Low-level, utils string utility functions (probably similar to many you have seen
* elsewhere as there really isn't anything new under the sun). These methods are optimized for reasonable
* performance and there is little error checking. You break it ... you buy it. Some methods are direct
* replacement for lodash equivalents.
*
* @author Jim Armstrong (https://www.linkedin.com/in/jimarmstrong/)
*
* @version 1.0
*/
export const WHITESPACE: Array<string> = [ ' ', '\n', '\r', '\t', '\f', '\v', '\u00A0', '\u1680', '\u180E', '\u2000',
'\u2001', '\u2002', '\u2003', '\u2004', '\u2005', '\u2006', '\u2007', '\u2008',
'\u2009', '\u200A', '\u2028', '\u2029', '\u202F', '\u205F', '\u3000'
];
/**
* Determine if an input string starts exactly with the specified char string (case matters)
*
* @param {string} input Input string
*
* @param {string} target string to check against
* @default 0
*/
export function startsWith(input: string, target: string, position: number = 0): boolean
{
const length: number = input.length || 0;
if (!input || !target ) return false;
// relatively quick string-convert
target = `${target}`;
const n: number = target.length;
if (length == 0 && n == 0) {
return true;
}
position = position < 0 ? 0 : (position >= length ? length-1 : position);
return input.slice(position, position + n) === target
}
/**
* Capitalize the first letter of a string and convert all remaining characters to lowercase
*
* @param {string} input String to be capitalized
*/
export function capitalize(input: string): string
{
const n: number = input.length;
if (n === 0) return input;
if (n === 1) return input.toUpperCase();
return input.charAt(0).toUpperCase() + (input.substr(1, n)).toLowerCase();
}
/**
* Quick trim of spaces from a string
*
* @param {string} inputInput string
*/
export function trim(input: string): string
{
return input.replace(/ /g, '');
}
/**
* Remove selected whitepsace characters from the beginning of a string
*
* @param {string} input Input string
*
* @param {Array<string>} white List of whitespace characters to be removed
* @default {WHITESPACE}
*/
export function leftTrim(input: string, chars: Array<string> = WHITESPACE): string
{
let start = 0;
const len: number = input.length;
const whiteLen: number = chars.length;
let found = true;
let i: number;
let char: string;
while (found && start < len)
{
found = false;
i = -1;
char = input.charAt(start);
while (++i < whiteLen)
{
if (char === chars[i])
{
found = true;
start++;
break;
}
}
}
return (start >= len) ? '' : input.substr(start, len);
}
/**
* Remove selected whitespace characters from the end of a string
*
* @param {string} input Input string
*
* @param {Array<string>} white List of whitespace characters to be removed
* @default {WHITESPACE}
*/
export function rightTrim(input: string, chars: Array<string> = WHITESPACE): string
{
const len: number = input.length;
let end: number = len-1;
const whiteLen: number = chars.length;
let found = true;
let i: number;
let char: string;
while (found && end >= 0)
{
found = false;
i = -1;
char = input.charAt(end);
while (++i < whiteLen)
{
if (char === chars[i])
{
found = true;
end--;
break;
}
}
}
return (end >= 0) ? input.substr(0, end+1) : '';
}
/**
* Trim whitespace from beginning and end of a string based on a list of whitespace characters
* (that may include line feeds and such)
*
* @param {string} input Input string
*
* @param {Array<string>} chars List of 'whitespace' characters to remove
* @default {WHITESPACE}
*/
export function trimEnds(input: string, chars: Array<string> = WHITESPACE): string
{
return leftTrim(rightTrim(input, chars), chars);
}
/**
* Trim a string at the nearest (previous) space based on a character count with optional insertion of ellipses.
* Original string is trimmed at nearest previous space, i.e. 'This is a test' is trimmed to 'This is a'
* with a character count greater than nine or 'This is a...' if the ellipses parameter is true.
*
* @param input : input string
*
* @param count : number - Character count for trimming (must be greater than zero)
*
* @param ellipses: boolean If true, insert ellipses (...) after trip
* @default {false}
*/
export function trimToCharCount(input: string, count: number, ellipses: boolean = false): string
{
count = Math.max(1, Math.round(count));
const len: number = input.length;
if (len < count) return input;
if (input === ' ') return '';
let char: string = input.charAt(count-1);
let end: number = count-1;
while (end >= 0)
{
char = input.charAt(end--);
if (char === ' ') break;
}
end = end < 0 ? count-1 : end;
// add ellipses?
return ellipses ? input.substring(0,end+1) + '...' : input.substring(0, end+1);
}
/**
* Left-pad a string with a specified character if its length is smaller than the specified value
*
* @param {string} input Input string
*
* @param {number} len minimum length (must be greater than zero)
*
* @param {string} replaceWith: string Replacement string
* @default ' ' (single space)
*/
export function leftPad(input: string, len: number, replaceWith: string = ' '): string
{
len = Math.max(1, Math.round(len));
return ((input.length < len) ? repeat(replaceWith, len - input.length) + input : input);
}
/**
* Right-pad a string with a specified character if its length is smaller than the specified value
*
* @param {string} input Input string
*
* @param {number} len minimum length (must be greater than zero)
*
* @param {string} replaceWith Replacement string
* @default ' ' (single space)
*/
export function rightPad(input: string, len: number, replaceWith: string = ' '): string
{
len = Math.max(1, Math.round(len));
return (input.length < len) ? input + repeat(replaceWith, len - input.length) : input;
}
/**
* Repeat a string specified number of times
*
* @param {string} input Input string
*
* @param {number} n Repeat count (must be greater than zero)
*/
export function repeat(input: string, n: number): string
{
n = Math.max(1, Math.round(n));
return (new Array(n + 1)).join(input);
}
/**
* Escape a string to prepare for DOM insertion
*
* @param {string} input Input string with characters that require escaping before dynamic placement into DOM elements
*/
export function toHtml(input: string): string
{
return input
.replace(/</g, '<')
.replace(/>/g, '>')
.replace(/&/g, '&')
.replace(/"/g, '"')
.replace(/'/g, ''');
}
/**
* Unescape HTML special characters (reverse of toHtml)
*
* @param {string} input Input string containing html-escaped characters
*/
export function fromHtml(input: string): string
{
return input
.replace(/</g, '<')
.replace(/>/g, '>')
.replace(/&/g, '&')
.replace(/"/g, '"')
.replace(/'/g, "'");
}
/**
* Return the first non-repeating character in a string or a null string if all characters are unique
*
* @param {string} input Input string
*/
export function firstNonrepeatingChar(input: string): string
{
if (input == '') return '';
// this algorithm tends to run reasonably fast in practice, although complexity is still O(n^2).
const len: number = input.length;
let i: number
let char = '';
for (i = 0; i < len; ++i)
{
char = input.charAt(i);
if (input.indexOf(char) == i && input.indexOf(char,i+1) == -1) {
return char;
}
}
return '';
}
/**
* Reverse characters in a string
*
* @param {string} input Input string
*/
export function reverseChars(input: string): string
{
return input.split('').reverse().join('');
}
/**
* Convert an input string (presumed to be a name) into uppercase initials with an optional delimiter, i.e.
* james tiberius kirk -> JTK or J.T.K.
*
* @param {string} input Input string
*/
export function initials(input: string, delim: string=''): string
{
return input.split(' ').map( (n:string): string => {return n.charAt(0).toUpperCase()} ).join(delim);
}
/**
* Count the number of words in a string.
*
* @param {string} input Input string
*/
export function wordCount(input: string): number
{
if (input === undefined || input == null) return 0;
if (input == '' || input == ' ') return 0;
const matcher: RegExpMatchArray | null = input.match(/\b\w+\b/g);
return matcher != null ? matcher.length : 0;
}
/**
* Remove all instances of the input substring from the supplied string.
*
* @param {string} input Input string
*
* @param {string} remove Substring to be removed
*
* @param {boolean} caseSensitive Indicate if replacement is case sensitive.
* @edefault {true}
*/
export function remove(input: string, remove: string, caseSensitive: boolean=true): string
{
if (input === undefined || input == null) return '';
if (input == '' || input == ' ') return input;
const rem: string = __pattern(remove);
const flags: string = (!caseSensitive) ? 'ig' : 'g';
return input.replace(new RegExp(rem, flags), '');
}
/**
* Is the input string numeric?
*
* @param {string} input Input string
*/
export function isNumeric(input: string): boolean
{
if (input === undefined && input == null) return false;
if (input == '' || input == ' ') return false;
// ha ha - another one I looked up on stackoverflow!
const regex = /^[-+]?\d*\.?\d+(?:[eE][-+]?\d+)?$/;
return regex.test(input);
}
export function __pattern(pattern: string): string
{
// of course I ripped this from stackoverflow ... what did you expect?
return pattern.replace(/(\]|\[|\{|\}|\(|\)|\*|\+|\?|\.|\\)/g, '\\$1');
}
| 28.146154 | 119 | 0.613556 | 179 | 20 | 0 | 35 | 26 | 0 | 4 | 0 | 75 | 0 | 0 | 5.95 | 3,045 | 0.018062 | 0.008539 | 0 | 0 | 0 | 0 | 0.925926 | 0.240023 | /**
* Copyright 2016 Jim Armstrong (www.algorithmist.net)
*
* 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.
*/
/**
* AMYR Library: Low-level, utils string utility functions (probably similar to many you have seen
* elsewhere as there really isn't anything new under the sun). These methods are optimized for reasonable
* performance and there is little error checking. You break it ... you buy it. Some methods are direct
* replacement for lodash equivalents.
*
* @author Jim Armstrong (https://www.linkedin.com/in/jimarmstrong/)
*
* @version 1.0
*/
export const WHITESPACE = [ ' ', '\n', '\r', '\t', '\f', '\v', '\u00A0', '\u1680', '\u180E', '\u2000',
'\u2001', '\u2002', '\u2003', '\u2004', '\u2005', '\u2006', '\u2007', '\u2008',
'\u2009', '\u200A', '\u2028', '\u2029', '\u202F', '\u205F', '\u3000'
];
/**
* Determine if an input string starts exactly with the specified char string (case matters)
*
* @param {string} input Input string
*
* @param {string} target string to check against
* @default 0
*/
export function startsWith(input, target, position = 0)
{
const length = input.length || 0;
if (!input || !target ) return false;
// relatively quick string-convert
target = `${target}`;
const n = target.length;
if (length == 0 && n == 0) {
return true;
}
position = position < 0 ? 0 : (position >= length ? length-1 : position);
return input.slice(position, position + n) === target
}
/**
* Capitalize the first letter of a string and convert all remaining characters to lowercase
*
* @param {string} input String to be capitalized
*/
export function capitalize(input)
{
const n = input.length;
if (n === 0) return input;
if (n === 1) return input.toUpperCase();
return input.charAt(0).toUpperCase() + (input.substr(1, n)).toLowerCase();
}
/**
* Quick trim of spaces from a string
*
* @param {string} inputInput string
*/
export function trim(input)
{
return input.replace(/ /g, '');
}
/**
* Remove selected whitepsace characters from the beginning of a string
*
* @param {string} input Input string
*
* @param {Array<string>} white List of whitespace characters to be removed
* @default {WHITESPACE}
*/
export /* Example usages of 'leftTrim' are shown below:
leftTrim(rightTrim(input, chars), chars);
*/
function leftTrim(input, chars = WHITESPACE)
{
let start = 0;
const len = input.length;
const whiteLen = chars.length;
let found = true;
let i;
let char;
while (found && start < len)
{
found = false;
i = -1;
char = input.charAt(start);
while (++i < whiteLen)
{
if (char === chars[i])
{
found = true;
start++;
break;
}
}
}
return (start >= len) ? '' : input.substr(start, len);
}
/**
* Remove selected whitespace characters from the end of a string
*
* @param {string} input Input string
*
* @param {Array<string>} white List of whitespace characters to be removed
* @default {WHITESPACE}
*/
export /* Example usages of 'rightTrim' are shown below:
leftTrim(rightTrim(input, chars), chars);
*/
function rightTrim(input, chars = WHITESPACE)
{
const len = input.length;
let end = len-1;
const whiteLen = chars.length;
let found = true;
let i;
let char;
while (found && end >= 0)
{
found = false;
i = -1;
char = input.charAt(end);
while (++i < whiteLen)
{
if (char === chars[i])
{
found = true;
end--;
break;
}
}
}
return (end >= 0) ? input.substr(0, end+1) : '';
}
/**
* Trim whitespace from beginning and end of a string based on a list of whitespace characters
* (that may include line feeds and such)
*
* @param {string} input Input string
*
* @param {Array<string>} chars List of 'whitespace' characters to remove
* @default {WHITESPACE}
*/
export function trimEnds(input, chars = WHITESPACE)
{
return leftTrim(rightTrim(input, chars), chars);
}
/**
* Trim a string at the nearest (previous) space based on a character count with optional insertion of ellipses.
* Original string is trimmed at nearest previous space, i.e. 'This is a test' is trimmed to 'This is a'
* with a character count greater than nine or 'This is a...' if the ellipses parameter is true.
*
* @param input : input string
*
* @param count : number - Character count for trimming (must be greater than zero)
*
* @param ellipses: boolean If true, insert ellipses (...) after trip
* @default {false}
*/
export function trimToCharCount(input, count, ellipses = false)
{
count = Math.max(1, Math.round(count));
const len = input.length;
if (len < count) return input;
if (input === ' ') return '';
let char = input.charAt(count-1);
let end = count-1;
while (end >= 0)
{
char = input.charAt(end--);
if (char === ' ') break;
}
end = end < 0 ? count-1 : end;
// add ellipses?
return ellipses ? input.substring(0,end+1) + '...' : input.substring(0, end+1);
}
/**
* Left-pad a string with a specified character if its length is smaller than the specified value
*
* @param {string} input Input string
*
* @param {number} len minimum length (must be greater than zero)
*
* @param {string} replaceWith: string Replacement string
* @default ' ' (single space)
*/
export function leftPad(input, len, replaceWith = ' ')
{
len = Math.max(1, Math.round(len));
return ((input.length < len) ? repeat(replaceWith, len - input.length) + input : input);
}
/**
* Right-pad a string with a specified character if its length is smaller than the specified value
*
* @param {string} input Input string
*
* @param {number} len minimum length (must be greater than zero)
*
* @param {string} replaceWith Replacement string
* @default ' ' (single space)
*/
export function rightPad(input, len, replaceWith = ' ')
{
len = Math.max(1, Math.round(len));
return (input.length < len) ? input + repeat(replaceWith, len - input.length) : input;
}
/**
* Repeat a string specified number of times
*
* @param {string} input Input string
*
* @param {number} n Repeat count (must be greater than zero)
*/
export /* Example usages of 'repeat' are shown below:
(input.length < len) ? repeat(replaceWith, len - input.length) + input : input;
(input.length < len) ? input + repeat(replaceWith, len - input.length) : input;
*/
function repeat(input, n)
{
n = Math.max(1, Math.round(n));
return (new Array(n + 1)).join(input);
}
/**
* Escape a string to prepare for DOM insertion
*
* @param {string} input Input string with characters that require escaping before dynamic placement into DOM elements
*/
export function toHtml(input)
{
return input
.replace(/</g, '<')
.replace(/>/g, '>')
.replace(/&/g, '&')
.replace(/"/g, '"')
.replace(/'/g, ''');
}
/**
* Unescape HTML special characters (reverse of toHtml)
*
* @param {string} input Input string containing html-escaped characters
*/
export function fromHtml(input)
{
return input
.replace(/</g, '<')
.replace(/>/g, '>')
.replace(/&/g, '&')
.replace(/"/g, '"')
.replace(/'/g, "'");
}
/**
* Return the first non-repeating character in a string or a null string if all characters are unique
*
* @param {string} input Input string
*/
export function firstNonrepeatingChar(input)
{
if (input == '') return '';
// this algorithm tends to run reasonably fast in practice, although complexity is still O(n^2).
const len = input.length;
let i
let char = '';
for (i = 0; i < len; ++i)
{
char = input.charAt(i);
if (input.indexOf(char) == i && input.indexOf(char,i+1) == -1) {
return char;
}
}
return '';
}
/**
* Reverse characters in a string
*
* @param {string} input Input string
*/
export function reverseChars(input)
{
return input.split('').reverse().join('');
}
/**
* Convert an input string (presumed to be a name) into uppercase initials with an optional delimiter, i.e.
* james tiberius kirk -> JTK or J.T.K.
*
* @param {string} input Input string
*/
export function initials(input, delim='')
{
return input.split(' ').map( (n) => {return n.charAt(0).toUpperCase()} ).join(delim);
}
/**
* Count the number of words in a string.
*
* @param {string} input Input string
*/
export function wordCount(input)
{
if (input === undefined || input == null) return 0;
if (input == '' || input == ' ') return 0;
const matcher = input.match(/\b\w+\b/g);
return matcher != null ? matcher.length : 0;
}
/**
* Remove all instances of the input substring from the supplied string.
*
* @param {string} input Input string
*
* @param {string} remove Substring to be removed
*
* @param {boolean} caseSensitive Indicate if replacement is case sensitive.
* @edefault {true}
*/
export /* Example usages of 'remove' are shown below:
;
__pattern(remove);
*/
function remove(input, remove, caseSensitive=true)
{
if (input === undefined || input == null) return '';
if (input == '' || input == ' ') return input;
const rem = __pattern(remove);
const flags = (!caseSensitive) ? 'ig' : 'g';
return input.replace(new RegExp(rem, flags), '');
}
/**
* Is the input string numeric?
*
* @param {string} input Input string
*/
export function isNumeric(input)
{
if (input === undefined && input == null) return false;
if (input == '' || input == ' ') return false;
// ha ha - another one I looked up on stackoverflow!
const regex = /^[-+]?\d*\.?\d+(?:[eE][-+]?\d+)?$/;
return regex.test(input);
}
export /* Example usages of '__pattern' are shown below:
__pattern(remove);
*/
function __pattern(pattern)
{
// of course I ripped this from stackoverflow ... what did you expect?
return pattern.replace(/(\]|\[|\{|\}|\(|\)|\*|\+|\?|\.|\\)/g, '\\$1');
}
|
a665fed0ae259c933eeb81c6c1c601dcc968e5ba | 3,045 | ts | TypeScript | src/structures/util/Color.ts | SevenTV/Website | 285153a36974e2c5d0253c6a4279d2ab2491faf2 | [
"Apache-2.0"
] | 3 | 2022-03-02T10:34:23.000Z | 2022-03-17T16:36:06.000Z | src/structures/util/Color.ts | SevenTV/Website | 285153a36974e2c5d0253c6a4279d2ab2491faf2 | [
"Apache-2.0"
] | 29 | 2022-02-24T00:35:41.000Z | 2022-03-31T00:28:44.000Z | src/structures/util/Color.ts | SevenTV/Website | 285153a36974e2c5d0253c6a4279d2ab2491faf2 | [
"Apache-2.0"
] | 2 | 2022-03-06T18:30:59.000Z | 2022-03-27T15:50:23.000Z | export const ConvertIntColorToHex = (color: number, alpha?: number) => {
return `#${color.toString(16)}` + (alpha ? SetHexAlpha(alpha) : "");
};
export const SetHexAlpha = (alpha: number): string => {
if (alpha > 1 || alpha < 0 || isNaN(alpha)) {
throw Error("alpha must be between 0 and 1");
}
return Math.ceil(255 * alpha)
.toString(16)
.toUpperCase();
};
export const ConvertRGBAToDecimal = (r: number, g: number, b: number, a: number): number =>
(r << 24) | (g << 16) | (b << 8) | a;
export const ConvertDecimalRGBAToString = (num: number): string => {
const r = (num >>> 24) & 0xff;
const g = (num >>> 16) & 0xff;
const b = (num >>> 8) & 0xff;
const a = num & 0xff;
return `rgba(${r}, ${g}, ${b}, ${(a / 255).toFixed(3)})`;
};
export const ConvertHexToRGB = (hex: string): [number, number, number] => {
const t = parseInt(hex?.slice(1) ?? "0", 16);
const r = (t >> 16) & 255;
const g = (t >> 8) & 255;
const b = t & 255;
return [r, g, b];
};
export const ConvertDecimalToHex = (num: number, alpha?: boolean): string => {
const r = (num >>> 24) & 0xff;
const g = (num >>> 16) & 0xff;
const b = (num >>> 8) & 0xff;
const a = num & 0xff;
return "#" + ((1 << 24) + (r << 16) + (g << 8) + b).toString(16).slice(1) + (alpha ? SetHexAlpha(a / 255) : "");
};
export const ConvertIntToHSVColor = (color: number) => {
const r = color >> 16;
const g = (color >> 8) & ((1 << 8) - 1);
const b = color & ((1 << 8) - 1);
return ConvertRGBToHSVColor(r, g, b);
};
export const ConvertRGBToHSVColor = (r: number, g: number, b: number) => {
const rabs = r / 255;
const gabs = g / 255;
const babs = b / 255;
const v = Math.max(rabs, gabs, babs);
const diff = v - Math.min(rabs, gabs, babs);
const diffc = (c: number) => (v - c) / 6 / diff + 1 / 2;
const percentRoundFn = (num: number) => Math.round(num * 100) / 100;
let h = 0;
let s = 0;
if (diff === 0) {
h = s = 0;
} else {
s = diff / v;
const rr = diffc(rabs);
const gg = diffc(gabs);
const bb = diffc(babs);
if (rabs === v) {
h = bb - gg;
} else if (gabs === v) {
h = 1 / 3 + rr - bb;
} else if (babs === v) {
h = 2 / 3 + gg - rr;
}
if (h < 0) {
h += 1;
} else if (h > 1) {
h -= 1;
}
}
return {
h: Math.round(h * 360),
s: percentRoundFn(s * 100),
v: percentRoundFn(v * 100),
};
};
export const hsv2hsl = (h: number, s: number, v: number, l = v - (v * s) / 2, m = Math.min(l, 1 - l)) => [
h,
m ? (v - l) / m : 0,
l,
];
export const hsl2hsv = (h: number, s: number, l: number, v = s * Math.min(l, 1 - l) + l) => [
h,
v ? 2 - (2 * l) / v : 0,
v,
];
export const NormalizeColor = (color: number, loweLight: number, upperLight: number) => {
const r = color >> 16;
const g = (color >> 8) & ((1 << 8) - 1);
const b = color & ((1 << 8) - 1);
const hsv = ConvertRGBToHSVColor(r, g, b);
const hsl = hsv2hsl(hsv.h / 360, hsv.s / 100, hsv.v / 100).map((v) => v * 100);
return `hsl(${hsl[0] * 3.6}deg, ${hsl[1]}%, ${
hsl[2] < loweLight ? loweLight : hsl[2] > upperLight ? upperLight : hsl[2]
}%)`;
};
| 27.681818 | 113 | 0.537274 | 96 | 14 | 0 | 30 | 43 | 0 | 5 | 0 | 33 | 0 | 0 | 5.857143 | 1,369 | 0.03214 | 0.03141 | 0 | 0 | 0 | 0 | 0.37931 | 0.348679 | export const ConvertIntColorToHex = (color, alpha?) => {
return `#${color.toString(16)}` + (alpha ? SetHexAlpha(alpha) : "");
};
export /* Example usages of 'SetHexAlpha' are shown below:
alpha ? SetHexAlpha(alpha) : "";
alpha ? SetHexAlpha(a / 255) : "";
*/
const SetHexAlpha = (alpha) => {
if (alpha > 1 || alpha < 0 || isNaN(alpha)) {
throw Error("alpha must be between 0 and 1");
}
return Math.ceil(255 * alpha)
.toString(16)
.toUpperCase();
};
export const ConvertRGBAToDecimal = (r, g, b, a) =>
(r << 24) | (g << 16) | (b << 8) | a;
export const ConvertDecimalRGBAToString = (num) => {
const r = (num >>> 24) & 0xff;
const g = (num >>> 16) & 0xff;
const b = (num >>> 8) & 0xff;
const a = num & 0xff;
return `rgba(${r}, ${g}, ${b}, ${(a / 255).toFixed(3)})`;
};
export const ConvertHexToRGB = (hex) => {
const t = parseInt(hex?.slice(1) ?? "0", 16);
const r = (t >> 16) & 255;
const g = (t >> 8) & 255;
const b = t & 255;
return [r, g, b];
};
export const ConvertDecimalToHex = (num, alpha?) => {
const r = (num >>> 24) & 0xff;
const g = (num >>> 16) & 0xff;
const b = (num >>> 8) & 0xff;
const a = num & 0xff;
return "#" + ((1 << 24) + (r << 16) + (g << 8) + b).toString(16).slice(1) + (alpha ? SetHexAlpha(a / 255) : "");
};
export const ConvertIntToHSVColor = (color) => {
const r = color >> 16;
const g = (color >> 8) & ((1 << 8) - 1);
const b = color & ((1 << 8) - 1);
return ConvertRGBToHSVColor(r, g, b);
};
export /* Example usages of 'ConvertRGBToHSVColor' are shown below:
ConvertRGBToHSVColor(r, g, b);
*/
const ConvertRGBToHSVColor = (r, g, b) => {
const rabs = r / 255;
const gabs = g / 255;
const babs = b / 255;
const v = Math.max(rabs, gabs, babs);
const diff = v - Math.min(rabs, gabs, babs);
/* Example usages of 'diffc' are shown below:
diffc(rabs);
diffc(gabs);
diffc(babs);
*/
const diffc = (c) => (v - c) / 6 / diff + 1 / 2;
/* Example usages of 'percentRoundFn' are shown below:
percentRoundFn(s * 100);
percentRoundFn(v * 100);
*/
const percentRoundFn = (num) => Math.round(num * 100) / 100;
let h = 0;
let s = 0;
if (diff === 0) {
h = s = 0;
} else {
s = diff / v;
const rr = diffc(rabs);
const gg = diffc(gabs);
const bb = diffc(babs);
if (rabs === v) {
h = bb - gg;
} else if (gabs === v) {
h = 1 / 3 + rr - bb;
} else if (babs === v) {
h = 2 / 3 + gg - rr;
}
if (h < 0) {
h += 1;
} else if (h > 1) {
h -= 1;
}
}
return {
h: Math.round(h * 360),
s: percentRoundFn(s * 100),
v: percentRoundFn(v * 100),
};
};
export /* Example usages of 'hsv2hsl' are shown below:
hsv2hsl(hsv.h / 360, hsv.s / 100, hsv.v / 100).map((v) => v * 100);
*/
const hsv2hsl = (h, s, v, l = v - (v * s) / 2, m = Math.min(l, 1 - l)) => [
h,
m ? (v - l) / m : 0,
l,
];
export const hsl2hsv = (h, s, l, v = s * Math.min(l, 1 - l) + l) => [
h,
v ? 2 - (2 * l) / v : 0,
v,
];
export const NormalizeColor = (color, loweLight, upperLight) => {
const r = color >> 16;
const g = (color >> 8) & ((1 << 8) - 1);
const b = color & ((1 << 8) - 1);
const hsv = ConvertRGBToHSVColor(r, g, b);
const hsl = hsv2hsl(hsv.h / 360, hsv.s / 100, hsv.v / 100).map((v) => v * 100);
return `hsl(${hsl[0] * 3.6}deg, ${hsl[1]}%, ${
hsl[2] < loweLight ? loweLight : hsl[2] > upperLight ? upperLight : hsl[2]
}%)`;
};
|
a674ca2d53758362beae531b93f4d5c527eb5ec1 | 7,139 | ts | TypeScript | src/app/script/klecks/image-operations/flood-fill.ts | satopian/klecks | aa1026c59ab925a275c330b3bbe552063c8c810f | [
"MIT"
] | 11 | 2022-01-29T22:46:39.000Z | 2022-03-28T15:42:22.000Z | src/app/script/klecks/image-operations/flood-fill.ts | satopian/klecks | aa1026c59ab925a275c330b3bbe552063c8c810f | [
"MIT"
] | 14 | 2022-02-13T21:52:23.000Z | 2022-03-31T16:07:47.000Z | src/app/script/klecks/image-operations/flood-fill.ts | satopian/klecks | aa1026c59ab925a275c330b3bbe552063c8c810f | [
"MIT"
] | 7 | 2022-02-04T23:51:42.000Z | 2022-03-21T12:31:44.000Z |
/**
* Flood fill. Tried https://github.com/binarymax/floodfill.js/ but it implemented tolerance wrong, and had bugs.
* So, my own implementation. can handle tolerance, grow, opacity.
* Needs to be optimized.
*/
/**
* Set values in data within rect to 254, unless they're 255
*
* @param data Uint8Array
* @param width int
* @param x0 int
* @param y0 int
* @param x1 int >x0
* @param y1 int >y0
*/
function fillRect(data, width, x0, y0, x1, y1) {
for (let x = x0; x <= x1; x++) {
for (let y = y0; y <= y1; y++) {
if (data[y * width + x] === 255) {
continue;
}
data[y * width + x] = 254;
}
}
}
let mx, my;
/**
* Get index i moved by dX, dY. in array with dimensions width height.
* Returns null if outside bounds.
*
* @param width int
* @param height int
* @param i int
* @param dX int
* @param dY int
* @returns {null|*}
*/
function moveIndex(width, height, i, dX, dY) {
mx = i % width + dX;
my = Math.floor(i / width) + dY;
if (mx < 0 || my < 0 || mx >= width || my >= height) {
return null;
}
return my * width + mx;
}
/**
* If pixel can be filled (within tolerance) will be set 255 and returns true.
* returns false if already filled, or i is null
*
* @param srcArr Uint8Array rgba
* @param targetArr Uint8Array
* @param width int
* @param height int
* @param initRgba rgba
* @param tolerance int 0 - 255
* @param i int - srcArr index
* @returns {boolean}
*/
function testAndFill(srcArr, targetArr, width, height, initRgba, tolerance, i) {
if (i === null || targetArr[i] === 255) {
return false;
}
if (
srcArr[i * 4] === initRgba[0] &&
srcArr[i * 4 + 1] === initRgba[1] &&
srcArr[i * 4 + 2] === initRgba[2] &&
srcArr[i * 4 + 3] === initRgba[3]
) {
targetArr[i] = 255;
return true;
}
if (
tolerance > 0 &&
Math.abs(srcArr[i * 4] - initRgba[0]) <= tolerance &&
Math.abs(srcArr[i * 4 + 1] - initRgba[1]) <= tolerance &&
Math.abs(srcArr[i * 4 + 2] - initRgba[2]) <= tolerance &&
Math.abs(srcArr[i * 4 + 3] - initRgba[3]) <= tolerance
) {
targetArr[i] = 255;
return true;
}
return false;
}
/**
*
* @param srcArr Uint8Array rgba
* @param targetArr Uint8Array
* @param width int
* @param height int
* @param px int
* @param py int
* @param tolerance int 0 - 255
* @param grow int >= 0
* @param isContiguous boolean
*/
function floodFill(srcArr, targetArr, width, height, px, py, tolerance, grow, isContiguous) {
let initRgba = [
srcArr[(py * width + px) * 4],
srcArr[(py * width + px) * 4 + 1],
srcArr[(py * width + px) * 4 + 2],
srcArr[(py * width + px) * 4 + 3]
];
if (isContiguous) {
let q = [];
q.push(py * width + px);
targetArr[py * width + px] = 255;
let i, e;
while (q.length) {
i = q.pop();
// queue up unfilled neighbors
e = moveIndex(width, height, i, -1, 0); // left
testAndFill(srcArr, targetArr, width, height, initRgba, tolerance, e) && q.push(e);
e = moveIndex(width, height, i, 1, 0); // right
testAndFill(srcArr, targetArr, width, height, initRgba, tolerance, e) && q.push(e);
e = moveIndex(width, height, i, 0, -1); // up
testAndFill(srcArr, targetArr, width, height, initRgba, tolerance, e) && q.push(e);
e = moveIndex(width, height, i, 0, 1); // bottom
testAndFill(srcArr, targetArr, width, height, initRgba, tolerance, e) && q.push(e);
}
} else {
for (let i = 0; i < width * height; i++) {
testAndFill(srcArr, targetArr, width, height, initRgba, tolerance, i);
}
}
// grow
if (grow === 0) {
return;
}
// how does it grow? it finds all pixel at the edge.
// then depending on what kind of edge it is, it draws a rectangle into target
// the rectangle has the value 254, or else it mess it all up.
// after it's all done, replaces it with 255
let x0, x1, y0, y1;
let l, tl, t, tr, r, br, b, bl; // left, top left, top, top right, etc.
for (let x = 0; x < width; x++) {
for (let y = 0; y < height; y++) {
if (targetArr[y * width + x] !== 255) {
continue;
}
// bounds of rectangle
x0 = x;
x1 = x;
y0 = y;
y1 = y;
l = targetArr[(y) * width + x - 1] !== 255;
tl = targetArr[(y - 1) * width + x - 1] !== 255;
t = targetArr[(y - 1) * width + x] !== 255;
tr = targetArr[(y - 1) * width + x + 1] !== 255;
r = targetArr[(y) * width + x + 1] !== 255;
br = targetArr[(y + 1) * width + x + 1] !== 255;
b = targetArr[(y + 1) * width + x] !== 255;
bl = targetArr[(y + 1) * width + x - 1] !== 255;
if (l) { // left
x0 = x - grow;
}
if (l && tl && t) { // top left
x0 = x - grow;
y0 = y - grow;
}
if (t) { // top
y0 = Math.min(y0, y - grow);
}
if (t && tr && r) { // top right
y0 = Math.min(y0, y - grow);
x1 = x + grow;
}
if (r) { // right
x1 = Math.max(x1, x + 1 * grow);
}
if (r && br && b) { // bottom right
x1 = Math.max(x1, x + 1 * grow);
y1 = Math.max(y1, y + 1 * grow);
}
if (b) { // bottom
y1 = Math.max(y1, y + 1 * grow);
}
if (b && bl && l) { // bottom left
x0 = Math.min(x0, x - 1 * grow);
y1 = Math.max(y1, y + 1 * grow);
}
if (!l && !tl && !t && !tr && !r && !br && !b && !bl) {
continue;
}
fillRect(
targetArr,
width,
Math.max(0, x0),
Math.max(0, y0),
Math.min(width - 1, x1),
Math.min(height - 1, y1)
);
}
}
for (let i = 0; i < width * height; i++) {
if (targetArr[i] === 254) {
targetArr[i] = 255;
}
}
}
/**
* Does flood fill, and returns that. an array - 0 not filled. 255 filled
*
* returns {
* data: Uint8Array
* }
*
* @param rgbaArr Uint8Array rgba
* @param width int
* @param height int
* @param x int
* @param y int
* @param tolerance int 0 - 255
* @param grow int >= 0
* @param isContiguous boolean
* @returns {{data: Uint8Array}}
*/
export function floodFillBits(rgbaArr, width, height, x, y, tolerance, grow, isContiguous) {
x = Math.round(x);
y = Math.round(y);
let resultArr = new Uint8Array(new ArrayBuffer(width * height));
floodFill(rgbaArr, resultArr, width, height, x, y, tolerance, grow, isContiguous);
return {
data: resultArr
}
}
| 27.563707 | 113 | 0.48228 | 150 | 5 | 0 | 35 | 25 | 0 | 4 | 0 | 0 | 0 | 0 | 27.8 | 2,342 | 0.017079 | 0.010675 | 0 | 0 | 0 | 0 | 0 | 0.245992 |
/**
* Flood fill. Tried https://github.com/binarymax/floodfill.js/ but it implemented tolerance wrong, and had bugs.
* So, my own implementation. can handle tolerance, grow, opacity.
* Needs to be optimized.
*/
/**
* Set values in data within rect to 254, unless they're 255
*
* @param data Uint8Array
* @param width int
* @param x0 int
* @param y0 int
* @param x1 int >x0
* @param y1 int >y0
*/
/* Example usages of 'fillRect' are shown below:
fillRect(targetArr, width, Math.max(0, x0), Math.max(0, y0), Math.min(width - 1, x1), Math.min(height - 1, y1));
*/
function fillRect(data, width, x0, y0, x1, y1) {
for (let x = x0; x <= x1; x++) {
for (let y = y0; y <= y1; y++) {
if (data[y * width + x] === 255) {
continue;
}
data[y * width + x] = 254;
}
}
}
let mx, my;
/**
* Get index i moved by dX, dY. in array with dimensions width height.
* Returns null if outside bounds.
*
* @param width int
* @param height int
* @param i int
* @param dX int
* @param dY int
* @returns {null|*}
*/
/* Example usages of 'moveIndex' are shown below:
// queue up unfilled neighbors
e = moveIndex(width, height, i, -1, 0);
e = moveIndex(width, height, i, 1, 0);
e = moveIndex(width, height, i, 0, -1);
e = moveIndex(width, height, i, 0, 1);
*/
function moveIndex(width, height, i, dX, dY) {
mx = i % width + dX;
my = Math.floor(i / width) + dY;
if (mx < 0 || my < 0 || mx >= width || my >= height) {
return null;
}
return my * width + mx;
}
/**
* If pixel can be filled (within tolerance) will be set 255 and returns true.
* returns false if already filled, or i is null
*
* @param srcArr Uint8Array rgba
* @param targetArr Uint8Array
* @param width int
* @param height int
* @param initRgba rgba
* @param tolerance int 0 - 255
* @param i int - srcArr index
* @returns {boolean}
*/
/* Example usages of 'testAndFill' are shown below:
testAndFill(srcArr, targetArr, width, height, initRgba, tolerance, e) && q.push(e);
testAndFill(srcArr, targetArr, width, height, initRgba, tolerance, i);
*/
function testAndFill(srcArr, targetArr, width, height, initRgba, tolerance, i) {
if (i === null || targetArr[i] === 255) {
return false;
}
if (
srcArr[i * 4] === initRgba[0] &&
srcArr[i * 4 + 1] === initRgba[1] &&
srcArr[i * 4 + 2] === initRgba[2] &&
srcArr[i * 4 + 3] === initRgba[3]
) {
targetArr[i] = 255;
return true;
}
if (
tolerance > 0 &&
Math.abs(srcArr[i * 4] - initRgba[0]) <= tolerance &&
Math.abs(srcArr[i * 4 + 1] - initRgba[1]) <= tolerance &&
Math.abs(srcArr[i * 4 + 2] - initRgba[2]) <= tolerance &&
Math.abs(srcArr[i * 4 + 3] - initRgba[3]) <= tolerance
) {
targetArr[i] = 255;
return true;
}
return false;
}
/**
*
* @param srcArr Uint8Array rgba
* @param targetArr Uint8Array
* @param width int
* @param height int
* @param px int
* @param py int
* @param tolerance int 0 - 255
* @param grow int >= 0
* @param isContiguous boolean
*/
/* Example usages of 'floodFill' are shown below:
floodFill(rgbaArr, resultArr, width, height, x, y, tolerance, grow, isContiguous);
*/
function floodFill(srcArr, targetArr, width, height, px, py, tolerance, grow, isContiguous) {
let initRgba = [
srcArr[(py * width + px) * 4],
srcArr[(py * width + px) * 4 + 1],
srcArr[(py * width + px) * 4 + 2],
srcArr[(py * width + px) * 4 + 3]
];
if (isContiguous) {
let q = [];
q.push(py * width + px);
targetArr[py * width + px] = 255;
let i, e;
while (q.length) {
i = q.pop();
// queue up unfilled neighbors
e = moveIndex(width, height, i, -1, 0); // left
testAndFill(srcArr, targetArr, width, height, initRgba, tolerance, e) && q.push(e);
e = moveIndex(width, height, i, 1, 0); // right
testAndFill(srcArr, targetArr, width, height, initRgba, tolerance, e) && q.push(e);
e = moveIndex(width, height, i, 0, -1); // up
testAndFill(srcArr, targetArr, width, height, initRgba, tolerance, e) && q.push(e);
e = moveIndex(width, height, i, 0, 1); // bottom
testAndFill(srcArr, targetArr, width, height, initRgba, tolerance, e) && q.push(e);
}
} else {
for (let i = 0; i < width * height; i++) {
testAndFill(srcArr, targetArr, width, height, initRgba, tolerance, i);
}
}
// grow
if (grow === 0) {
return;
}
// how does it grow? it finds all pixel at the edge.
// then depending on what kind of edge it is, it draws a rectangle into target
// the rectangle has the value 254, or else it mess it all up.
// after it's all done, replaces it with 255
let x0, x1, y0, y1;
let l, tl, t, tr, r, br, b, bl; // left, top left, top, top right, etc.
for (let x = 0; x < width; x++) {
for (let y = 0; y < height; y++) {
if (targetArr[y * width + x] !== 255) {
continue;
}
// bounds of rectangle
x0 = x;
x1 = x;
y0 = y;
y1 = y;
l = targetArr[(y) * width + x - 1] !== 255;
tl = targetArr[(y - 1) * width + x - 1] !== 255;
t = targetArr[(y - 1) * width + x] !== 255;
tr = targetArr[(y - 1) * width + x + 1] !== 255;
r = targetArr[(y) * width + x + 1] !== 255;
br = targetArr[(y + 1) * width + x + 1] !== 255;
b = targetArr[(y + 1) * width + x] !== 255;
bl = targetArr[(y + 1) * width + x - 1] !== 255;
if (l) { // left
x0 = x - grow;
}
if (l && tl && t) { // top left
x0 = x - grow;
y0 = y - grow;
}
if (t) { // top
y0 = Math.min(y0, y - grow);
}
if (t && tr && r) { // top right
y0 = Math.min(y0, y - grow);
x1 = x + grow;
}
if (r) { // right
x1 = Math.max(x1, x + 1 * grow);
}
if (r && br && b) { // bottom right
x1 = Math.max(x1, x + 1 * grow);
y1 = Math.max(y1, y + 1 * grow);
}
if (b) { // bottom
y1 = Math.max(y1, y + 1 * grow);
}
if (b && bl && l) { // bottom left
x0 = Math.min(x0, x - 1 * grow);
y1 = Math.max(y1, y + 1 * grow);
}
if (!l && !tl && !t && !tr && !r && !br && !b && !bl) {
continue;
}
fillRect(
targetArr,
width,
Math.max(0, x0),
Math.max(0, y0),
Math.min(width - 1, x1),
Math.min(height - 1, y1)
);
}
}
for (let i = 0; i < width * height; i++) {
if (targetArr[i] === 254) {
targetArr[i] = 255;
}
}
}
/**
* Does flood fill, and returns that. an array - 0 not filled. 255 filled
*
* returns {
* data: Uint8Array
* }
*
* @param rgbaArr Uint8Array rgba
* @param width int
* @param height int
* @param x int
* @param y int
* @param tolerance int 0 - 255
* @param grow int >= 0
* @param isContiguous boolean
* @returns {{data: Uint8Array}}
*/
export function floodFillBits(rgbaArr, width, height, x, y, tolerance, grow, isContiguous) {
x = Math.round(x);
y = Math.round(y);
let resultArr = new Uint8Array(new ArrayBuffer(width * height));
floodFill(rgbaArr, resultArr, width, height, x, y, tolerance, grow, isContiguous);
return {
data: resultArr
}
}
|
a69d585dc2b6c26d17b76427c1eb6e676c7905ec | 2,158 | ts | TypeScript | src/utils.ts | mame/xterm-pty | 4424b40ad7b5985e217b9aabc74ed3aa3678275b | [
"MIT"
] | 5 | 2022-02-18T10:48:32.000Z | 2022-03-24T18:32:26.000Z | src/utils.ts | mame/xterm-pty | 4424b40ad7b5985e217b9aabc74ed3aa3678275b | [
"MIT"
] | null | null | null | src/utils.ts | mame/xterm-pty | 4424b40ad7b5985e217b9aabc74ed3aa3678275b | [
"MIT"
] | null | null | null | export const BS = 8;
export const TAB = 9;
export const NL = 10;
export const CR = 13;
export const SP = 32;
export const isalnum = (c: number) =>
(0x30 <= c && c <= 0x39) ||
(0x41 <= c && c <= 0x5a) ||
c == 0x5f ||
(0x61 <= c && c <= 0x7a);
export const iscntrl = (c: number) =>
(0x00 <= c && c <= 0x1f && c != 0x09) || c == 0x7f;
export const isUtf8ContinuationByte = (c: number) => (c & 0xc0) == 0x80;
export const tolower = (c: number) => (0x41 <= c && c <= 0x5a ? c + 0x20 : c);
export const toupper = (c: number) => (0x61 <= c && c <= 0x7a ? c - 0x20 : c);
export const utf8BytesToString = (buf: number[]): [string, number[]] => {
let str = "";
let i = 0;
while (i < buf.length) {
const b = buf[i];
let cp;
if (b < 0x80) {
cp = b;
} else if ((b & 0xe0) == 0xc0) {
if (buf.length <= i + 1) break;
cp = (b & 0x1f) << 6;
cp |= buf[++i] & 0x3f;
} else if ((b & 0xf0) == 0xe0) {
if (buf.length <= i + 2) break;
cp = (b & 0x0f) << 12;
cp |= (buf[++i] & 0x3f) << 6;
cp |= buf[++i] & 0x3f;
} else if ((b & 0xf8) == 0xf0) {
if (buf.length <= i + 3) break;
cp = (b & 0x03) << 18;
cp |= (buf[++i] & 0x3f) << 12;
cp |= (buf[++i] & 0x3f) << 6;
cp |= buf[++i] & 0x3f;
} else {
cp = 0xfffe;
}
i++;
str += String.fromCodePoint(cp);
}
return [str, buf.slice(i)];
};
export const stringToUtf8Bytes = (str: string) => {
const bytes: number[] = [];
for (let i = 0; i < str.length; ) {
// eslint-disable-next-line @typescript-eslint/no-non-null-assertion
const cp = str.codePointAt(i)!;
if (cp < 0x80) bytes.push(cp);
else if (cp < 0x800) {
bytes.push(0xc0 | (cp >> 6));
bytes.push(0x80 | (cp & 0x3f));
} else if (cp < 0x10000) {
bytes.push(0xe0 | (cp >> 12));
bytes.push(0x80 | ((cp >> 6) & 0x3f));
bytes.push(0x80 | (cp & 0x3f));
} else {
bytes.push(0xf0 | (cp >> 18));
bytes.push(0x80 | ((cp >> 12) & 0x3f));
bytes.push(0x80 | ((cp >> 6) & 0x3f));
bytes.push(0x80 | (cp & 0x3f));
}
i += cp >= 0x10000 ? 2 : 1;
}
return bytes;
};
| 29.561644 | 78 | 0.483781 | 68 | 7 | 0 | 7 | 19 | 0 | 0 | 0 | 10 | 0 | 0 | 8.142857 | 969 | 0.014448 | 0.019608 | 0 | 0 | 0 | 0 | 0.30303 | 0.267522 | export const BS = 8;
export const TAB = 9;
export const NL = 10;
export const CR = 13;
export const SP = 32;
export const isalnum = (c) =>
(0x30 <= c && c <= 0x39) ||
(0x41 <= c && c <= 0x5a) ||
c == 0x5f ||
(0x61 <= c && c <= 0x7a);
export const iscntrl = (c) =>
(0x00 <= c && c <= 0x1f && c != 0x09) || c == 0x7f;
export const isUtf8ContinuationByte = (c) => (c & 0xc0) == 0x80;
export const tolower = (c) => (0x41 <= c && c <= 0x5a ? c + 0x20 : c);
export const toupper = (c) => (0x61 <= c && c <= 0x7a ? c - 0x20 : c);
export const utf8BytesToString = (buf) => {
let str = "";
let i = 0;
while (i < buf.length) {
const b = buf[i];
let cp;
if (b < 0x80) {
cp = b;
} else if ((b & 0xe0) == 0xc0) {
if (buf.length <= i + 1) break;
cp = (b & 0x1f) << 6;
cp |= buf[++i] & 0x3f;
} else if ((b & 0xf0) == 0xe0) {
if (buf.length <= i + 2) break;
cp = (b & 0x0f) << 12;
cp |= (buf[++i] & 0x3f) << 6;
cp |= buf[++i] & 0x3f;
} else if ((b & 0xf8) == 0xf0) {
if (buf.length <= i + 3) break;
cp = (b & 0x03) << 18;
cp |= (buf[++i] & 0x3f) << 12;
cp |= (buf[++i] & 0x3f) << 6;
cp |= buf[++i] & 0x3f;
} else {
cp = 0xfffe;
}
i++;
str += String.fromCodePoint(cp);
}
return [str, buf.slice(i)];
};
export const stringToUtf8Bytes = (str) => {
const bytes = [];
for (let i = 0; i < str.length; ) {
// eslint-disable-next-line @typescript-eslint/no-non-null-assertion
const cp = str.codePointAt(i)!;
if (cp < 0x80) bytes.push(cp);
else if (cp < 0x800) {
bytes.push(0xc0 | (cp >> 6));
bytes.push(0x80 | (cp & 0x3f));
} else if (cp < 0x10000) {
bytes.push(0xe0 | (cp >> 12));
bytes.push(0x80 | ((cp >> 6) & 0x3f));
bytes.push(0x80 | (cp & 0x3f));
} else {
bytes.push(0xf0 | (cp >> 18));
bytes.push(0x80 | ((cp >> 12) & 0x3f));
bytes.push(0x80 | ((cp >> 6) & 0x3f));
bytes.push(0x80 | (cp & 0x3f));
}
i += cp >= 0x10000 ? 2 : 1;
}
return bytes;
};
|
a6f9aec61c153682dc872f7fdabd8d491ac1618e | 3,775 | ts | TypeScript | day-24.ts | dubzzz/advent-of-pbt-2021 | 7b324588cc582bea60155cc922778f39d503a818 | [
"MIT"
] | 2 | 2022-03-14T00:03:38.000Z | 2022-03-14T11:51:27.000Z | day-24.ts | dubzzz/advent-of-pbt-2021 | 7b324588cc582bea60155cc922778f39d503a818 | [
"MIT"
] | null | null | null | day-24.ts | dubzzz/advent-of-pbt-2021 | 7b324588cc582bea60155cc922778f39d503a818 | [
"MIT"
] | null | null | null | export type Task = {
taskId: number;
estimatedTime: number;
dependsOnTasks: number[];
};
export type ScheduledTask = {
taskId: number;
start: number;
finish: number;
};
/**
* Christmas is coming! Santa Claus and his elves have to produce all the presents before the D-day.
* In order to be as efficient as possible they want to schedule and parallelize as many tasks as possible.
*
* So they come up with a precise list of all the tasks including their dependencies and the time they will take.
* Now we have to suggest the ideal timetable to achieve this goal.
*
* @param tasks - Define the tasks to achieve.
* Tasks should not define circular dependencies, one task cannot be dependant on itself (even indirectly).
*
* The following implementation is based on the one suggested at https://algs4.cs.princeton.edu/44sp/CPM.java.html.
* It solves the "parallel precedence-constrained job scheduling problem".
*/
export function christmasFactorySchedule(tasks: Task[]): ScheduledTask[] {
const g = buildDirectedGraphFromTasks(tasks);
const distTo = computeAcyclicLongestPath(g);
return tasks.map(
(task): ScheduledTask => ({
taskId: task.taskId,
start: distTo[g.startVertexFor(task.taskId)],
finish: distTo[g.finishVertexFor(task.taskId)],
})
);
}
type InternalTask = {
estimatedTime: number;
dependsOnTasks: number[];
};
type DirectedEdge = {
from: number;
to: number;
weight: number;
};
type DirectedGraph = {
source: number;
startVertexFor: (taskId: number) => number;
finishVertexFor: (taskId: number) => number;
numVertex: number;
edges: DirectedEdge[];
};
function buildDirectedGraphFromTasks(tasks: Task[]): DirectedGraph {
const n = tasks.length;
const source = 2 * n;
const sink = 2 * n + 1;
const edges = tasks
.map(
(task): InternalTask => ({
estimatedTime: task.estimatedTime,
dependsOnTasks: task.dependsOnTasks.map((taskId) =>
tasks.findIndex((t) => t.taskId === taskId)
),
})
)
.flatMap((task, index): DirectedEdge[] => {
return [
{ from: source, to: index, weight: 0 },
{ from: index + n, to: sink, weight: 0 },
{ from: index, to: index + n, weight: task.estimatedTime },
//...task.dependsOnTasks.map((dependsOnTaskId) => ({ from: index + n, to: dependsOnTaskId, weight: 0 })),
...task.dependsOnTasks.map((dependsOnTaskId) => ({
from: dependsOnTaskId + n,
to: index,
weight: 0,
})),
];
});
return {
numVertex: 2 * n + 2,
edges,
source,
startVertexFor: (taskId) => tasks.findIndex((t) => t.taskId === taskId),
finishVertexFor: (taskId) =>
tasks.findIndex((t) => t.taskId === taskId) + n,
};
}
function computeAcyclicLongestPath(g: DirectedGraph): number[] {
const distTo: number[] = Array(g.numVertex).fill(Number.NEGATIVE_INFINITY);
distTo[g.source] = 0;
for (const v of topologicalOrder(g)) {
for (const e of g.edges.filter((e) => e.from === v)) {
const w = e.to;
if (distTo[w] < distTo[v] + e.weight) {
distTo[w] = distTo[v] + e.weight;
}
}
}
return distTo;
}
function topologicalOrder(g: DirectedGraph): number[] {
const marked = new Set<number>();
const postOrder: number[] = [];
for (let v = 0; v !== g.numVertex; ++v) {
if (!marked.has(v)) {
postDfsInternal(g, v, marked, postOrder);
}
}
return postOrder.reverse();
}
function postDfsInternal(
g: DirectedGraph,
v: number,
marked: Set<number>,
acc: number[]
): void {
marked.add(v);
for (const adj of g.edges.filter((e) => e.from === v)) {
if (!marked.has(adj.to)) {
postDfsInternal(g, adj.to, marked, acc);
}
}
acc.push(v);
}
| 27.962963 | 115 | 0.633113 | 108 | 17 | 0 | 21 | 11 | 16 | 4 | 0 | 26 | 5 | 0 | 5.941176 | 1,119 | 0.033959 | 0.00983 | 0.014298 | 0.004468 | 0 | 0 | 0.4 | 0.289343 | export type Task = {
taskId;
estimatedTime;
dependsOnTasks;
};
export type ScheduledTask = {
taskId;
start;
finish;
};
/**
* Christmas is coming! Santa Claus and his elves have to produce all the presents before the D-day.
* In order to be as efficient as possible they want to schedule and parallelize as many tasks as possible.
*
* So they come up with a precise list of all the tasks including their dependencies and the time they will take.
* Now we have to suggest the ideal timetable to achieve this goal.
*
* @param tasks - Define the tasks to achieve.
* Tasks should not define circular dependencies, one task cannot be dependant on itself (even indirectly).
*
* The following implementation is based on the one suggested at https://algs4.cs.princeton.edu/44sp/CPM.java.html.
* It solves the "parallel precedence-constrained job scheduling problem".
*/
export function christmasFactorySchedule(tasks) {
const g = buildDirectedGraphFromTasks(tasks);
const distTo = computeAcyclicLongestPath(g);
return tasks.map(
(task) => ({
taskId: task.taskId,
start: distTo[g.startVertexFor(task.taskId)],
finish: distTo[g.finishVertexFor(task.taskId)],
})
);
}
type InternalTask = {
estimatedTime;
dependsOnTasks;
};
type DirectedEdge = {
from;
to;
weight;
};
type DirectedGraph = {
source;
startVertexFor;
finishVertexFor;
numVertex;
edges;
};
/* Example usages of 'buildDirectedGraphFromTasks' are shown below:
buildDirectedGraphFromTasks(tasks);
*/
function buildDirectedGraphFromTasks(tasks) {
const n = tasks.length;
const source = 2 * n;
const sink = 2 * n + 1;
const edges = tasks
.map(
(task) => ({
estimatedTime: task.estimatedTime,
dependsOnTasks: task.dependsOnTasks.map((taskId) =>
tasks.findIndex((t) => t.taskId === taskId)
),
})
)
.flatMap((task, index) => {
return [
{ from: source, to: index, weight: 0 },
{ from: index + n, to: sink, weight: 0 },
{ from: index, to: index + n, weight: task.estimatedTime },
//...task.dependsOnTasks.map((dependsOnTaskId) => ({ from: index + n, to: dependsOnTaskId, weight: 0 })),
...task.dependsOnTasks.map((dependsOnTaskId) => ({
from: dependsOnTaskId + n,
to: index,
weight: 0,
})),
];
});
return {
numVertex: 2 * n + 2,
edges,
source,
startVertexFor: (taskId) => tasks.findIndex((t) => t.taskId === taskId),
finishVertexFor: (taskId) =>
tasks.findIndex((t) => t.taskId === taskId) + n,
};
}
/* Example usages of 'computeAcyclicLongestPath' are shown below:
computeAcyclicLongestPath(g);
*/
function computeAcyclicLongestPath(g) {
const distTo = Array(g.numVertex).fill(Number.NEGATIVE_INFINITY);
distTo[g.source] = 0;
for (const v of topologicalOrder(g)) {
for (const e of g.edges.filter((e) => e.from === v)) {
const w = e.to;
if (distTo[w] < distTo[v] + e.weight) {
distTo[w] = distTo[v] + e.weight;
}
}
}
return distTo;
}
/* Example usages of 'topologicalOrder' are shown below:
topologicalOrder(g);
*/
function topologicalOrder(g) {
const marked = new Set<number>();
const postOrder = [];
for (let v = 0; v !== g.numVertex; ++v) {
if (!marked.has(v)) {
postDfsInternal(g, v, marked, postOrder);
}
}
return postOrder.reverse();
}
/* Example usages of 'postDfsInternal' are shown below:
postDfsInternal(g, v, marked, postOrder);
postDfsInternal(g, adj.to, marked, acc);
*/
function postDfsInternal(
g,
v,
marked,
acc
) {
marked.add(v);
for (const adj of g.edges.filter((e) => e.from === v)) {
if (!marked.has(adj.to)) {
postDfsInternal(g, adj.to, marked, acc);
}
}
acc.push(v);
}
|
98000e7ea7d9f88c6c0f12d701d19d81441d0dd5 | 1,676 | ts | TypeScript | src/app/ChymallServices/helpers/datetranslate.ts | Natdiv/chymall-app | bc52466ffe7f49187bfe1d13c5beb49fd69d3232 | [
"MIT"
] | 1 | 2022-03-06T22:11:43.000Z | 2022-03-06T22:11:43.000Z | src/app/ChymallServices/helpers/datetranslate.ts | Natdiv/chymall-app | bc52466ffe7f49187bfe1d13c5beb49fd69d3232 | [
"MIT"
] | 4 | 2022-02-13T23:15:16.000Z | 2022-03-02T10:09:20.000Z | src/app/ChymallServices/helpers/datetranslate.ts | Natdiv/chymall-app | bc52466ffe7f49187bfe1d13c5beb49fd69d3232 | [
"MIT"
] | null | null | null | export class Datetranslate {
public static getFrenchDay(date: Date) {
const day = date.getDay();
switch (day) {
case 1:
return 'Lundi';
case 2:
return 'Mardi';
case 3:
return 'Mercredi';
case 4:
return 'Jeudi';
case 5:
return 'Vendredi';
case 6:
return 'Samedi';
case 7:
return 'Dimanche';
default:
return '';
}
}
public static getFrenchMonth(date: Date) {
const month = date.getMonth();
switch (month) {
case 0:
return 'Janvier';
case 1:
return 'Février';
case 2:
return 'Mars';
case 3:
return 'Avril';
case 4:
return 'Mai';
case 5:
return 'Juin';
case 6:
return 'Juillet';
case 7:
return 'Août';
case 8:
return 'Septembre';
case 9:
return 'Octobre';
case 10:
return 'Novembre';
case 11:
return 'Décembre';
default:
return '';
}
}
public static formatInFrench(date: Date) {
const month = Datetranslate.getFrenchMonth(date);
const dayweek = Datetranslate.getFrenchDay(date);
const chaine = dayweek + ' ' + date.getDate() + ' ' + month + ' ' + date.getFullYear();
return chaine;
}
}
| 26.603175 | 95 | 0.406921 | 60 | 3 | 0 | 3 | 5 | 0 | 2 | 0 | 0 | 1 | 0 | 17.333333 | 390 | 0.015385 | 0.012821 | 0 | 0.002564 | 0 | 0 | 0 | 0.252615 | export class Datetranslate {
public static getFrenchDay(date) {
const day = date.getDay();
switch (day) {
case 1:
return 'Lundi';
case 2:
return 'Mardi';
case 3:
return 'Mercredi';
case 4:
return 'Jeudi';
case 5:
return 'Vendredi';
case 6:
return 'Samedi';
case 7:
return 'Dimanche';
default:
return '';
}
}
public static getFrenchMonth(date) {
const month = date.getMonth();
switch (month) {
case 0:
return 'Janvier';
case 1:
return 'Février';
case 2:
return 'Mars';
case 3:
return 'Avril';
case 4:
return 'Mai';
case 5:
return 'Juin';
case 6:
return 'Juillet';
case 7:
return 'Août';
case 8:
return 'Septembre';
case 9:
return 'Octobre';
case 10:
return 'Novembre';
case 11:
return 'Décembre';
default:
return '';
}
}
public static formatInFrench(date) {
const month = Datetranslate.getFrenchMonth(date);
const dayweek = Datetranslate.getFrenchDay(date);
const chaine = dayweek + ' ' + date.getDate() + ' ' + month + ' ' + date.getFullYear();
return chaine;
}
}
|
98134d8b39c30fa1b56afbccd90b832c3f8eb635 | 2,526 | ts | TypeScript | src/react/TransformStyles.ts | dipeshrai123/re-motion | 5b768bb54c8806666f3ffb9ff6782df4381fca95 | [
"MIT"
] | 1 | 2022-03-24T13:46:32.000Z | 2022-03-24T13:46:32.000Z | src/react/TransformStyles.ts | dipeshrai123/re-motion | 5b768bb54c8806666f3ffb9ff6782df4381fca95 | [
"MIT"
] | 1 | 2022-02-28T12:04:00.000Z | 2022-02-28T12:04:00.000Z | src/react/TransformStyles.ts | dipeshrai123/re-motion | 5b768bb54c8806666f3ffb9ff6782df4381fca95 | [
"MIT"
] | null | null | null | /**
* style keys which can be accepted by animated component
*/
export const styleTrasformKeys = [
'perspective',
'translate',
'translateX',
'translateY',
'translateZ',
'scale',
'scaleX',
'scaleY',
'scaleZ',
'rotate',
'rotateX',
'rotateY',
'rotateZ',
'skew',
'skewX',
'skewY',
] as const;
function splitCSSValueAndUnit(value: string) {
const valueMatch = value.match(/(-)?(\d+.)?\d+/g);
const unitMatch = value.match(
/px|rem|em|ex|%|cm|mm|in|pt|pc|ch|vh|vw|vmin|vmax/
);
return {
value: Number(valueMatch),
unit: unitMatch && unitMatch[0],
};
}
// get unit of transform style property
function getValueUnit(property: string, value: string) {
let unit;
const splitValue = splitCSSValueAndUnit(String(value)).value;
const splitUnit = splitCSSValueAndUnit(String(value)).unit;
// if string value is passed with unit then split it
if (splitUnit) {
return { value: splitValue, unit: splitUnit };
}
if (
property.indexOf('translate') !== -1 ||
property.indexOf('perspective') !== -1
) {
unit = 'px';
} else if (property.indexOf('scale') !== -1) {
unit = '';
} else if (
property.indexOf('rotate') !== -1 ||
property.indexOf('skew') !== -1
) {
unit = 'deg';
}
return { value, unit };
}
function getTransformValueWithUnits(property: string, value: string) {
const valueUnit = getValueUnit(property, value);
if (
property.indexOf('X') !== -1 ||
property.indexOf('Y') !== -1 ||
property.indexOf('Z') !== -1 ||
property.indexOf('perspective') !== -1 ||
property.indexOf('rotate') !== -1 ||
property.indexOf('skew') !== -1
) {
// axis value
return `${property}(${valueUnit.value}${valueUnit.unit})`;
} else if (
property.indexOf('translate') !== -1 ||
property.indexOf('scale') !== -1
) {
// two parameter value
return `${property}(${valueUnit.value}${valueUnit.unit}, ${valueUnit.value}${valueUnit.unit})`;
} else {
throw new Error(`Error! Property '${property}' cannot be transformed`);
}
}
/**
* getTransform function returns transform string from style object
*/
export function getTransform(style: any) {
const styleKeys: any = Object.keys(style);
return styleKeys
.map(function (styleProp: string) {
const value = style[styleProp];
return getTransformValueWithUnits(styleProp, value);
})
.reduce(function (transform: string, value: number) {
return (transform += ` ${value}`);
}, '')
.trim();
}
| 24.057143 | 99 | 0.617577 | 82 | 6 | 0 | 9 | 9 | 0 | 3 | 2 | 8 | 0 | 1 | 9.833333 | 717 | 0.020921 | 0.012552 | 0 | 0 | 0.001395 | 0.083333 | 0.333333 | 0.258817 | /**
* style keys which can be accepted by animated component
*/
export const styleTrasformKeys = [
'perspective',
'translate',
'translateX',
'translateY',
'translateZ',
'scale',
'scaleX',
'scaleY',
'scaleZ',
'rotate',
'rotateX',
'rotateY',
'rotateZ',
'skew',
'skewX',
'skewY',
] as const;
/* Example usages of 'splitCSSValueAndUnit' are shown below:
splitCSSValueAndUnit(String(value)).value;
splitCSSValueAndUnit(String(value)).unit;
*/
function splitCSSValueAndUnit(value) {
const valueMatch = value.match(/(-)?(\d+.)?\d+/g);
const unitMatch = value.match(
/px|rem|em|ex|%|cm|mm|in|pt|pc|ch|vh|vw|vmin|vmax/
);
return {
value: Number(valueMatch),
unit: unitMatch && unitMatch[0],
};
}
// get unit of transform style property
/* Example usages of 'getValueUnit' are shown below:
getValueUnit(property, value);
*/
function getValueUnit(property, value) {
let unit;
const splitValue = splitCSSValueAndUnit(String(value)).value;
const splitUnit = splitCSSValueAndUnit(String(value)).unit;
// if string value is passed with unit then split it
if (splitUnit) {
return { value: splitValue, unit: splitUnit };
}
if (
property.indexOf('translate') !== -1 ||
property.indexOf('perspective') !== -1
) {
unit = 'px';
} else if (property.indexOf('scale') !== -1) {
unit = '';
} else if (
property.indexOf('rotate') !== -1 ||
property.indexOf('skew') !== -1
) {
unit = 'deg';
}
return { value, unit };
}
/* Example usages of 'getTransformValueWithUnits' are shown below:
getTransformValueWithUnits(styleProp, value);
*/
function getTransformValueWithUnits(property, value) {
const valueUnit = getValueUnit(property, value);
if (
property.indexOf('X') !== -1 ||
property.indexOf('Y') !== -1 ||
property.indexOf('Z') !== -1 ||
property.indexOf('perspective') !== -1 ||
property.indexOf('rotate') !== -1 ||
property.indexOf('skew') !== -1
) {
// axis value
return `${property}(${valueUnit.value}${valueUnit.unit})`;
} else if (
property.indexOf('translate') !== -1 ||
property.indexOf('scale') !== -1
) {
// two parameter value
return `${property}(${valueUnit.value}${valueUnit.unit}, ${valueUnit.value}${valueUnit.unit})`;
} else {
throw new Error(`Error! Property '${property}' cannot be transformed`);
}
}
/**
* getTransform function returns transform string from style object
*/
export function getTransform(style) {
const styleKeys = Object.keys(style);
return styleKeys
.map(function (styleProp) {
const value = style[styleProp];
return getTransformValueWithUnits(styleProp, value);
})
.reduce(function (transform, value) {
return (transform += ` ${value}`);
}, '')
.trim();
}
|
9824df1e1ab70908c6c3c952d7f8ed237842e242 | 3,453 | ts | TypeScript | src/command/tokenize.ts | bridge-core/common-utils | a3be7ee0c169667c73ec93735812f7cc044a32a3 | [
"MIT"
] | null | null | null | src/command/tokenize.ts | bridge-core/common-utils | a3be7ee0c169667c73ec93735812f7cc044a32a3 | [
"MIT"
] | null | null | null | src/command/tokenize.ts | bridge-core/common-utils | a3be7ee0c169667c73ec93735812f7cc044a32a3 | [
"MIT"
] | 1 | 2022-01-20T18:35:59.000Z | 2022-01-20T18:35:59.000Z | /**
* Tokenize a Minecraft command
* @param command
* @returns
*/
export function tokenizeCommand(command: string) {
let curlyBrackets = 0
let squareBrackets = 0
let inQuotes = false
let i = 0
let wordStart = 0
let word = ''
let tokens = []
while (i < command.length) {
if (
(command[i] === '^' && word[0] === '^') ||
(command[i] === '~' && word[0] === '~')
) {
tokens.push({
startColumn: wordStart,
endColumn: i,
word,
})
wordStart = i + 1
word = command[i]
} else if (command[i] === '"') {
word += command[i]
if (inQuotes) {
tokens.push({
startColumn: wordStart,
endColumn: i,
word,
})
wordStart = i + 1
word = ''
}
inQuotes = !inQuotes
} else if (command[i] === ' ' || command[i] === '\t') {
if (inQuotes) {
word += command[i]
i++
continue
}
if (curlyBrackets === 0 && squareBrackets === 0 && word !== '') {
tokens.push({
startColumn: wordStart,
endColumn: i,
word,
})
wordStart = i + 1
word = ''
}
} else {
if (command[i] === '{') {
curlyBrackets++
} else if (command[i] === '}') {
curlyBrackets--
} else if (command[i] === '[') {
squareBrackets++
} else if (command[i] === ']') {
squareBrackets--
}
if (command[i].trim() !== '') word += command[i]
}
i++
}
tokens.push({
startColumn: wordStart,
endColumn: i,
word,
})
return { tokens }
}
/**
* Tokenize target selectors that may appear inside of Minecraft's commands
* @param targetSelector
*
* @example "@a[tag=test]" > [{ startColumn: ..., endColumn: ..., word: "tag" }, { startColumn: ..., endColumn: ..., word: "=" }, { startColumn: ..., endColumn: ..., word: "test" }]
* @example "@a[tag=test,tag2=test2]" > [{ startColumn: ..., endColumn: ..., word: "tag" }, { startColumn: ..., endColumn: ..., word: "=" }, { startColumn: ..., endColumn: ..., word: "test" }, { startColumn: ..., endColumn: ..., word: "," }, { startColumn: ..., endColumn: ..., word: "tag2" }, { startColumn: ..., endColumn: ..., word: "=" }, { startColumn: ..., endColumn: ..., word: "test2" }]
*/
export function tokenizeTargetSelector(targetSelector: string, wordOffset = 0) {
let i = 0
let wordStart = 0
let word = ''
let tokens = []
while (i < targetSelector.length) {
// TODO: Properly support advanced score selector: "scores={something=..1,something_else=0..2}"
if (targetSelector[i] === '=') {
tokens.push({
startColumn: wordStart + wordOffset,
endColumn: i + wordOffset,
word,
})
wordStart = i + 1
word = ''
if (targetSelector[i + 1] === '!') {
tokens.push({
startColumn: i + wordOffset,
endColumn: wordStart + wordOffset + 1,
word: '=!',
})
i++
wordStart++
} else {
tokens.push({
startColumn: i + wordOffset,
endColumn: wordStart + wordOffset,
word: '=',
})
}
} else if (targetSelector[i] === ',') {
tokens.push({
startColumn: wordStart + wordOffset,
endColumn: i + wordOffset,
word,
})
wordStart = i + 1
word = ''
tokens.push({
startColumn: i + wordOffset,
endColumn: wordStart + wordOffset,
word: ',',
})
} else {
if (targetSelector[i].trim() === '' && wordStart === i) wordStart++
word += targetSelector[i].trim()
}
i++
}
tokens.push({
startColumn: wordStart + wordOffset,
endColumn: i + wordOffset,
word,
})
return { tokens }
}
| 22.422078 | 395 | 0.545613 | 123 | 2 | 0 | 3 | 11 | 0 | 0 | 0 | 2 | 0 | 0 | 59.5 | 1,173 | 0.004263 | 0.009378 | 0 | 0 | 0 | 0 | 0.125 | 0.210716 | /**
* Tokenize a Minecraft command
* @param command
* @returns
*/
export function tokenizeCommand(command) {
let curlyBrackets = 0
let squareBrackets = 0
let inQuotes = false
let i = 0
let wordStart = 0
let word = ''
let tokens = []
while (i < command.length) {
if (
(command[i] === '^' && word[0] === '^') ||
(command[i] === '~' && word[0] === '~')
) {
tokens.push({
startColumn: wordStart,
endColumn: i,
word,
})
wordStart = i + 1
word = command[i]
} else if (command[i] === '"') {
word += command[i]
if (inQuotes) {
tokens.push({
startColumn: wordStart,
endColumn: i,
word,
})
wordStart = i + 1
word = ''
}
inQuotes = !inQuotes
} else if (command[i] === ' ' || command[i] === '\t') {
if (inQuotes) {
word += command[i]
i++
continue
}
if (curlyBrackets === 0 && squareBrackets === 0 && word !== '') {
tokens.push({
startColumn: wordStart,
endColumn: i,
word,
})
wordStart = i + 1
word = ''
}
} else {
if (command[i] === '{') {
curlyBrackets++
} else if (command[i] === '}') {
curlyBrackets--
} else if (command[i] === '[') {
squareBrackets++
} else if (command[i] === ']') {
squareBrackets--
}
if (command[i].trim() !== '') word += command[i]
}
i++
}
tokens.push({
startColumn: wordStart,
endColumn: i,
word,
})
return { tokens }
}
/**
* Tokenize target selectors that may appear inside of Minecraft's commands
* @param targetSelector
*
* @example "@a[tag=test]" > [{ startColumn: ..., endColumn: ..., word: "tag" }, { startColumn: ..., endColumn: ..., word: "=" }, { startColumn: ..., endColumn: ..., word: "test" }]
* @example "@a[tag=test,tag2=test2]" > [{ startColumn: ..., endColumn: ..., word: "tag" }, { startColumn: ..., endColumn: ..., word: "=" }, { startColumn: ..., endColumn: ..., word: "test" }, { startColumn: ..., endColumn: ..., word: "," }, { startColumn: ..., endColumn: ..., word: "tag2" }, { startColumn: ..., endColumn: ..., word: "=" }, { startColumn: ..., endColumn: ..., word: "test2" }]
*/
export function tokenizeTargetSelector(targetSelector, wordOffset = 0) {
let i = 0
let wordStart = 0
let word = ''
let tokens = []
while (i < targetSelector.length) {
// TODO: Properly support advanced score selector: "scores={something=..1,something_else=0..2}"
if (targetSelector[i] === '=') {
tokens.push({
startColumn: wordStart + wordOffset,
endColumn: i + wordOffset,
word,
})
wordStart = i + 1
word = ''
if (targetSelector[i + 1] === '!') {
tokens.push({
startColumn: i + wordOffset,
endColumn: wordStart + wordOffset + 1,
word: '=!',
})
i++
wordStart++
} else {
tokens.push({
startColumn: i + wordOffset,
endColumn: wordStart + wordOffset,
word: '=',
})
}
} else if (targetSelector[i] === ',') {
tokens.push({
startColumn: wordStart + wordOffset,
endColumn: i + wordOffset,
word,
})
wordStart = i + 1
word = ''
tokens.push({
startColumn: i + wordOffset,
endColumn: wordStart + wordOffset,
word: ',',
})
} else {
if (targetSelector[i].trim() === '' && wordStart === i) wordStart++
word += targetSelector[i].trim()
}
i++
}
tokens.push({
startColumn: wordStart + wordOffset,
endColumn: i + wordOffset,
word,
})
return { tokens }
}
|
982df982b3c52b9f90008fa7aeefb3502e4c2543 | 3,612 | ts | TypeScript | src/arithmetic/fractions.ts | donatto-minaya/ax-calculator | 1b015e2e58796b76bd40fa3055b8709e51137a08 | [
"Apache-2.0"
] | 3 | 2022-01-04T20:01:33.000Z | 2022-02-24T03:27:24.000Z | src/arithmetic/fractions.ts | donatto22/ax-calculator | 1b015e2e58796b76bd40fa3055b8709e51137a08 | [
"Apache-2.0"
] | null | null | null | src/arithmetic/fractions.ts | donatto22/ax-calculator | 1b015e2e58796b76bd40fa3055b8709e51137a08 | [
"Apache-2.0"
] | 1 | 2022-02-15T23:35:52.000Z | 2022-02-15T23:35:52.000Z | export const Fractions = {
sum: function(numerator1: number, denominator1: number, numerator2: number, denominator2: number) {
let result, bober = false;
if(denominator1 == denominator2) {
// When dominators are equals
let top = numerator1 + numerator2
let bottom = denominator1
//Check if negative
if(top < 0) {
bober = true;
top = top * -1;
}
if((top / bottom) % 1 == 0) {
result = String(top / bottom)
}
else {
result = String(top) + "/" + String(bottom);
}
}
else {
// When dominators are different
let top = (denominator2 * numerator1) + (denominator1 * numerator2)
let bottom = denominator1 * denominator2
result = simplify(top, bottom);
}
return result;
},
substract: function(numerator1: number, denominator1: number, numerator2: number, denominator2: number) {
var result;
if(denominator1 == denominator2) {
// When dominators are equals
var top = numerator1 - numerator2
var bottom = denominator1
if((top / bottom) % 1 == 0) {
result = String(top / bottom)
}
else {
result = String(top) + "/" + String(bottom);
}
}
else {
// When dominators are different
var top = (denominator2 * numerator1) - (denominator1 * numerator2)
var bottom = denominator1 * denominator2
result = simplify(top, bottom);
}
return result;
},
product: function(numerator1: number, denominator1: number, numerator2: number, denominator2: number) {
var top = numerator1 * numerator2;
var bottom = denominator1 * denominator2;
return simplify(top, bottom);
},
division: function(numerator1: number, denominator1: number, numerator2: number, denominator2: number) {
var top = numerator1 * denominator2;
var bottom = denominator1 * numerator2;
return simplify(top, bottom);
},
/**
@param top - Numerator
@param bottom - Denominator
**/
simplify: function(top: number, bottom: number) {
return simplify(top, bottom);
},
/**
@param fraction
**/
destructure: function(fraction: string) {
return destructure(fraction);
}
}
function simplify(top: number, bottom: number): string {
let result = '';
var bober = false;
if(top < 0) {
bober = true;
top = top * -1;
}
if(bottom < 0) {
bober = true;
bottom = bottom * -1;
}
for(let i = 2; i < 20; i++) {
while((top / i > 0) && ((bottom / i) > 0)) {
if((top % i == 0) && ((bottom % i) == 0)) {
top = top / i;
bottom = bottom / i;
}
else{
if(bober) {
result = "-" + String(top) + "/" + String(bottom)
}
else {
result = String(top) + "/" + String(bottom)
}
break;
}
}
}
return result;
}
function destructure(string: string) {
let array = string.split('/');
var top = array[0], bottom = array[1];
return {
top, bottom
}
} | 25.985612 | 109 | 0.477852 | 97 | 8 | 0 | 22 | 22 | 0 | 2 | 0 | 23 | 0 | 0 | 9.875 | 821 | 0.036541 | 0.026797 | 0 | 0 | 0 | 0 | 0.442308 | 0.343075 | export const Fractions = {
sum: function(numerator1, denominator1, numerator2, denominator2) {
let result, bober = false;
if(denominator1 == denominator2) {
// When dominators are equals
let top = numerator1 + numerator2
let bottom = denominator1
//Check if negative
if(top < 0) {
bober = true;
top = top * -1;
}
if((top / bottom) % 1 == 0) {
result = String(top / bottom)
}
else {
result = String(top) + "/" + String(bottom);
}
}
else {
// When dominators are different
let top = (denominator2 * numerator1) + (denominator1 * numerator2)
let bottom = denominator1 * denominator2
result = simplify(top, bottom);
}
return result;
},
substract: function(numerator1, denominator1, numerator2, denominator2) {
var result;
if(denominator1 == denominator2) {
// When dominators are equals
var top = numerator1 - numerator2
var bottom = denominator1
if((top / bottom) % 1 == 0) {
result = String(top / bottom)
}
else {
result = String(top) + "/" + String(bottom);
}
}
else {
// When dominators are different
var top = (denominator2 * numerator1) - (denominator1 * numerator2)
var bottom = denominator1 * denominator2
result = simplify(top, bottom);
}
return result;
},
product: function(numerator1, denominator1, numerator2, denominator2) {
var top = numerator1 * numerator2;
var bottom = denominator1 * denominator2;
return simplify(top, bottom);
},
division: function(numerator1, denominator1, numerator2, denominator2) {
var top = numerator1 * denominator2;
var bottom = denominator1 * numerator2;
return simplify(top, bottom);
},
/**
@param top - Numerator
@param bottom - Denominator
**/
simplify: function(top, bottom) {
return simplify(top, bottom);
},
/**
@param fraction
**/
destructure: function(fraction) {
return destructure(fraction);
}
}
/* Example usages of 'simplify' are shown below:
result = simplify(top, bottom);
simplify(top, bottom);
*
@param top - Numerator
@param bottom - Denominator
*
;
*/
function simplify(top, bottom) {
let result = '';
var bober = false;
if(top < 0) {
bober = true;
top = top * -1;
}
if(bottom < 0) {
bober = true;
bottom = bottom * -1;
}
for(let i = 2; i < 20; i++) {
while((top / i > 0) && ((bottom / i) > 0)) {
if((top % i == 0) && ((bottom % i) == 0)) {
top = top / i;
bottom = bottom / i;
}
else{
if(bober) {
result = "-" + String(top) + "/" + String(bottom)
}
else {
result = String(top) + "/" + String(bottom)
}
break;
}
}
}
return result;
}
/* Example usages of 'destructure' are shown below:
*
@param fraction
*
;
destructure(fraction);
*/
function destructure(string) {
let array = string.split('/');
var top = array[0], bottom = array[1];
return {
top, bottom
}
} |
98f45a45b0cd927be1978060c2e2bccd7e68e1be | 3,026 | ts | TypeScript | src/parse.ts | KeithAlt/FTP-Deploy-Action | d6ad227aa5444819c601ca2590fd1b921aafdef8 | [
"MIT"
] | 1 | 2022-01-29T19:13:26.000Z | 2022-01-29T19:13:26.000Z | src/parse.ts | KeithAlt/FTP-Deploy-Action | d6ad227aa5444819c601ca2590fd1b921aafdef8 | [
"MIT"
] | null | null | null | src/parse.ts | KeithAlt/FTP-Deploy-Action | d6ad227aa5444819c601ca2590fd1b921aafdef8 | [
"MIT"
] | null | null | null | export function optionalString(rawValue: string): string | undefined {
if (rawValue.length === 0) {
return undefined;
}
return rawValue;
}
export function optionalBoolean(argumentName: string, rawValue: string): boolean | undefined {
if (rawValue.length === 0) {
return undefined;
}
const cleanValue = rawValue.toLowerCase();
if (cleanValue === "true") {
return true;
}
if (cleanValue === "false") {
return false;
}
throw new Error(`${argumentName}: invalid parameter - please use a boolean, you provided "${rawValue}". Try true or false instead.`);
}
export function optionalProtocol(argumentName: string, rawValue: string): "ftp" | "ftps" | "ftps-legacy" | undefined {
if (rawValue.length === 0) {
return undefined;
}
const cleanValue = rawValue.toLowerCase();
if (cleanValue === "ftp") {
return "ftp";
}
if (cleanValue === "ftps") {
return "ftps";
}
if (cleanValue === "ftps-legacy") {
return "ftps-legacy";
}
throw new Error(`${argumentName}: invalid parameter - you provided "${rawValue}". Try "ftp", "ftps", or "ftps-legacy" instead.`);
}
export function optionalLogLevel(argumentName: string, rawValue: string): "minimal" | "standard" | "verbose" | undefined {
if (rawValue.length === 0) {
return undefined;
}
const cleanValue = rawValue.toLowerCase();
if (cleanValue === "minimal") {
return "minimal";
}
if (cleanValue === "standard") {
return "standard";
}
if (cleanValue === "verbose") {
return "verbose";
}
throw new Error(`${argumentName}: invalid parameter - you provided "${rawValue}". Try "minimal", "standard", or "verbose" instead.`);
}
export function optionalSecurity(argumentName: string, rawValue: string): "loose" | "strict" | undefined {
if (rawValue.length === 0) {
return undefined;
}
const cleanValue = rawValue.toLowerCase();
if (cleanValue === "loose") {
return "loose";
}
if (cleanValue === "strict") {
return "strict";
}
throw new Error(`${argumentName}: invalid parameter - you provided "${rawValue}". Try "loose" or "strict" instead.`);
}
export function optionalInt(argumentName: string, rawValue: string): number | undefined {
if (rawValue.length === 0) {
return undefined;
}
const valueAsNumber = parseFloat(rawValue);
if (Number.isInteger(valueAsNumber)) {
return valueAsNumber;
}
throw new Error(`${argumentName}: invalid parameter - you provided "${rawValue}". Try a whole number (no decimals) instead like 1234`);
}
export function optionalStringArray(argumentName: string, rawValue: string[]): string[] | undefined {
if (typeof rawValue === "string") {
throw new Error(`${argumentName}: invalid parameter - you provided "${rawValue}". This option expects an list in the EXACT format described in the readme`);
}
return rawValue;
}
| 30.26 | 164 | 0.625578 | 80 | 7 | 0 | 13 | 5 | 0 | 0 | 0 | 17 | 0 | 1 | 9.428571 | 750 | 0.026667 | 0.006667 | 0 | 0 | 0.001333 | 0 | 0.68 | 0.253155 | export function optionalString(rawValue) {
if (rawValue.length === 0) {
return undefined;
}
return rawValue;
}
export function optionalBoolean(argumentName, rawValue) {
if (rawValue.length === 0) {
return undefined;
}
const cleanValue = rawValue.toLowerCase();
if (cleanValue === "true") {
return true;
}
if (cleanValue === "false") {
return false;
}
throw new Error(`${argumentName}: invalid parameter - please use a boolean, you provided "${rawValue}". Try true or false instead.`);
}
export function optionalProtocol(argumentName, rawValue) {
if (rawValue.length === 0) {
return undefined;
}
const cleanValue = rawValue.toLowerCase();
if (cleanValue === "ftp") {
return "ftp";
}
if (cleanValue === "ftps") {
return "ftps";
}
if (cleanValue === "ftps-legacy") {
return "ftps-legacy";
}
throw new Error(`${argumentName}: invalid parameter - you provided "${rawValue}". Try "ftp", "ftps", or "ftps-legacy" instead.`);
}
export function optionalLogLevel(argumentName, rawValue) {
if (rawValue.length === 0) {
return undefined;
}
const cleanValue = rawValue.toLowerCase();
if (cleanValue === "minimal") {
return "minimal";
}
if (cleanValue === "standard") {
return "standard";
}
if (cleanValue === "verbose") {
return "verbose";
}
throw new Error(`${argumentName}: invalid parameter - you provided "${rawValue}". Try "minimal", "standard", or "verbose" instead.`);
}
export function optionalSecurity(argumentName, rawValue) {
if (rawValue.length === 0) {
return undefined;
}
const cleanValue = rawValue.toLowerCase();
if (cleanValue === "loose") {
return "loose";
}
if (cleanValue === "strict") {
return "strict";
}
throw new Error(`${argumentName}: invalid parameter - you provided "${rawValue}". Try "loose" or "strict" instead.`);
}
export function optionalInt(argumentName, rawValue) {
if (rawValue.length === 0) {
return undefined;
}
const valueAsNumber = parseFloat(rawValue);
if (Number.isInteger(valueAsNumber)) {
return valueAsNumber;
}
throw new Error(`${argumentName}: invalid parameter - you provided "${rawValue}". Try a whole number (no decimals) instead like 1234`);
}
export function optionalStringArray(argumentName, rawValue) {
if (typeof rawValue === "string") {
throw new Error(`${argumentName}: invalid parameter - you provided "${rawValue}". This option expects an list in the EXACT format described in the readme`);
}
return rawValue;
}
|
cf0796b6a6d7cd2657a854a73c3e908fae288953 | 5,567 | ts | TypeScript | wwwroot/libs/vidyano/common/string.ts | Vidyano/vidyano | 1c7639568974515e821dd033beff6df360a3ca58 | [
"MIT"
] | null | null | null | wwwroot/libs/vidyano/common/string.ts | Vidyano/vidyano | 1c7639568974515e821dd033beff6df360a3ca58 | [
"MIT"
] | 10 | 2022-03-16T12:52:46.000Z | 2022-03-25T12:05:18.000Z | wwwroot/libs/vidyano/common/string.ts | Vidyano/vidyano | 1c7639568974515e821dd033beff6df360a3ca58 | [
"MIT"
] | null | null | null | declare global {
export interface String {
asDataUri(): string;
contains(str: string): boolean;
endsWith(suffix: string): boolean;
insert(str: string, index: number): string;
padLeft(width: number, str?: string): string;
padRight(width: number, str?: string): string;
splitWithTail(separator: string | RegExp, limit?: number): string[];
toKebabCase(): string;
trimEnd(char: string): string;
trimStart(char: string): string;
}
export interface StringConstructor {
isNullOrEmpty(str: string): boolean;
isNullOrWhiteSpace(str: string): boolean;
format(format: string, ...args: any[]): string;
fromChar(ch: string, count: number): string;
}
}
String.prototype.contains = function(it: string) {
return this.indexOf(it) != -1;
};
String.prototype.padLeft = function(totalWidth: number, ch: string) {
if (this.length < totalWidth) {
return String.fromChar(ch || ' ', totalWidth - this.length) + this;
}
return this.substring(0, this.length);
};
String.prototype.padRight = function(totalWidth: number, ch?: string) {
if (this.length < totalWidth) {
return this + String.fromChar(ch || ' ', totalWidth - this.length);
}
return this.substring(0, this.length);
};
const trimStart = String.prototype.trimStart;
String.prototype.trimStart = <any>function(ch?: string) {
if (!ch || !this.length)
return trimStart.apply(this);
ch = ch || ' ';
var i = 0;
for (; this.charAt(i) == ch && i < this.length; i++);
return this.substring(i);
};
const trimEnd = String.prototype.trimEnd;
String.prototype.trimEnd = <any>function(ch?: string) {
if (!ch || !this.length)
return trimEnd.apply(this);
ch = ch ? ch : ' ';
var i = this.length - 1;
for (; i >= 0 && this.charAt(i) == ch; i--);
return this.substring(0, i + 1);
};
String.prototype.insert = function(str: string, index: number) {
var length = this.length;
if (index == length) {
return this.substring(0, index) + str;
}
return this.substring(0, index) + str + this.substring(index, length);
};
String.prototype.asDataUri = function() {
if (/^iVBOR/.test(this))
return "data:image/png;base64," + this;
if (/^\/9j\//.test(this))
return "data:image/jpeg;base64," + this;
if (/^R0lGOD/.test(this))
return "data:image/gif;base64," + this;
if (/^Qk/.test(this))
return "data:image/bmp;base64," + this;
if (/^PD94/.test(this))
return "data:image/svg+xml;base64," + this;
return "";
};
String.prototype.toKebabCase = function() {
if (!this || this === this.toLowerCase())
return this;
var _this = this;
return Array.from(this as string).map(function(c, i) {
var cLower = c.toLowerCase();
if (c === cLower)
return c;
if (i === 0)
return cLower;
var cPrev = _this[i - 1];
if (!/^[a-zA-Z]+$/.test(cPrev))
return cLower;
var cPrevLower = cPrev.toLowerCase();
if (cPrev === cPrevLower)
return "-" + cLower;
if (i + 1 === _this.length)
return cLower;
var cNext = _this[i + 1];
var cNextUpper = cNext.toUpperCase();
if (cNext === cNextUpper)
return cLower;
return "-" + cLower;
}).join("");
}
String.prototype.splitWithTail = function(separator: string | RegExp, limit?: number): string[] {
let pattern: RegExp, startIndex: number, m: RegExpExecArray;
const parts: string[] = [];
if (!limit)
return this.split(separator);
if (separator instanceof RegExp)
pattern = new RegExp(separator.source, "g" + (separator.ignoreCase ? "i" : "") + (separator.multiline ? "m" : ""));
else
pattern = new RegExp(separator.replace(/([.*+?^${}()|\[\]\/\\])/g, "\\$1"), "g");
do {
startIndex = pattern.lastIndex;
if (m = pattern.exec(this)) {
parts.push(this.substr(startIndex, m.index - startIndex));
}
} while (m && parts.length < limit - 1);
parts.push(this.substr(pattern.lastIndex));
return parts;
}
String.isNullOrEmpty = function(str: string) {
return str == null || str.length == 0;
};
String.isNullOrWhiteSpace = function(str: string) {
return str == null || !(/\S/.test(str));
};
const _formatRE = /(\{[^\}^\{]+\})/g;
const _format = function(format: string, values: any[], useLocale: boolean) {
return format.replace(_formatRE,
function (m) {
var index = parseInt(m.substr(1), 10);
var value = values[index];
if (value == null)
return '';
if (value.format) {
var formatSpec = null;
var formatIndex = m.indexOf(':');
if (formatIndex > 0) {
formatSpec = m.substring(formatIndex + 1, m.length - 1);
}
return useLocale ? value.localeFormat(formatSpec) : value.format(formatSpec);
}
else
return useLocale ? (value.localeFormat ? value.localeFormat() : value.toLocaleString()) : value.toString();
});
};
String.format = function(format: string, ...args: any[]) {
return _format(format, args, /* useLocale */true);
};
String.fromChar = function(ch: string, count: number) {
var s = ch;
for (var i = 1; i < count; i++) {
s += ch;
}
return s;
};
export default String; | 30.927778 | 123 | 0.568888 | 153 | 16 | 14 | 41 | 23 | 0 | 3 | 5 | 53 | 2 | 2 | 8.3125 | 1,578 | 0.036122 | 0.014575 | 0 | 0.001267 | 0.001267 | 0.053191 | 0.56383 | 0.303256 | declare global {
export interface String {
asDataUri();
contains(str);
endsWith(suffix);
insert(str, index);
padLeft(width, str?);
padRight(width, str?);
splitWithTail(separator, limit?);
toKebabCase();
trimEnd(char);
trimStart(char);
}
export interface StringConstructor {
isNullOrEmpty(str);
isNullOrWhiteSpace(str);
format(format, ...args);
fromChar(ch, count);
}
}
String.prototype.contains = function(it) {
return this.indexOf(it) != -1;
};
String.prototype.padLeft = function(totalWidth, ch) {
if (this.length < totalWidth) {
return String.fromChar(ch || ' ', totalWidth - this.length) + this;
}
return this.substring(0, this.length);
};
String.prototype.padRight = function(totalWidth, ch?) {
if (this.length < totalWidth) {
return this + String.fromChar(ch || ' ', totalWidth - this.length);
}
return this.substring(0, this.length);
};
const trimStart = String.prototype.trimStart;
String.prototype.trimStart = <any>function(ch?) {
if (!ch || !this.length)
return trimStart.apply(this);
ch = ch || ' ';
var i = 0;
for (; this.charAt(i) == ch && i < this.length; i++);
return this.substring(i);
};
const trimEnd = String.prototype.trimEnd;
String.prototype.trimEnd = <any>function(ch?) {
if (!ch || !this.length)
return trimEnd.apply(this);
ch = ch ? ch : ' ';
var i = this.length - 1;
for (; i >= 0 && this.charAt(i) == ch; i--);
return this.substring(0, i + 1);
};
String.prototype.insert = function(str, index) {
var length = this.length;
if (index == length) {
return this.substring(0, index) + str;
}
return this.substring(0, index) + str + this.substring(index, length);
};
String.prototype.asDataUri = function() {
if (/^iVBOR/.test(this))
return "data:image/png;base64," + this;
if (/^\/9j\//.test(this))
return "data:image/jpeg;base64," + this;
if (/^R0lGOD/.test(this))
return "data:image/gif;base64," + this;
if (/^Qk/.test(this))
return "data:image/bmp;base64," + this;
if (/^PD94/.test(this))
return "data:image/svg+xml;base64," + this;
return "";
};
String.prototype.toKebabCase = function() {
if (!this || this === this.toLowerCase())
return this;
var _this = this;
return Array.from(this as string).map(function(c, i) {
var cLower = c.toLowerCase();
if (c === cLower)
return c;
if (i === 0)
return cLower;
var cPrev = _this[i - 1];
if (!/^[a-zA-Z]+$/.test(cPrev))
return cLower;
var cPrevLower = cPrev.toLowerCase();
if (cPrev === cPrevLower)
return "-" + cLower;
if (i + 1 === _this.length)
return cLower;
var cNext = _this[i + 1];
var cNextUpper = cNext.toUpperCase();
if (cNext === cNextUpper)
return cLower;
return "-" + cLower;
}).join("");
}
String.prototype.splitWithTail = function(separator, limit?) {
let pattern, startIndex, m;
const parts = [];
if (!limit)
return this.split(separator);
if (separator instanceof RegExp)
pattern = new RegExp(separator.source, "g" + (separator.ignoreCase ? "i" : "") + (separator.multiline ? "m" : ""));
else
pattern = new RegExp(separator.replace(/([.*+?^${}()|\[\]\/\\])/g, "\\$1"), "g");
do {
startIndex = pattern.lastIndex;
if (m = pattern.exec(this)) {
parts.push(this.substr(startIndex, m.index - startIndex));
}
} while (m && parts.length < limit - 1);
parts.push(this.substr(pattern.lastIndex));
return parts;
}
String.isNullOrEmpty = function(str) {
return str == null || str.length == 0;
};
String.isNullOrWhiteSpace = function(str) {
return str == null || !(/\S/.test(str));
};
const _formatRE = /(\{[^\}^\{]+\})/g;
/* Example usages of '_format' are shown below:
_format(format, args, useLocale true);
*/
const _format = function(format, values, useLocale) {
return format.replace(_formatRE,
function (m) {
var index = parseInt(m.substr(1), 10);
var value = values[index];
if (value == null)
return '';
if (value.format) {
var formatSpec = null;
var formatIndex = m.indexOf(':');
if (formatIndex > 0) {
formatSpec = m.substring(formatIndex + 1, m.length - 1);
}
return useLocale ? value.localeFormat(formatSpec) : value.format(formatSpec);
}
else
return useLocale ? (value.localeFormat ? value.localeFormat() : value.toLocaleString()) : value.toString();
});
};
String.format = function(format, ...args) {
return _format(format, args, /* useLocale */true);
};
String.fromChar = function(ch, count) {
var s = ch;
for (var i = 1; i < count; i++) {
s += ch;
}
return s;
};
export default String; |
a312d18e48976a6825298b151b938de7054db0c1 | 9,010 | ts | TypeScript | src/lib/hmac-md5.ts | raine/homebridge-w215 | 67b05050dcfc6fb262a2728fb8fcd8d0dcc7668d | [
"Apache-2.0"
] | null | null | null | src/lib/hmac-md5.ts | raine/homebridge-w215 | 67b05050dcfc6fb262a2728fb8fcd8d0dcc7668d | [
"Apache-2.0"
] | null | null | null | src/lib/hmac-md5.ts | raine/homebridge-w215 | 67b05050dcfc6fb262a2728fb8fcd8d0dcc7668d | [
"Apache-2.0"
] | 1 | 2022-03-26T17:08:51.000Z | 2022-03-26T17:08:51.000Z | export class HMACMD5 {
public static hex_hmac_md5(k, d) {
return HMACMD5.rstr2hex(HMACMD5.rstr_hmac_md5(HMACMD5.str2rstr_utf8(k), HMACMD5.str2rstr_utf8(d)));
}
/*
* Calculate the HMAC-MD5, of a key and some data (raw strings)
*/
private static rstr_hmac_md5(key, data) {
let bkey = HMACMD5.rstr2binl(key);
if (bkey.length > 16) {
bkey = HMACMD5.binl_md5(bkey, key.length * 8);
}
const ipad = Array(16), opad = Array(16);
for (let i = 0; i < 16; i++) {
ipad[i] = bkey[i] ^ 0x36363636;
opad[i] = bkey[i] ^ 0x5C5C5C5C;
}
const hash = HMACMD5.binl_md5(ipad.concat(HMACMD5.rstr2binl(data)), 512 + data.length * 8);
return HMACMD5.binl2rstr(HMACMD5.binl_md5(opad.concat(hash), 512 + 128));
}
/*
* Convert a raw string to a hex string
*/
private static rstr2hex(input) {
let hexcase = 0;
try {
hexcase
} catch (e) {
hexcase = 0;
}
const hex_tab = hexcase ? '0123456789ABCDEF' : '0123456789abcdef';
let output = '';
let x;
for (let i = 0; i < input.length; i++) {
x = input.charCodeAt(i);
output += hex_tab.charAt((x >>> 4) & 0x0F)
+ hex_tab.charAt(x & 0x0F);
}
return output;
}
/*
* Encode a string as utf-8.
* For efficiency, this assumes the input is valid utf-16.
*/
private static str2rstr_utf8(input) {
let output = '';
let i = -1;
let x, y;
while (++i < input.length) {
/* Decode utf-16 surrogate pairs */
x = input.charCodeAt(i);
y = i + 1 < input.length ? input.charCodeAt(i + 1) : 0;
if (0xD800 <= x && x <= 0xDBFF && 0xDC00 <= y && y <= 0xDFFF) {
x = 0x10000 + ((x & 0x03FF) << 10) + (y & 0x03FF);
i++;
}
/* Encode output as utf-8 */
if (x <= 0x7F) {
output += String.fromCharCode(x);
} else if (x <= 0x7FF) {
output += String.fromCharCode(0xC0 | ((x >>> 6) & 0x1F),
0x80 | (x & 0x3F));
} else if (x <= 0xFFFF) {
output += String.fromCharCode(0xE0 | ((x >>> 12) & 0x0F),
0x80 | ((x >>> 6) & 0x3F),
0x80 | (x & 0x3F));
} else if (x <= 0x1FFFFF) {
output += String.fromCharCode(0xF0 | ((x >>> 18) & 0x07),
0x80 | ((x >>> 12) & 0x3F),
0x80 | ((x >>> 6) & 0x3F),
0x80 | (x & 0x3F));
}
}
return output;
}
/*
* Convert a raw string to an array of little-endian words
* Characters >255 have their high-byte silently ignored.
*/
private static rstr2binl(input) {
let i;
const output = Array(input.length >> 2);
for (i = 0; i < output.length; i++) {
output[i] = 0;
}
for (i = 0; i < input.length * 8; i += 8) {
output[i >> 5] |= (input.charCodeAt(i / 8) & 0xFF) << (i % 32);
}
return output;
}
/*
* Convert an array of little-endian words to a string
*/
private static binl2rstr(input) {
let output = '';
for (let i = 0; i < input.length * 32; i += 8) {
output += String.fromCharCode((input[i >> 5] >>> (i % 32)) & 0xFF);
}
return output;
}
/*
* Calculate the MD5 of an array of little-endian words, and a bit length.
*/
private static binl_md5(x, len) {
/* append padding */
x[len >> 5] |= 0x80 << ((len) % 32);
x[(((len + 64) >>> 9) << 4) + 14] = len;
let a = 1732584193;
let b = -271733879;
let c = -1732584194;
let d = 271733878;
for (let i = 0; i < x.length; i += 16) {
const olda = a;
const oldb = b;
const oldc = c;
const oldd = d;
a = HMACMD5.md5_ff(a, b, c, d, x[i], 7, -680876936);
d = HMACMD5.md5_ff(d, a, b, c, x[i + 1], 12, -389564586);
c = HMACMD5.md5_ff(c, d, a, b, x[i + 2], 17, 606105819);
b = HMACMD5.md5_ff(b, c, d, a, x[i + 3], 22, -1044525330);
a = HMACMD5.md5_ff(a, b, c, d, x[i + 4], 7, -176418897);
d = HMACMD5.md5_ff(d, a, b, c, x[i + 5], 12, 1200080426);
c = HMACMD5.md5_ff(c, d, a, b, x[i + 6], 17, -1473231341);
b = HMACMD5.md5_ff(b, c, d, a, x[i + 7], 22, -45705983);
a = HMACMD5.md5_ff(a, b, c, d, x[i + 8], 7, 1770035416);
d = HMACMD5.md5_ff(d, a, b, c, x[i + 9], 12, -1958414417);
c = HMACMD5.md5_ff(c, d, a, b, x[i + 10], 17, -42063);
b = HMACMD5.md5_ff(b, c, d, a, x[i + 11], 22, -1990404162);
a = HMACMD5.md5_ff(a, b, c, d, x[i + 12], 7, 1804603682);
d = HMACMD5.md5_ff(d, a, b, c, x[i + 13], 12, -40341101);
c = HMACMD5.md5_ff(c, d, a, b, x[i + 14], 17, -1502002290);
b = HMACMD5.md5_ff(b, c, d, a, x[i + 15], 22, 1236535329);
a = HMACMD5.md5_gg(a, b, c, d, x[i + 1], 5, -165796510);
d = HMACMD5.md5_gg(d, a, b, c, x[i + 6], 9, -1069501632);
c = HMACMD5.md5_gg(c, d, a, b, x[i + 11], 14, 643717713);
b = HMACMD5.md5_gg(b, c, d, a, x[i], 20, -373897302);
a = HMACMD5.md5_gg(a, b, c, d, x[i + 5], 5, -701558691);
d = HMACMD5.md5_gg(d, a, b, c, x[i + 10], 9, 38016083);
c = HMACMD5.md5_gg(c, d, a, b, x[i + 15], 14, -660478335);
b = HMACMD5.md5_gg(b, c, d, a, x[i + 4], 20, -405537848);
a = HMACMD5.md5_gg(a, b, c, d, x[i + 9], 5, 568446438);
d = HMACMD5.md5_gg(d, a, b, c, x[i + 14], 9, -1019803690);
c = HMACMD5.md5_gg(c, d, a, b, x[i + 3], 14, -187363961);
b = HMACMD5.md5_gg(b, c, d, a, x[i + 8], 20, 1163531501);
a = HMACMD5.md5_gg(a, b, c, d, x[i + 13], 5, -1444681467);
d = HMACMD5.md5_gg(d, a, b, c, x[i + 2], 9, -51403784);
c = HMACMD5.md5_gg(c, d, a, b, x[i + 7], 14, 1735328473);
b = HMACMD5.md5_gg(b, c, d, a, x[i + 12], 20, -1926607734);
a = HMACMD5.md5_hh(a, b, c, d, x[i + 5], 4, -378558);
d = HMACMD5.md5_hh(d, a, b, c, x[i + 8], 11, -2022574463);
c = HMACMD5.md5_hh(c, d, a, b, x[i + 11], 16, 1839030562);
b = HMACMD5.md5_hh(b, c, d, a, x[i + 14], 23, -35309556);
a = HMACMD5.md5_hh(a, b, c, d, x[i + 1], 4, -1530992060);
d = HMACMD5.md5_hh(d, a, b, c, x[i + 4], 11, 1272893353);
c = HMACMD5.md5_hh(c, d, a, b, x[i + 7], 16, -155497632);
b = HMACMD5.md5_hh(b, c, d, a, x[i + 10], 23, -1094730640);
a = HMACMD5.md5_hh(a, b, c, d, x[i + 13], 4, 681279174);
d = HMACMD5.md5_hh(d, a, b, c, x[i], 11, -358537222);
c = HMACMD5.md5_hh(c, d, a, b, x[i + 3], 16, -722521979);
b = HMACMD5.md5_hh(b, c, d, a, x[i + 6], 23, 76029189);
a = HMACMD5.md5_hh(a, b, c, d, x[i + 9], 4, -640364487);
d = HMACMD5.md5_hh(d, a, b, c, x[i + 12], 11, -421815835);
c = HMACMD5.md5_hh(c, d, a, b, x[i + 15], 16, 530742520);
b = HMACMD5.md5_hh(b, c, d, a, x[i + 2], 23, -995338651);
a = HMACMD5.md5_ii(a, b, c, d, x[i], 6, -198630844);
d = HMACMD5.md5_ii(d, a, b, c, x[i + 7], 10, 1126891415);
c = HMACMD5.md5_ii(c, d, a, b, x[i + 14], 15, -1416354905);
b = HMACMD5.md5_ii(b, c, d, a, x[i + 5], 21, -57434055);
a = HMACMD5.md5_ii(a, b, c, d, x[i + 12], 6, 1700485571);
d = HMACMD5.md5_ii(d, a, b, c, x[i + 3], 10, -1894986606);
c = HMACMD5.md5_ii(c, d, a, b, x[i + 10], 15, -1051523);
b = HMACMD5.md5_ii(b, c, d, a, x[i + 1], 21, -2054922799);
a = HMACMD5.md5_ii(a, b, c, d, x[i + 8], 6, 1873313359);
d = HMACMD5.md5_ii(d, a, b, c, x[i + 15], 10, -30611744);
c = HMACMD5.md5_ii(c, d, a, b, x[i + 6], 15, -1560198380);
b = HMACMD5.md5_ii(b, c, d, a, x[i + 13], 21, 1309151649);
a = HMACMD5.md5_ii(a, b, c, d, x[i + 4], 6, -145523070);
d = HMACMD5.md5_ii(d, a, b, c, x[i + 11], 10, -1120210379);
c = HMACMD5.md5_ii(c, d, a, b, x[i + 2], 15, 718787259);
b = HMACMD5.md5_ii(b, c, d, a, x[i + 9], 21, -343485551);
a = HMACMD5.safe_add(a, olda);
b = HMACMD5.safe_add(b, oldb);
c = HMACMD5.safe_add(c, oldc);
d = HMACMD5.safe_add(d, oldd);
}
return Array(a, b, c, d);
}
/*
* These functions implement the four basic operations the algorithm uses.
*/
private static md5_cmn(q, a, b, x, s, t) {
return HMACMD5.safe_add(HMACMD5.bit_rol(HMACMD5.safe_add(HMACMD5.safe_add(a, q), HMACMD5.safe_add(x, t)), s), b);
}
private static md5_ff(a, b, c, d, x, s, t) {
return HMACMD5.md5_cmn((b & c) | ((~b) & d), a, b, x, s, t);
}
private static md5_gg(a, b, c, d, x, s, t) {
return HMACMD5.md5_cmn((b & d) | (c & (~d)), a, b, x, s, t);
}
private static md5_hh(a, b, c, d, x, s, t) {
return HMACMD5.md5_cmn(b ^ c ^ d, a, b, x, s, t);
}
private static md5_ii(a, b, c, d, x, s, t) {
return HMACMD5.md5_cmn(c ^ (b | (~d)), a, b, x, s, t);
}
/*
* Add integers, wrapping at 2^32. This uses 16-bit operations internally
* to work around bugs in some JS interpreters.
*/
private static safe_add(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.
*/
private static bit_rol(num, cnt) {
return (num << cnt) | (num >>> (32 - cnt));
}
}
| 36.330645 | 117 | 0.520089 | 188 | 14 | 0 | 48 | 29 | 0 | 13 | 0 | 0 | 1 | 0 | 11.285714 | 4,766 | 0.013009 | 0.006085 | 0 | 0.00021 | 0 | 0 | 0 | 0.224026 | export class HMACMD5 {
public static hex_hmac_md5(k, d) {
return HMACMD5.rstr2hex(HMACMD5.rstr_hmac_md5(HMACMD5.str2rstr_utf8(k), HMACMD5.str2rstr_utf8(d)));
}
/*
* Calculate the HMAC-MD5, of a key and some data (raw strings)
*/
private static rstr_hmac_md5(key, data) {
let bkey = HMACMD5.rstr2binl(key);
if (bkey.length > 16) {
bkey = HMACMD5.binl_md5(bkey, key.length * 8);
}
const ipad = Array(16), opad = Array(16);
for (let i = 0; i < 16; i++) {
ipad[i] = bkey[i] ^ 0x36363636;
opad[i] = bkey[i] ^ 0x5C5C5C5C;
}
const hash = HMACMD5.binl_md5(ipad.concat(HMACMD5.rstr2binl(data)), 512 + data.length * 8);
return HMACMD5.binl2rstr(HMACMD5.binl_md5(opad.concat(hash), 512 + 128));
}
/*
* Convert a raw string to a hex string
*/
private static rstr2hex(input) {
let hexcase = 0;
try {
hexcase
} catch (e) {
hexcase = 0;
}
const hex_tab = hexcase ? '0123456789ABCDEF' : '0123456789abcdef';
let output = '';
let x;
for (let i = 0; i < input.length; i++) {
x = input.charCodeAt(i);
output += hex_tab.charAt((x >>> 4) & 0x0F)
+ hex_tab.charAt(x & 0x0F);
}
return output;
}
/*
* Encode a string as utf-8.
* For efficiency, this assumes the input is valid utf-16.
*/
private static str2rstr_utf8(input) {
let output = '';
let i = -1;
let x, y;
while (++i < input.length) {
/* Decode utf-16 surrogate pairs */
x = input.charCodeAt(i);
y = i + 1 < input.length ? input.charCodeAt(i + 1) : 0;
if (0xD800 <= x && x <= 0xDBFF && 0xDC00 <= y && y <= 0xDFFF) {
x = 0x10000 + ((x & 0x03FF) << 10) + (y & 0x03FF);
i++;
}
/* Encode output as utf-8 */
if (x <= 0x7F) {
output += String.fromCharCode(x);
} else if (x <= 0x7FF) {
output += String.fromCharCode(0xC0 | ((x >>> 6) & 0x1F),
0x80 | (x & 0x3F));
} else if (x <= 0xFFFF) {
output += String.fromCharCode(0xE0 | ((x >>> 12) & 0x0F),
0x80 | ((x >>> 6) & 0x3F),
0x80 | (x & 0x3F));
} else if (x <= 0x1FFFFF) {
output += String.fromCharCode(0xF0 | ((x >>> 18) & 0x07),
0x80 | ((x >>> 12) & 0x3F),
0x80 | ((x >>> 6) & 0x3F),
0x80 | (x & 0x3F));
}
}
return output;
}
/*
* Convert a raw string to an array of little-endian words
* Characters >255 have their high-byte silently ignored.
*/
private static rstr2binl(input) {
let i;
const output = Array(input.length >> 2);
for (i = 0; i < output.length; i++) {
output[i] = 0;
}
for (i = 0; i < input.length * 8; i += 8) {
output[i >> 5] |= (input.charCodeAt(i / 8) & 0xFF) << (i % 32);
}
return output;
}
/*
* Convert an array of little-endian words to a string
*/
private static binl2rstr(input) {
let output = '';
for (let i = 0; i < input.length * 32; i += 8) {
output += String.fromCharCode((input[i >> 5] >>> (i % 32)) & 0xFF);
}
return output;
}
/*
* Calculate the MD5 of an array of little-endian words, and a bit length.
*/
private static binl_md5(x, len) {
/* append padding */
x[len >> 5] |= 0x80 << ((len) % 32);
x[(((len + 64) >>> 9) << 4) + 14] = len;
let a = 1732584193;
let b = -271733879;
let c = -1732584194;
let d = 271733878;
for (let i = 0; i < x.length; i += 16) {
const olda = a;
const oldb = b;
const oldc = c;
const oldd = d;
a = HMACMD5.md5_ff(a, b, c, d, x[i], 7, -680876936);
d = HMACMD5.md5_ff(d, a, b, c, x[i + 1], 12, -389564586);
c = HMACMD5.md5_ff(c, d, a, b, x[i + 2], 17, 606105819);
b = HMACMD5.md5_ff(b, c, d, a, x[i + 3], 22, -1044525330);
a = HMACMD5.md5_ff(a, b, c, d, x[i + 4], 7, -176418897);
d = HMACMD5.md5_ff(d, a, b, c, x[i + 5], 12, 1200080426);
c = HMACMD5.md5_ff(c, d, a, b, x[i + 6], 17, -1473231341);
b = HMACMD5.md5_ff(b, c, d, a, x[i + 7], 22, -45705983);
a = HMACMD5.md5_ff(a, b, c, d, x[i + 8], 7, 1770035416);
d = HMACMD5.md5_ff(d, a, b, c, x[i + 9], 12, -1958414417);
c = HMACMD5.md5_ff(c, d, a, b, x[i + 10], 17, -42063);
b = HMACMD5.md5_ff(b, c, d, a, x[i + 11], 22, -1990404162);
a = HMACMD5.md5_ff(a, b, c, d, x[i + 12], 7, 1804603682);
d = HMACMD5.md5_ff(d, a, b, c, x[i + 13], 12, -40341101);
c = HMACMD5.md5_ff(c, d, a, b, x[i + 14], 17, -1502002290);
b = HMACMD5.md5_ff(b, c, d, a, x[i + 15], 22, 1236535329);
a = HMACMD5.md5_gg(a, b, c, d, x[i + 1], 5, -165796510);
d = HMACMD5.md5_gg(d, a, b, c, x[i + 6], 9, -1069501632);
c = HMACMD5.md5_gg(c, d, a, b, x[i + 11], 14, 643717713);
b = HMACMD5.md5_gg(b, c, d, a, x[i], 20, -373897302);
a = HMACMD5.md5_gg(a, b, c, d, x[i + 5], 5, -701558691);
d = HMACMD5.md5_gg(d, a, b, c, x[i + 10], 9, 38016083);
c = HMACMD5.md5_gg(c, d, a, b, x[i + 15], 14, -660478335);
b = HMACMD5.md5_gg(b, c, d, a, x[i + 4], 20, -405537848);
a = HMACMD5.md5_gg(a, b, c, d, x[i + 9], 5, 568446438);
d = HMACMD5.md5_gg(d, a, b, c, x[i + 14], 9, -1019803690);
c = HMACMD5.md5_gg(c, d, a, b, x[i + 3], 14, -187363961);
b = HMACMD5.md5_gg(b, c, d, a, x[i + 8], 20, 1163531501);
a = HMACMD5.md5_gg(a, b, c, d, x[i + 13], 5, -1444681467);
d = HMACMD5.md5_gg(d, a, b, c, x[i + 2], 9, -51403784);
c = HMACMD5.md5_gg(c, d, a, b, x[i + 7], 14, 1735328473);
b = HMACMD5.md5_gg(b, c, d, a, x[i + 12], 20, -1926607734);
a = HMACMD5.md5_hh(a, b, c, d, x[i + 5], 4, -378558);
d = HMACMD5.md5_hh(d, a, b, c, x[i + 8], 11, -2022574463);
c = HMACMD5.md5_hh(c, d, a, b, x[i + 11], 16, 1839030562);
b = HMACMD5.md5_hh(b, c, d, a, x[i + 14], 23, -35309556);
a = HMACMD5.md5_hh(a, b, c, d, x[i + 1], 4, -1530992060);
d = HMACMD5.md5_hh(d, a, b, c, x[i + 4], 11, 1272893353);
c = HMACMD5.md5_hh(c, d, a, b, x[i + 7], 16, -155497632);
b = HMACMD5.md5_hh(b, c, d, a, x[i + 10], 23, -1094730640);
a = HMACMD5.md5_hh(a, b, c, d, x[i + 13], 4, 681279174);
d = HMACMD5.md5_hh(d, a, b, c, x[i], 11, -358537222);
c = HMACMD5.md5_hh(c, d, a, b, x[i + 3], 16, -722521979);
b = HMACMD5.md5_hh(b, c, d, a, x[i + 6], 23, 76029189);
a = HMACMD5.md5_hh(a, b, c, d, x[i + 9], 4, -640364487);
d = HMACMD5.md5_hh(d, a, b, c, x[i + 12], 11, -421815835);
c = HMACMD5.md5_hh(c, d, a, b, x[i + 15], 16, 530742520);
b = HMACMD5.md5_hh(b, c, d, a, x[i + 2], 23, -995338651);
a = HMACMD5.md5_ii(a, b, c, d, x[i], 6, -198630844);
d = HMACMD5.md5_ii(d, a, b, c, x[i + 7], 10, 1126891415);
c = HMACMD5.md5_ii(c, d, a, b, x[i + 14], 15, -1416354905);
b = HMACMD5.md5_ii(b, c, d, a, x[i + 5], 21, -57434055);
a = HMACMD5.md5_ii(a, b, c, d, x[i + 12], 6, 1700485571);
d = HMACMD5.md5_ii(d, a, b, c, x[i + 3], 10, -1894986606);
c = HMACMD5.md5_ii(c, d, a, b, x[i + 10], 15, -1051523);
b = HMACMD5.md5_ii(b, c, d, a, x[i + 1], 21, -2054922799);
a = HMACMD5.md5_ii(a, b, c, d, x[i + 8], 6, 1873313359);
d = HMACMD5.md5_ii(d, a, b, c, x[i + 15], 10, -30611744);
c = HMACMD5.md5_ii(c, d, a, b, x[i + 6], 15, -1560198380);
b = HMACMD5.md5_ii(b, c, d, a, x[i + 13], 21, 1309151649);
a = HMACMD5.md5_ii(a, b, c, d, x[i + 4], 6, -145523070);
d = HMACMD5.md5_ii(d, a, b, c, x[i + 11], 10, -1120210379);
c = HMACMD5.md5_ii(c, d, a, b, x[i + 2], 15, 718787259);
b = HMACMD5.md5_ii(b, c, d, a, x[i + 9], 21, -343485551);
a = HMACMD5.safe_add(a, olda);
b = HMACMD5.safe_add(b, oldb);
c = HMACMD5.safe_add(c, oldc);
d = HMACMD5.safe_add(d, oldd);
}
return Array(a, b, c, d);
}
/*
* These functions implement the four basic operations the algorithm uses.
*/
private static md5_cmn(q, a, b, x, s, t) {
return HMACMD5.safe_add(HMACMD5.bit_rol(HMACMD5.safe_add(HMACMD5.safe_add(a, q), HMACMD5.safe_add(x, t)), s), b);
}
private static md5_ff(a, b, c, d, x, s, t) {
return HMACMD5.md5_cmn((b & c) | ((~b) & d), a, b, x, s, t);
}
private static md5_gg(a, b, c, d, x, s, t) {
return HMACMD5.md5_cmn((b & d) | (c & (~d)), a, b, x, s, t);
}
private static md5_hh(a, b, c, d, x, s, t) {
return HMACMD5.md5_cmn(b ^ c ^ d, a, b, x, s, t);
}
private static md5_ii(a, b, c, d, x, s, t) {
return HMACMD5.md5_cmn(c ^ (b | (~d)), a, b, x, s, t);
}
/*
* Add integers, wrapping at 2^32. This uses 16-bit operations internally
* to work around bugs in some JS interpreters.
*/
private static safe_add(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.
*/
private static bit_rol(num, cnt) {
return (num << cnt) | (num >>> (32 - cnt));
}
}
|
a39abc380f4c4af8e45296a9d17dd3369b215f99 | 3,360 | ts | TypeScript | solutions/day15.ts | GiyoMoon/aoc2021 | 83d7e9018ed3b628353bc9a0a37b70a1462ecd74 | [
"Unlicense"
] | null | null | null | solutions/day15.ts | GiyoMoon/aoc2021 | 83d7e9018ed3b628353bc9a0a37b70a1462ecd74 | [
"Unlicense"
] | 1 | 2022-02-03T11:04:17.000Z | 2022-02-03T11:04:17.000Z | solutions/day15.ts | GiyoMoon/aoc2021 | 83d7e9018ed3b628353bc9a0a37b70a1462ecd74 | [
"Unlicense"
] | null | null | null | export default class Day15 {
private _points: { distance: number; value: number; visited: boolean; }[][] = [];
public solve(input: string): { part1: any, part2: any; } {
const inputPoints = input.split('\n').map(l => l.split('').map(c => parseInt(c)));
this._initPoints(inputPoints);
let finished = false;
while (!finished) {
const shortestDistanceCoord = this._findShortestDistance();
if (
shortestDistanceCoord[0] === null &&
shortestDistanceCoord[1] === null
) {
finished = true;
break;
}
this._updateAdjacent(shortestDistanceCoord);
}
const lastPointDistancePart1 = this._points[this._points.length - 1][this._points[0].length - 1].distance;
this._initBigPoints(inputPoints);
finished = false;
while (!finished) {
const shortestDistanceCoord = this._findShortestDistance();
if (
shortestDistanceCoord[0] === null &&
shortestDistanceCoord[1] === null
) {
finished = true;
break;
}
this._updateAdjacent(shortestDistanceCoord);
}
const lastPointDistancePart2 = this._points[this._points.length - 1][this._points[0].length - 1].distance;
return { part1: lastPointDistancePart1, part2: lastPointDistancePart2 };
}
private _findShortestDistance() {
let distance = Number.MAX_VALUE;
const shortestDistance: [number, number] = [null, null];
this._points.forEach((l, y) => {
l.forEach((c, x) => {
if (!c.visited && c.distance < distance) {
distance = c.distance;
shortestDistance[0] = y;
shortestDistance[1] = x;
}
});
});
return shortestDistance;
}
private _updateAdjacent(sDC: [number, number]) {
const distance = this._points[sDC[0]][sDC[1]].distance;
this._points[sDC[0]][sDC[1]].visited = true;
const yCoords = [sDC[0] + 1, sDC[0] - 1, sDC[0], sDC[0]];
const xCoords = [sDC[1], sDC[1], sDC[1] + 1, sDC[1] - 1];
for (let i = 0; i < yCoords.length; i++) {
if (this._points[yCoords[i]] && this._points[yCoords[i]][xCoords[i]]) {
const oldDistance = this._points[yCoords[i]][xCoords[i]].distance;
const newDistance = distance + this._points[yCoords[i]][xCoords[i]].value;
this._points[yCoords[i]][xCoords[i]].distance = oldDistance > newDistance ? newDistance : oldDistance;
}
}
}
private _initPoints(inputPoints: number[][]) {
inputPoints.forEach((l, y) => {
if (!this._points[y]) {
this._points[y] = [];
}
l.forEach((c, x) => {
this._points[y][x] = { distance: Number.MAX_VALUE, value: c, visited: false };
});
});
this._points[0][0].distance = 0;
}
private _initBigPoints(inputPoints: number[][]) {
const size = inputPoints.length;
inputPoints.forEach((l, y) => {
l.forEach((c, x) => {
for (let yy = 0; yy < 5; yy++) {
for (let xx = 0; xx < 5; xx++) {
if (!this._points[y + size * yy]) {
this._points[y + size * yy] = [];
}
const value = (c + yy + xx) % 9 === 0 ? 9 : (c + yy + xx) % 9;
this._points[y + size * yy][x + size * xx] = { distance: Number.MAX_VALUE, value, visited: false };
}
}
});
});
this._points[0][0].distance = 0;
}
}
| 31.698113 | 111 | 0.569345 | 90 | 13 | 0 | 18 | 18 | 1 | 4 | 2 | 10 | 1 | 0 | 9.076923 | 994 | 0.031187 | 0.018109 | 0.001006 | 0.001006 | 0 | 0.04 | 0.2 | 0.303956 | export default class Day15 {
private _points = [];
public solve(input) {
const inputPoints = input.split('\n').map(l => l.split('').map(c => parseInt(c)));
this._initPoints(inputPoints);
let finished = false;
while (!finished) {
const shortestDistanceCoord = this._findShortestDistance();
if (
shortestDistanceCoord[0] === null &&
shortestDistanceCoord[1] === null
) {
finished = true;
break;
}
this._updateAdjacent(shortestDistanceCoord);
}
const lastPointDistancePart1 = this._points[this._points.length - 1][this._points[0].length - 1].distance;
this._initBigPoints(inputPoints);
finished = false;
while (!finished) {
const shortestDistanceCoord = this._findShortestDistance();
if (
shortestDistanceCoord[0] === null &&
shortestDistanceCoord[1] === null
) {
finished = true;
break;
}
this._updateAdjacent(shortestDistanceCoord);
}
const lastPointDistancePart2 = this._points[this._points.length - 1][this._points[0].length - 1].distance;
return { part1: lastPointDistancePart1, part2: lastPointDistancePart2 };
}
private _findShortestDistance() {
let distance = Number.MAX_VALUE;
const shortestDistance = [null, null];
this._points.forEach((l, y) => {
l.forEach((c, x) => {
if (!c.visited && c.distance < distance) {
distance = c.distance;
shortestDistance[0] = y;
shortestDistance[1] = x;
}
});
});
return shortestDistance;
}
private _updateAdjacent(sDC) {
const distance = this._points[sDC[0]][sDC[1]].distance;
this._points[sDC[0]][sDC[1]].visited = true;
const yCoords = [sDC[0] + 1, sDC[0] - 1, sDC[0], sDC[0]];
const xCoords = [sDC[1], sDC[1], sDC[1] + 1, sDC[1] - 1];
for (let i = 0; i < yCoords.length; i++) {
if (this._points[yCoords[i]] && this._points[yCoords[i]][xCoords[i]]) {
const oldDistance = this._points[yCoords[i]][xCoords[i]].distance;
const newDistance = distance + this._points[yCoords[i]][xCoords[i]].value;
this._points[yCoords[i]][xCoords[i]].distance = oldDistance > newDistance ? newDistance : oldDistance;
}
}
}
private _initPoints(inputPoints) {
inputPoints.forEach((l, y) => {
if (!this._points[y]) {
this._points[y] = [];
}
l.forEach((c, x) => {
this._points[y][x] = { distance: Number.MAX_VALUE, value: c, visited: false };
});
});
this._points[0][0].distance = 0;
}
private _initBigPoints(inputPoints) {
const size = inputPoints.length;
inputPoints.forEach((l, y) => {
l.forEach((c, x) => {
for (let yy = 0; yy < 5; yy++) {
for (let xx = 0; xx < 5; xx++) {
if (!this._points[y + size * yy]) {
this._points[y + size * yy] = [];
}
const value = (c + yy + xx) % 9 === 0 ? 9 : (c + yy + xx) % 9;
this._points[y + size * yy][x + size * xx] = { distance: Number.MAX_VALUE, value, visited: false };
}
}
});
});
this._points[0][0].distance = 0;
}
}
|
a3c87e22c30072055cfbcdaba851bef6a0244dc3 | 3,226 | ts | TypeScript | src/infrastructure/service-utils/dto-mapper.ts | aspian-io/adrian-blog | 51380c2134ac20256d7535b2714b2853044251c4 | [
"MIT"
] | 1 | 2022-02-06T19:49:20.000Z | 2022-02-06T19:49:20.000Z | src/infrastructure/service-utils/dto-mapper.ts | aspian-io/adrian-blog | 51380c2134ac20256d7535b2714b2853044251c4 | [
"MIT"
] | null | null | null | src/infrastructure/service-utils/dto-mapper.ts | aspian-io/adrian-blog | 51380c2134ac20256d7535b2714b2853044251c4 | [
"MIT"
] | null | null | null | // /**
// * DTOs must extends this class
// */
export class DTOMapper {
dtoMapperProfile (): IDtoMapperOption<any>[] | undefined {
return undefined;
};
}
/**
* DTO Mapper Option Type
* @param T - Type of class
*/
export interface IDtoMapperOption<T> {
mapToClass?: IDtoMapperToClass<T>;
mapToPath?: IDtoMapperToPath;
}
// Mapping to class type
export interface IDtoMapperToClass<T> {
mapFromKey: string;
dtoClass: new () => T;
}
// mapping to path type
export interface IDtoMapperToPath {
mapFromKey: string;
valueFromPath: string;
}
/**
*
* Map source object to destination class
*
* @param {T} source - Source object to map from
* @param {U} destination - Destination class to map to
* @returns {U} An object of type U
*/
export function dtoMapper<T, U extends DTOMapper> (
source: T extends Array<any> ? never : T,
destination: new () => U
): U;
/**
*
* Map source object to destination class
*
* @param {T[]} source - Source array of objects to map from
* @param {U} destination - Destination class to which map each object from the source
* @returns {U[]} An array of type U
*/
export function dtoMapper<T, U extends DTOMapper> (
source: T[],
destination: new () => U
): U[];
export function dtoMapper<T, U extends DTOMapper> (
source: T | T[],
destination: new () => U
): U | U[] {
if ( Array.isArray( source ) ) {
return source.map( s => {
return mapper( s, new destination() );
} );
}
return mapper( source, new destination() );
}
// Mapper to map source to destination
function mapper<T, U extends DTOMapper> ( source: T, destination: U ): U {
Object.keys( destination ).forEach( key => {
destination[ key as keyof U ] = <any>source[ key as keyof T ];
if ( destination.dtoMapperProfile()?.length ) {
destination.dtoMapperProfile()?.forEach( option => {
// To class mapping (recursively)
if ( option.mapToClass?.mapFromKey === key ) {
if ( source[ key as keyof T ] ) {
if ( Array.isArray( source[ key as keyof T ] ) ) {
const result = Array.from( source[ key as keyof T ] as any ).map( el => {
return mapper( el, new option.mapToClass!.dtoClass() );
} );
destination[ key as keyof U ] = result as any;
} else {
const result = mapper( source[ key as keyof T ], new option.mapToClass.dtoClass() );
destination[ key as keyof U ] = result as any;
}
}
// To value mapping
} else if ( option.mapToPath?.mapFromKey === key ) {
let sourceVal: any;
if ( Array.isArray( option.mapToPath.valueFromPath.split( '.' ) ) ) {
const paths = option.mapToPath.valueFromPath.split( '.' );
paths.forEach( p => {
if ( !sourceVal ) {
sourceVal = source[ p as keyof T ];
} else {
sourceVal = sourceVal[ p ];
}
} );
} else {
sourceVal = <any>source[ option.mapToPath.valueFromPath as keyof T ];
}
destination[ key as keyof U ] = sourceVal;
}
} );
}
} );
return destination;
} | 29.87037 | 98 | 0.580285 | 74 | 8 | 2 | 13 | 4 | 6 | 2 | 8 | 4 | 4 | 14 | 13.875 | 871 | 0.02411 | 0.004592 | 0.006889 | 0.004592 | 0.016073 | 0.242424 | 0.121212 | 0.242975 | // /**
// * DTOs must extends this class
// */
export class DTOMapper {
dtoMapperProfile () {
return undefined;
};
}
/**
* DTO Mapper Option Type
* @param T - Type of class
*/
export interface IDtoMapperOption<T> {
mapToClass?;
mapToPath?;
}
// Mapping to class type
export interface IDtoMapperToClass<T> {
mapFromKey;
dtoClass;
}
// mapping to path type
export interface IDtoMapperToPath {
mapFromKey;
valueFromPath;
}
/**
*
* Map source object to destination class
*
* @param {T} source - Source object to map from
* @param {U} destination - Destination class to map to
* @returns {U} An object of type U
*/
export function dtoMapper<T, U extends DTOMapper> (
source,
destination
);
/**
*
* Map source object to destination class
*
* @param {T[]} source - Source array of objects to map from
* @param {U} destination - Destination class to which map each object from the source
* @returns {U[]} An array of type U
*/
export function dtoMapper<T, U extends DTOMapper> (
source,
destination
);
export function dtoMapper<T, U extends DTOMapper> (
source,
destination
) {
if ( Array.isArray( source ) ) {
return source.map( s => {
return mapper( s, new destination() );
} );
}
return mapper( source, new destination() );
}
// Mapper to map source to destination
/* Example usages of 'mapper' are shown below:
mapper(s, new destination());
mapper(source, new destination());
mapper(el, new option.mapToClass!.dtoClass());
mapper(source[key as keyof T], new option.mapToClass.dtoClass());
*/
function mapper<T, U extends DTOMapper> ( source, destination ) {
Object.keys( destination ).forEach( key => {
destination[ key as keyof U ] = <any>source[ key as keyof T ];
if ( destination.dtoMapperProfile()?.length ) {
destination.dtoMapperProfile()?.forEach( option => {
// To class mapping (recursively)
if ( option.mapToClass?.mapFromKey === key ) {
if ( source[ key as keyof T ] ) {
if ( Array.isArray( source[ key as keyof T ] ) ) {
const result = Array.from( source[ key as keyof T ] as any ).map( el => {
return mapper( el, new option.mapToClass!.dtoClass() );
} );
destination[ key as keyof U ] = result as any;
} else {
const result = mapper( source[ key as keyof T ], new option.mapToClass.dtoClass() );
destination[ key as keyof U ] = result as any;
}
}
// To value mapping
} else if ( option.mapToPath?.mapFromKey === key ) {
let sourceVal;
if ( Array.isArray( option.mapToPath.valueFromPath.split( '.' ) ) ) {
const paths = option.mapToPath.valueFromPath.split( '.' );
paths.forEach( p => {
if ( !sourceVal ) {
sourceVal = source[ p as keyof T ];
} else {
sourceVal = sourceVal[ p ];
}
} );
} else {
sourceVal = <any>source[ option.mapToPath.valueFromPath as keyof T ];
}
destination[ key as keyof U ] = sourceVal;
}
} );
}
} );
return destination;
} |
a3d0d102f121fd1bc264184794013ec8c867f62c | 2,219 | ts | TypeScript | packages/react-table/src/aggregationTypes.ts | dvh91/react-table | ca69c89008b216cf1f20bcbadc5ef92dbec9bc4e | [
"MIT"
] | 1 | 2022-03-09T05:24:51.000Z | 2022-03-09T05:24:51.000Z | packages/react-table/src/aggregationTypes.ts | dvh91/react-table | ca69c89008b216cf1f20bcbadc5ef92dbec9bc4e | [
"MIT"
] | null | null | null | packages/react-table/src/aggregationTypes.ts | dvh91/react-table | ca69c89008b216cf1f20bcbadc5ef92dbec9bc4e | [
"MIT"
] | null | null | null | export const aggregationTypes = {
sum,
min,
max,
extent,
mean,
median,
unique,
uniqueCount,
count,
}
export type BuiltInAggregationType = keyof typeof aggregationTypes
function sum(_leafValues: unknown[], childValues: unknown[]) {
// It's faster to just add the aggregations together instead of
// process leaf nodes individually
return childValues.reduce(
(sum: number, next: unknown) => sum + (typeof next === 'number' ? next : 0),
0
)
}
function min(_leafValues: unknown[], childValues: unknown[]) {
let min: number | undefined
for (const value of childValues as number[]) {
if (
value != null &&
(min! > value || (min === undefined && value >= value))
) {
min = value
}
}
return min
}
function max(_leafValues: unknown[], childValues: unknown[]) {
let max: number | undefined
for (const value of childValues as number[]) {
if (
value != null &&
(max! < value || (max === undefined && value >= value))
) {
max = value
}
}
return max
}
function extent(_leafValues: unknown[], childValues: unknown[]) {
let min: number | undefined
let max: number | undefined
for (const value of childValues as number[]) {
if (value != null) {
if (min === undefined) {
if (value >= value) min = max = value
} else {
if (min > value) min = value
if (max! < value) max = value
}
}
}
return [min, max]
}
function mean(leafValues: unknown[]) {
let count = 0
let sum = 0
for (let value of leafValues as number[]) {
if (value != null && (value = +value) >= value) {
++count, (sum += value)
}
}
if (count) return sum / count
return
}
function median(values: unknown[]) {
if (!values.length) {
return
}
let min = 0
let max = 0
values.forEach(value => {
if (typeof value === 'number') {
min = Math.min(min, value)
max = Math.max(max, value)
}
})
return (min + max) / 2
}
function unique<T>(values: T[]) {
return Array.from(new Set(values).values())
}
function uniqueCount(values: unknown[]) {
return new Set(values).size
}
function count(values: unknown[]) {
return values.length
}
| 19.12931 | 80 | 0.592159 | 91 | 11 | 0 | 16 | 9 | 0 | 2 | 0 | 22 | 1 | 6 | 6 | 620 | 0.043548 | 0.014516 | 0 | 0.001613 | 0.009677 | 0 | 0.611111 | 0.320256 | export const aggregationTypes = {
sum,
min,
max,
extent,
mean,
median,
unique,
uniqueCount,
count,
}
export type BuiltInAggregationType = keyof typeof aggregationTypes
/* Example usages of 'sum' are shown below:
;
sum + (typeof next === 'number' ? next : 0);
var sum = 0;
sum += value;
sum / count;
*/
function sum(_leafValues, childValues) {
// It's faster to just add the aggregations together instead of
// process leaf nodes individually
return childValues.reduce(
(sum, next) => sum + (typeof next === 'number' ? next : 0),
0
)
}
/* Example usages of 'min' are shown below:
;
var min;
min! > value || (min === undefined && value >= value);
min === undefined && value >= value;
min = value;
return min;
min === undefined;
min = max = value;
min > value;
[min, max];
var min = 0;
min = Math.min(min, value);
min + max;
*/
function min(_leafValues, childValues) {
let min
for (const value of childValues as number[]) {
if (
value != null &&
(min! > value || (min === undefined && value >= value))
) {
min = value
}
}
return min
}
/* Example usages of 'max' are shown below:
;
var max;
max! < value || (max === undefined && value >= value);
max === undefined && value >= value;
max = value;
return max;
min = max = value;
max! < value;
[min, max];
var max = 0;
max = Math.max(max, value);
min + max;
*/
function max(_leafValues, childValues) {
let max
for (const value of childValues as number[]) {
if (
value != null &&
(max! < value || (max === undefined && value >= value))
) {
max = value
}
}
return max
}
/* Example usages of 'extent' are shown below:
;
*/
function extent(_leafValues, childValues) {
let min
let max
for (const value of childValues as number[]) {
if (value != null) {
if (min === undefined) {
if (value >= value) min = max = value
} else {
if (min > value) min = value
if (max! < value) max = value
}
}
}
return [min, max]
}
/* Example usages of 'mean' are shown below:
;
*/
function mean(leafValues) {
let count = 0
let sum = 0
for (let value of leafValues as number[]) {
if (value != null && (value = +value) >= value) {
++count, (sum += value)
}
}
if (count) return sum / count
return
}
/* Example usages of 'median' are shown below:
;
*/
function median(values) {
if (!values.length) {
return
}
let min = 0
let max = 0
values.forEach(value => {
if (typeof value === 'number') {
min = Math.min(min, value)
max = Math.max(max, value)
}
})
return (min + max) / 2
}
/* Example usages of 'unique' are shown below:
;
*/
function unique<T>(values) {
return Array.from(new Set(values).values())
}
/* Example usages of 'uniqueCount' are shown below:
;
*/
function uniqueCount(values) {
return new Set(values).size
}
/* Example usages of 'count' are shown below:
;
var count = 0;
++count, (sum += value);
sum / count;
*/
function count(values) {
return values.length
}
|
a3e1dd02d438bd56221d60dc4674790870208976 | 4,068 | ts | TypeScript | src/utils/config-mach.ts | Disq-Code-Bot/dyarn | 9de5fce5161b46b07a88d75bc17b3c3ff9d14ee4 | [
"BSD-2-Clause"
] | 1 | 2022-03-29T15:53:46.000Z | 2022-03-29T15:53:46.000Z | src/utils/config-mach.ts | Disq-Code-Bot/dyarn | 9de5fce5161b46b07a88d75bc17b3c3ff9d14ee4 | [
"BSD-2-Clause"
] | null | null | null | src/utils/config-mach.ts | Disq-Code-Bot/dyarn | 9de5fce5161b46b07a88d75bc17b3c3ff9d14ee4 | [
"BSD-2-Clause"
] | null | null | null | interface RecursiveTypeCheckOverload {
(obj: Record<string, any>, againstObj: Record<string, any>):
{ checks: true } | { checks: false, err: string }
}
//TODO Improve error handling messages and overall code structure/algorithm
export const RecursiveTypeCheck: RecursiveTypeCheckOverload = (obj, againstObj) => {
for(const key in againstObj) {
//* In case type should be an array
if(key.startsWith('[]') || key.startsWith('_[]')) {
//* In case is optional: checking if is even defined
if(key.startsWith('_')) {
const keyNoArr = key.replace('_[]', '')
if(!obj[keyNoArr]) continue
}
const keyNoArr = key.replace(`${key.startsWith('_') ? '_[]' : '[]'}`, '')
//* In case is not defined and obligatory
if(!obj[keyNoArr]) return {
checks: false,
err: `The key '${keyNoArr}' is missing!`
}
//* In case is not array check type
if(!Array.isArray(obj[keyNoArr])) return {
checks: false,
err: `The key '${keyNoArr}' is not an array!`
}
//* In case is array get deeper
const arrCheck = Array.from(obj[keyNoArr]).map((value: any) =>
RecursiveTypeCheck(value, againstObj[key]))
for(const optionCheck of arrCheck) {
if(!optionCheck.checks) return optionCheck
}
}
//* In case type should be an object
else if(key.startsWith('{}') || key.startsWith('_{}')) {
//* In case is optional: checking if is even defined
if(key.startsWith('_')) {
const keyNoObj = key.replace('_{}', '')
if(!obj[keyNoObj]) continue
}
const keyNoObj = key.replace(`${key.startsWith('_') ? '_{}' : '{}'}`, '')
//* In case is not defined and obligatory
if(!obj[keyNoObj]) return {
checks: false,
err: `The key '${keyNoObj}' is missing!`
}
//* In case is not object check type
if(!(typeof obj[keyNoObj] === 'object')) return {
checks: false,
err: `The key '${keyNoObj}' is not an object!`
}
//* In case object may contain any key and value
if(againstObj[key] === "?") continue
//* In case is object get deeper
for(const checkObjChild in obj[keyNoObj]) {
const objectCheck = RecursiveTypeCheck(obj[keyNoObj][checkObjChild], againstObj[key])
if(!objectCheck.checks) return objectCheck
}
}
//* Checking if key is optional
else if(key.startsWith('_')) {
const keyNoUnder = key.replace('_', '')
//* Checking if value is even defined
if(!obj[keyNoUnder]) continue
//* In case is not object check type
if(typeof obj[keyNoUnder] !== typeof againstObj[key]) return {
checks: false,
err: `The key '${keyNoUnder}' is not of type '${typeof againstObj[key]}'!`
}
//* In case is object get deeper
if(typeof obj[keyNoUnder] === 'object') {
const checkObject = RecursiveTypeCheck(obj[keyNoUnder], againstObj[key])
if(!checkObject.checks) return checkObject
}
}
//* In case key is not optional and doesn't exist
else if(!obj[key]) return {
checks: false,
err: `The key '${key}' is missing inside your dyarn config file!`
}
//* Checking if key is of the right type
else if(typeof obj[key] !== typeof againstObj[key]) {
return {
checks: false,
err: `The key '${key}' is not of type '${typeof againstObj[key]}'`
}
}
//* Get deeper in case it's an object
else if(typeof obj[key] === 'object') {
if(againstObj[key] === "?") continue
const recursiveRes = RecursiveTypeCheck(obj[key], againstObj[key])
if(!recursiveRes.checks) return recursiveRes
}
}
return { checks: true }
} | 38.018692 | 97 | 0.546952 | 76 | 2 | 0 | 3 | 10 | 0 | 1 | 3 | 3 | 1 | 9 | 35.5 | 998 | 0.00501 | 0.01002 | 0 | 0.001002 | 0.009018 | 0.2 | 0.2 | 0.211689 | interface RecursiveTypeCheckOverload {
(obj, againstObj)
}
//TODO Improve error handling messages and overall code structure/algorithm
export /* Example usages of 'RecursiveTypeCheck' are shown below:
RecursiveTypeCheck(value, againstObj[key]);
RecursiveTypeCheck(obj[keyNoObj][checkObjChild], againstObj[key]);
RecursiveTypeCheck(obj[keyNoUnder], againstObj[key]);
RecursiveTypeCheck(obj[key], againstObj[key]);
*/
const RecursiveTypeCheck = (obj, againstObj) => {
for(const key in againstObj) {
//* In case type should be an array
if(key.startsWith('[]') || key.startsWith('_[]')) {
//* In case is optional: checking if is even defined
if(key.startsWith('_')) {
const keyNoArr = key.replace('_[]', '')
if(!obj[keyNoArr]) continue
}
const keyNoArr = key.replace(`${key.startsWith('_') ? '_[]' : '[]'}`, '')
//* In case is not defined and obligatory
if(!obj[keyNoArr]) return {
checks: false,
err: `The key '${keyNoArr}' is missing!`
}
//* In case is not array check type
if(!Array.isArray(obj[keyNoArr])) return {
checks: false,
err: `The key '${keyNoArr}' is not an array!`
}
//* In case is array get deeper
const arrCheck = Array.from(obj[keyNoArr]).map((value) =>
RecursiveTypeCheck(value, againstObj[key]))
for(const optionCheck of arrCheck) {
if(!optionCheck.checks) return optionCheck
}
}
//* In case type should be an object
else if(key.startsWith('{}') || key.startsWith('_{}')) {
//* In case is optional: checking if is even defined
if(key.startsWith('_')) {
const keyNoObj = key.replace('_{}', '')
if(!obj[keyNoObj]) continue
}
const keyNoObj = key.replace(`${key.startsWith('_') ? '_{}' : '{}'}`, '')
//* In case is not defined and obligatory
if(!obj[keyNoObj]) return {
checks: false,
err: `The key '${keyNoObj}' is missing!`
}
//* In case is not object check type
if(!(typeof obj[keyNoObj] === 'object')) return {
checks: false,
err: `The key '${keyNoObj}' is not an object!`
}
//* In case object may contain any key and value
if(againstObj[key] === "?") continue
//* In case is object get deeper
for(const checkObjChild in obj[keyNoObj]) {
const objectCheck = RecursiveTypeCheck(obj[keyNoObj][checkObjChild], againstObj[key])
if(!objectCheck.checks) return objectCheck
}
}
//* Checking if key is optional
else if(key.startsWith('_')) {
const keyNoUnder = key.replace('_', '')
//* Checking if value is even defined
if(!obj[keyNoUnder]) continue
//* In case is not object check type
if(typeof obj[keyNoUnder] !== typeof againstObj[key]) return {
checks: false,
err: `The key '${keyNoUnder}' is not of type '${typeof againstObj[key]}'!`
}
//* In case is object get deeper
if(typeof obj[keyNoUnder] === 'object') {
const checkObject = RecursiveTypeCheck(obj[keyNoUnder], againstObj[key])
if(!checkObject.checks) return checkObject
}
}
//* In case key is not optional and doesn't exist
else if(!obj[key]) return {
checks: false,
err: `The key '${key}' is missing inside your dyarn config file!`
}
//* Checking if key is of the right type
else if(typeof obj[key] !== typeof againstObj[key]) {
return {
checks: false,
err: `The key '${key}' is not of type '${typeof againstObj[key]}'`
}
}
//* Get deeper in case it's an object
else if(typeof obj[key] === 'object') {
if(againstObj[key] === "?") continue
const recursiveRes = RecursiveTypeCheck(obj[key], againstObj[key])
if(!recursiveRes.checks) return recursiveRes
}
}
return { checks: true }
} |
5d19ce050bd5135b5325905de8019e55bc87ff19 | 2,899 | ts | TypeScript | src/helpers/stop-loss.ts | mikekruithof22/apollo14 | f1bebed7d3cc39ce91f2061449693c64f5d5e9bc | [
"MIT"
] | 1 | 2022-01-04T04:33:16.000Z | 2022-01-04T04:33:16.000Z | src/helpers/stop-loss.ts | mikekruithof22/apollo14 | f1bebed7d3cc39ce91f2061449693c64f5d5e9bc | [
"MIT"
] | null | null | null | src/helpers/stop-loss.ts | mikekruithof22/apollo14 | f1bebed7d3cc39ce91f2061449693c64f5d5e9bc | [
"MIT"
] | null | null | null | export default class Stoploss {
public static stopLossCalculation = (startCandle, nextCandlesAfterHit, takeLossPercentage, takeProfitPercentage) => {
let message: string;
let sellResult: number = 0;
const takeLossPercentageInPercentage: number = takeLossPercentage / 100;
const takeLossPrice: number = (1 - takeLossPercentageInPercentage) * startCandle.close;
const takeProfitPercentageInPercentage: number = takeProfitPercentage / 100;
let takeProfitPrice: number = (1 + takeProfitPercentageInPercentage) * startCandle.close;
takeProfitPrice = Number(takeProfitPrice.toFixed(5));
for (var i = 0; i < nextCandlesAfterHit.length; i++) {
let comparisonCandle = Object.assign({}, nextCandlesAfterHit[i]);
if (comparisonCandle.low <= takeLossPrice && comparisonCandle.high >= takeProfitPrice) {
message = `Unknown - Profit limit and sell limit occured inside the same candle.`;
break;
} else if (comparisonCandle.high >= takeProfitPrice) {
message = `Profitable - After ${i} candles sold for: ${takeProfitPrice} at ${nextCandlesAfterHit[i].openTime}`;
sellResult = takeProfitPercentageInPercentage;
break;
} else if (comparisonCandle.low <= takeLossPrice) {
message = `Unprofitable - After ${i} candles sold for: ${takeLossPrice} at ${nextCandlesAfterHit[i].openTime}`;
sellResult = - takeLossPercentageInPercentage;
break;
} else {
message = `UNKOWN - UNABLE TO CALCULATE!`;
}
}
return {
message: message,
profitOrLossPercentage: sellResult
};
}
public static findHighestCandle = (nextCandlesAfterHit): string => {
let message: string;
if (nextCandlesAfterHit.length === 0) {
message = `No candle after hit found. Something might be wrong.`;
} else {
const candleWithHighstPrice = nextCandlesAfterHit.reduce(function (prev, current) {
return (prev.high > current.high) ? prev : current
});
message = `${candleWithHighstPrice.high} at ${candleWithHighstPrice.openTime}`;
}
return message;
}
public static findLowestCandle = (nextCandlesAfterHit): string => {
let message: string;
if (nextCandlesAfterHit.length === 0) {
message = `No candle after hit found. Something might be wrong.`;
} else {
const candleWithLowestPrice = nextCandlesAfterHit.reduce(function (prev, current) {
return (prev.low > current.low) ? prev : current
});
message = `${candleWithLowestPrice.low} at ${candleWithLowestPrice.openTime} `;
}
return message;
}
}
| 44.6 | 128 | 0.61504 | 56 | 5 | 0 | 10 | 12 | 3 | 0 | 0 | 10 | 1 | 0 | 10 | 686 | 0.021866 | 0.017493 | 0.004373 | 0.001458 | 0 | 0 | 0.333333 | 0.280298 | export default class Stoploss {
public static stopLossCalculation = (startCandle, nextCandlesAfterHit, takeLossPercentage, takeProfitPercentage) => {
let message;
let sellResult = 0;
const takeLossPercentageInPercentage = takeLossPercentage / 100;
const takeLossPrice = (1 - takeLossPercentageInPercentage) * startCandle.close;
const takeProfitPercentageInPercentage = takeProfitPercentage / 100;
let takeProfitPrice = (1 + takeProfitPercentageInPercentage) * startCandle.close;
takeProfitPrice = Number(takeProfitPrice.toFixed(5));
for (var i = 0; i < nextCandlesAfterHit.length; i++) {
let comparisonCandle = Object.assign({}, nextCandlesAfterHit[i]);
if (comparisonCandle.low <= takeLossPrice && comparisonCandle.high >= takeProfitPrice) {
message = `Unknown - Profit limit and sell limit occured inside the same candle.`;
break;
} else if (comparisonCandle.high >= takeProfitPrice) {
message = `Profitable - After ${i} candles sold for: ${takeProfitPrice} at ${nextCandlesAfterHit[i].openTime}`;
sellResult = takeProfitPercentageInPercentage;
break;
} else if (comparisonCandle.low <= takeLossPrice) {
message = `Unprofitable - After ${i} candles sold for: ${takeLossPrice} at ${nextCandlesAfterHit[i].openTime}`;
sellResult = - takeLossPercentageInPercentage;
break;
} else {
message = `UNKOWN - UNABLE TO CALCULATE!`;
}
}
return {
message: message,
profitOrLossPercentage: sellResult
};
}
public static findHighestCandle = (nextCandlesAfterHit) => {
let message;
if (nextCandlesAfterHit.length === 0) {
message = `No candle after hit found. Something might be wrong.`;
} else {
const candleWithHighstPrice = nextCandlesAfterHit.reduce(function (prev, current) {
return (prev.high > current.high) ? prev : current
});
message = `${candleWithHighstPrice.high} at ${candleWithHighstPrice.openTime}`;
}
return message;
}
public static findLowestCandle = (nextCandlesAfterHit) => {
let message;
if (nextCandlesAfterHit.length === 0) {
message = `No candle after hit found. Something might be wrong.`;
} else {
const candleWithLowestPrice = nextCandlesAfterHit.reduce(function (prev, current) {
return (prev.low > current.low) ? prev : current
});
message = `${candleWithLowestPrice.low} at ${candleWithLowestPrice.openTime} `;
}
return message;
}
}
|
5d2036de1c12012a440806dbc109ba41bb49e194 | 3,368 | ts | TypeScript | utils/overlayPhoto.ts | dappweaver/ooxxnft_web | df249e520eab5f28576d1f4066a5245f8ee64fa2 | [
"MIT"
] | null | null | null | utils/overlayPhoto.ts | dappweaver/ooxxnft_web | df249e520eab5f28576d1f4066a5245f8ee64fa2 | [
"MIT"
] | null | null | null | utils/overlayPhoto.ts | dappweaver/ooxxnft_web | df249e520eab5f28576d1f4066a5245f8ee64fa2 | [
"MIT"
] | 1 | 2022-03-12T15:22:33.000Z | 2022-03-12T15:22:33.000Z |
export const SVG_W = 440;
export const SVG_H = 660;
export const NewGameSVG = `<svg xmlns="http://www.w3.org/2000/svg" preserveAspectRatio="xMinYMin meet" viewBox="0 0 420 660"><style>.base { fill: white; font-family: serif; font-size: 14px; }</style><rect width="100%" height="100%" fill="black" /><line x1="140" y1="0" x2="140" y2="420" stroke="white" stroke-width="3" /><line x1="280" y1="0" x2="280" y2="420" stroke="white" stroke-width="3" /><line x1="0" y1="140" x2="420" y2="140" stroke="white" stroke-width="3" /><line x1="0" y1="280" x2="420" y2="280" stroke="white" stroke-width="3" /></svg>`;
export function getSharpIdx(x: number, y: number) {
// console.log(`getSharpIdx() x:${x}, y: ${y}`);
let yInd = (y < (130 / 660)) ? 0 :
(y > (150 / 660) && y < (270 / 660)) ? 1 :
(y > (290 / 660) && y < (410 / 660)) ? 2 : -1;
if (yInd < 0) {
return -1;
}
let xInd = (x < (130 / 420)) ? 0 :
(x > (150 / 420) && x < (270 / 420)) ? 1 :
(x > (290 / 420) && x < (420 / 420)) ? 2 : -1;
if (xInd < 0) {
return -1;
}
return xInd + yInd * 3;
}
function decimalToHex(d: number) {
var hex = Number(d).toString(16);
hex = "000000".substr(0, 6 - hex.length) + hex;
return hex;
}
export function xmlDrawO(xmlDoc: any, space: number, color: number) {
// console.log("xmlDrawO:, space:", space);
const x = (space % 3) * 140 + 70;
const y = Math.floor(space / 3) * 140 + 70;
let o = xmlDoc.createElementNS(xmlDoc.documentElement.namespaceURI, "circle");
o.setAttribute('cx', x);
o.setAttribute('cy', y);
o.setAttribute('r', '50');
o.setAttribute("stroke", "#" + decimalToHex(color));
o.setAttribute("stroke-width", "3");
o.setAttribute("fill", "none");
xmlDoc.childNodes[0].insertBefore(o, xmlDoc.childNodes[0].childNodes[3]);
}
export function xmlDrawX(xmlDoc: any, space: number, color: number) {
const x = (space % 3) * 140 + 20;
const y = Math.floor(space / 3) * 140 + 20;
// console.log("xmlDrawO:, space:", space);
// console.log(`x=${x}, y=${y}`);
// '\' of 'X'
let l1 = xmlDoc.createElementNS(xmlDoc.documentElement.namespaceURI, "line");
l1.setAttribute('x1', x);
l1.setAttribute('y1', y);
l1.setAttribute('x2', x + 100);
l1.setAttribute('y2', y + 100);
l1.setAttribute("stroke", "#" + decimalToHex(color));
l1.setAttribute("stroke-width", "3");
// '/' of 'X'
let l2 = xmlDoc.createElementNS(xmlDoc.documentElement.namespaceURI, "line");
l2.setAttribute('x1', x + 100);
l2.setAttribute('y1', y);
l2.setAttribute('x2', x);
l2.setAttribute('y2', y + 100);
l2.setAttribute("stroke", "#" + decimalToHex(color));
l2.setAttribute("stroke-width", "3");
xmlDoc.childNodes[0].insertBefore(l1, xmlDoc.childNodes[0].childNodes[3]);
xmlDoc.childNodes[0].insertBefore(l2, xmlDoc.childNodes[0].childNodes[3]);
}
function getBoolean(_packedBools: number, _boolNumber: number) {
const flag = (_packedBools >> _boolNumber) & (1);
return (flag == 1 ? true : false);
}
export function getSpaceOXChar(marksO: number, marksX: number, space: number) {
const o = getBoolean(marksO, space);
if (o) {
return 'O';
}
const x = getBoolean(marksX, space);
if (x) {
return 'X';
}
return null;
} | 34.020202 | 551 | 0.585808 | 70 | 6 | 0 | 14 | 16 | 0 | 2 | 2 | 12 | 0 | 0 | 9.166667 | 1,270 | 0.015748 | 0.012598 | 0 | 0 | 0 | 0.055556 | 0.333333 | 0.247252 |
export const SVG_W = 440;
export const SVG_H = 660;
export const NewGameSVG = `<svg xmlns="http://www.w3.org/2000/svg" preserveAspectRatio="xMinYMin meet" viewBox="0 0 420 660"><style>.base { fill: white; font-family: serif; font-size: 14px; }</style><rect width="100%" height="100%" fill="black" /><line x1="140" y1="0" x2="140" y2="420" stroke="white" stroke-width="3" /><line x1="280" y1="0" x2="280" y2="420" stroke="white" stroke-width="3" /><line x1="0" y1="140" x2="420" y2="140" stroke="white" stroke-width="3" /><line x1="0" y1="280" x2="420" y2="280" stroke="white" stroke-width="3" /></svg>`;
export function getSharpIdx(x, y) {
// console.log(`getSharpIdx() x:${x}, y: ${y}`);
let yInd = (y < (130 / 660)) ? 0 :
(y > (150 / 660) && y < (270 / 660)) ? 1 :
(y > (290 / 660) && y < (410 / 660)) ? 2 : -1;
if (yInd < 0) {
return -1;
}
let xInd = (x < (130 / 420)) ? 0 :
(x > (150 / 420) && x < (270 / 420)) ? 1 :
(x > (290 / 420) && x < (420 / 420)) ? 2 : -1;
if (xInd < 0) {
return -1;
}
return xInd + yInd * 3;
}
/* Example usages of 'decimalToHex' are shown below:
o.setAttribute("stroke", "#" + decimalToHex(color));
l1.setAttribute("stroke", "#" + decimalToHex(color));
l2.setAttribute("stroke", "#" + decimalToHex(color));
*/
function decimalToHex(d) {
var hex = Number(d).toString(16);
hex = "000000".substr(0, 6 - hex.length) + hex;
return hex;
}
export function xmlDrawO(xmlDoc, space, color) {
// console.log("xmlDrawO:, space:", space);
const x = (space % 3) * 140 + 70;
const y = Math.floor(space / 3) * 140 + 70;
let o = xmlDoc.createElementNS(xmlDoc.documentElement.namespaceURI, "circle");
o.setAttribute('cx', x);
o.setAttribute('cy', y);
o.setAttribute('r', '50');
o.setAttribute("stroke", "#" + decimalToHex(color));
o.setAttribute("stroke-width", "3");
o.setAttribute("fill", "none");
xmlDoc.childNodes[0].insertBefore(o, xmlDoc.childNodes[0].childNodes[3]);
}
export function xmlDrawX(xmlDoc, space, color) {
const x = (space % 3) * 140 + 20;
const y = Math.floor(space / 3) * 140 + 20;
// console.log("xmlDrawO:, space:", space);
// console.log(`x=${x}, y=${y}`);
// '\' of 'X'
let l1 = xmlDoc.createElementNS(xmlDoc.documentElement.namespaceURI, "line");
l1.setAttribute('x1', x);
l1.setAttribute('y1', y);
l1.setAttribute('x2', x + 100);
l1.setAttribute('y2', y + 100);
l1.setAttribute("stroke", "#" + decimalToHex(color));
l1.setAttribute("stroke-width", "3");
// '/' of 'X'
let l2 = xmlDoc.createElementNS(xmlDoc.documentElement.namespaceURI, "line");
l2.setAttribute('x1', x + 100);
l2.setAttribute('y1', y);
l2.setAttribute('x2', x);
l2.setAttribute('y2', y + 100);
l2.setAttribute("stroke", "#" + decimalToHex(color));
l2.setAttribute("stroke-width", "3");
xmlDoc.childNodes[0].insertBefore(l1, xmlDoc.childNodes[0].childNodes[3]);
xmlDoc.childNodes[0].insertBefore(l2, xmlDoc.childNodes[0].childNodes[3]);
}
/* Example usages of 'getBoolean' are shown below:
getBoolean(marksO, space);
getBoolean(marksX, space);
*/
function getBoolean(_packedBools, _boolNumber) {
const flag = (_packedBools >> _boolNumber) & (1);
return (flag == 1 ? true : false);
}
export function getSpaceOXChar(marksO, marksX, space) {
const o = getBoolean(marksO, space);
if (o) {
return 'O';
}
const x = getBoolean(marksX, space);
if (x) {
return 'X';
}
return null;
} |
5df08bc984ff9aa5bbc66b68ebf7b948d951bbac | 3,952 | ts | TypeScript | libs/imagery/CoordTransform.ts | ts-gis/ts-cesium-lib | 6937e7d905037d3555bbcfe7561867b5a23f13fe | [
"Apache-2.0"
] | 1 | 2022-01-06T01:21:31.000Z | 2022-01-06T01:21:31.000Z | libs/imagery/CoordTransform.ts | ts-gis/ts-cesium-lib | 6937e7d905037d3555bbcfe7561867b5a23f13fe | [
"Apache-2.0"
] | null | null | null | libs/imagery/CoordTransform.ts | ts-gis/ts-cesium-lib | 6937e7d905037d3555bbcfe7561867b5a23f13fe | [
"Apache-2.0"
] | null | null | null | const BD_FACTOR = (3.14159265358979324 * 3000.0) / 180.0
const PI = 3.1415926535897932384626
const RADIUS = 6378245.0
const EE = 0.00669342162296594323
class CoordTransform {
/**
* BD-09 To GCJ-02
* @param lng
* @param lat
* @returns {number[]}
*/
static BD09ToGCJ02(lng:number, lat:number) {
let x = +lng - 0.0065
let y = +lat - 0.006
let z = Math.sqrt(x * x + y * y) - 0.00002 * Math.sin(y * BD_FACTOR)
let theta = Math.atan2(y, x) - 0.000003 * Math.cos(x * BD_FACTOR)
let gg_lng = z * Math.cos(theta)
let gg_lat = z * Math.sin(theta)
return [gg_lng, gg_lat]
}
/**
* GCJ-02 To BD-09
* @param lng
* @param lat
* @returns {number[]}
* @constructor
*/
static GCJ02ToBD09(lng:number, lat:number) {
lat = +lat
lng = +lng
let z =
Math.sqrt(lng * lng + lat * lat) + 0.00002 * Math.sin(lat * BD_FACTOR)
let theta = Math.atan2(lat, lng) + 0.000003 * Math.cos(lng * BD_FACTOR)
let bd_lng = z * Math.cos(theta) + 0.0065
let bd_lat = z * Math.sin(theta) + 0.006
return [bd_lng, bd_lat]
}
/**
* WGS-84 To GCJ-02
* @param lng
* @param lat
* @returns {number[]}
*/
static WGS84ToGCJ02(lng:number, lat:number) {
lat = +lat
lng = +lng
if (this.out_of_china(lng, lat)) {
return [lng, lat]
} else {
let d = this.delta(lng, lat)
return [lng + d[0], lat + d[1]]
}
}
/**
* GCJ-02 To WGS-84
* @param lng
* @param lat
* @returns {number[]}
* @constructor
*/
static GCJ02ToWGS84(lng:number, lat:number) {
lat = +lat
lng = +lng
if (this.out_of_china(lng, lat)) {
return [lng, lat]
} else {
let d = this.delta(lng, lat)
let mgLng = lng + d[0]
let mgLat = lat + d[1]
return [lng * 2 - mgLng, lat * 2 - mgLat]
}
}
/**
*
* @param lng
* @param lat
* @returns {number[]}
*/
static delta(lng:number, lat:number) {
let dLng = this.transformLng(lng - 105, lat - 35)
let dLat = this.transformLat(lng - 105, lat - 35)
const radLat = (lat / 180) * PI
let magic = Math.sin(radLat)
magic = 1 - EE * magic * magic
const sqrtMagic = Math.sqrt(magic)
dLng = (dLng * 180) / ((RADIUS / sqrtMagic) * Math.cos(radLat) * PI)
dLat = (dLat * 180) / (((RADIUS * (1 - EE)) / (magic * sqrtMagic)) * PI)
return [dLng, dLat]
}
/**
*
* @param lng
* @param lat
* @returns {number}
*/
static transformLng(lng:number, lat:number) {
lat = +lat
lng = +lng
let ret =
300.0 +
lng +
2.0 * lat +
0.1 * lng * lng +
0.1 * lng * lat +
0.1 * Math.sqrt(Math.abs(lng))
ret +=
((20.0 * Math.sin(6.0 * lng * PI) + 20.0 * Math.sin(2.0 * lng * PI)) *
2.0) /
3.0
ret +=
((20.0 * Math.sin(lng * PI) + 40.0 * Math.sin((lng / 3.0) * PI)) * 2.0) /
3.0
ret +=
((150.0 * Math.sin((lng / 12.0) * PI) +
300.0 * Math.sin((lng / 30.0) * PI)) *
2.0) /
3.0
return ret
}
/**
*
* @param lng
* @param lat
* @returns {number}
*/
static transformLat(lng:number, lat:number) {
lat = +lat
lng = +lng
let ret =
-100.0 +
2.0 * lng +
3.0 * lat +
0.2 * lat * lat +
0.1 * lng * lat +
0.2 * Math.sqrt(Math.abs(lng))
ret +=
((20.0 * Math.sin(6.0 * lng * PI) + 20.0 * Math.sin(2.0 * lng * PI)) *
2.0) /
3.0
ret +=
((20.0 * Math.sin(lat * PI) + 40.0 * Math.sin((lat / 3.0) * PI)) * 2.0) /
3.0
ret +=
((160.0 * Math.sin((lat / 12.0) * PI) +
320 * Math.sin((lat * PI) / 30.0)) *
2.0) /
3.0
return ret
}
/**
*
* @param lng
* @param lat
* @returns {boolean}
*/
static out_of_china(lng:number, lat:number) {
lat = +lat
lng = +lng
return !(lng > 73.66 && lng < 135.05 && lat > 3.86 && lat < 53.55)
}
}
export default CoordTransform | 23.111111 | 79 | 0.503796 | 112 | 8 | 0 | 16 | 25 | 0 | 4 | 0 | 16 | 1 | 0 | 11.125 | 1,634 | 0.014688 | 0.0153 | 0 | 0.000612 | 0 | 0 | 0.326531 | 0.256 | const BD_FACTOR = (3.14159265358979324 * 3000.0) / 180.0
const PI = 3.1415926535897932384626
const RADIUS = 6378245.0
const EE = 0.00669342162296594323
class CoordTransform {
/**
* BD-09 To GCJ-02
* @param lng
* @param lat
* @returns {number[]}
*/
static BD09ToGCJ02(lng, lat) {
let x = +lng - 0.0065
let y = +lat - 0.006
let z = Math.sqrt(x * x + y * y) - 0.00002 * Math.sin(y * BD_FACTOR)
let theta = Math.atan2(y, x) - 0.000003 * Math.cos(x * BD_FACTOR)
let gg_lng = z * Math.cos(theta)
let gg_lat = z * Math.sin(theta)
return [gg_lng, gg_lat]
}
/**
* GCJ-02 To BD-09
* @param lng
* @param lat
* @returns {number[]}
* @constructor
*/
static GCJ02ToBD09(lng, lat) {
lat = +lat
lng = +lng
let z =
Math.sqrt(lng * lng + lat * lat) + 0.00002 * Math.sin(lat * BD_FACTOR)
let theta = Math.atan2(lat, lng) + 0.000003 * Math.cos(lng * BD_FACTOR)
let bd_lng = z * Math.cos(theta) + 0.0065
let bd_lat = z * Math.sin(theta) + 0.006
return [bd_lng, bd_lat]
}
/**
* WGS-84 To GCJ-02
* @param lng
* @param lat
* @returns {number[]}
*/
static WGS84ToGCJ02(lng, lat) {
lat = +lat
lng = +lng
if (this.out_of_china(lng, lat)) {
return [lng, lat]
} else {
let d = this.delta(lng, lat)
return [lng + d[0], lat + d[1]]
}
}
/**
* GCJ-02 To WGS-84
* @param lng
* @param lat
* @returns {number[]}
* @constructor
*/
static GCJ02ToWGS84(lng, lat) {
lat = +lat
lng = +lng
if (this.out_of_china(lng, lat)) {
return [lng, lat]
} else {
let d = this.delta(lng, lat)
let mgLng = lng + d[0]
let mgLat = lat + d[1]
return [lng * 2 - mgLng, lat * 2 - mgLat]
}
}
/**
*
* @param lng
* @param lat
* @returns {number[]}
*/
static delta(lng, lat) {
let dLng = this.transformLng(lng - 105, lat - 35)
let dLat = this.transformLat(lng - 105, lat - 35)
const radLat = (lat / 180) * PI
let magic = Math.sin(radLat)
magic = 1 - EE * magic * magic
const sqrtMagic = Math.sqrt(magic)
dLng = (dLng * 180) / ((RADIUS / sqrtMagic) * Math.cos(radLat) * PI)
dLat = (dLat * 180) / (((RADIUS * (1 - EE)) / (magic * sqrtMagic)) * PI)
return [dLng, dLat]
}
/**
*
* @param lng
* @param lat
* @returns {number}
*/
static transformLng(lng, lat) {
lat = +lat
lng = +lng
let ret =
300.0 +
lng +
2.0 * lat +
0.1 * lng * lng +
0.1 * lng * lat +
0.1 * Math.sqrt(Math.abs(lng))
ret +=
((20.0 * Math.sin(6.0 * lng * PI) + 20.0 * Math.sin(2.0 * lng * PI)) *
2.0) /
3.0
ret +=
((20.0 * Math.sin(lng * PI) + 40.0 * Math.sin((lng / 3.0) * PI)) * 2.0) /
3.0
ret +=
((150.0 * Math.sin((lng / 12.0) * PI) +
300.0 * Math.sin((lng / 30.0) * PI)) *
2.0) /
3.0
return ret
}
/**
*
* @param lng
* @param lat
* @returns {number}
*/
static transformLat(lng, lat) {
lat = +lat
lng = +lng
let ret =
-100.0 +
2.0 * lng +
3.0 * lat +
0.2 * lat * lat +
0.1 * lng * lat +
0.2 * Math.sqrt(Math.abs(lng))
ret +=
((20.0 * Math.sin(6.0 * lng * PI) + 20.0 * Math.sin(2.0 * lng * PI)) *
2.0) /
3.0
ret +=
((20.0 * Math.sin(lat * PI) + 40.0 * Math.sin((lat / 3.0) * PI)) * 2.0) /
3.0
ret +=
((160.0 * Math.sin((lat / 12.0) * PI) +
320 * Math.sin((lat * PI) / 30.0)) *
2.0) /
3.0
return ret
}
/**
*
* @param lng
* @param lat
* @returns {boolean}
*/
static out_of_china(lng, lat) {
lat = +lat
lng = +lng
return !(lng > 73.66 && lng < 135.05 && lat > 3.86 && lat < 53.55)
}
}
export default CoordTransform |
574a90b8366d07f821fdec6eb1f5c102e754c994 | 3,759 | ts | TypeScript | src/utils/PitchUtil.ts | igorski/molecular-music-generator-web | b1265ab84a18e893d71bf537a534dc730d090f21 | [
"MIT"
] | 5 | 2022-02-02T01:45:08.000Z | 2022-03-03T23:17:28.000Z | src/utils/PitchUtil.ts | igorski/molecular-music-generator-web | b1265ab84a18e893d71bf537a534dc730d090f21 | [
"MIT"
] | null | null | null | src/utils/PitchUtil.ts | igorski/molecular-music-generator-web | b1265ab84a18e893d71bf537a534dc730d090f21 | [
"MIT"
] | null | null | null | /**
* The MIT License (MIT)
*
* Igor Zinken 2016-2022 - https://www.igorski.nl
*
* 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.
*/
/**
* order of note names within a single octave
*/
export const OCTAVE_SCALE: Array<string> = [ "C", "C#", "D", "D#", "E", "F", "F#", "G", "G#", "A", "A#", "B" ];
/**
* @param {string} aNote - musical note to return ( A, B, C, D, E, F, G with
* possible enharmonic notes ( 'b' meaning 'flat', '#' meaning 'sharp' )
* NOTE: flats are CASE sensitive ( to prevent seeing the note 'B' instead of 'b' )
* @param {number} aOctave - the octave to return ( accepted range 0 - 9 )
* @return {number} containing exact frequency in Hz for requested note
*/
export const getFrequency = ( aNote: string, aOctave: number ): number => {
let freq;
let enharmonic = 0;
// detect flat enharmonic
let i = aNote.indexOf( "b" );
if ( i > -1 ) {
aNote = aNote.substr( i - 1, 1 );
enharmonic = -1;
}
// detect sharp enharmonic
i = aNote.indexOf( "#" );
if ( i > -1 ) {
aNote = aNote.substr( i - 1, 1 );
enharmonic = 1;
}
freq = getOctaveIndex( aNote, enharmonic );
if ( aOctave === 4 ) {
return freq;
}
else {
// translate the pitches to the requested octave
const d = aOctave - 4;
let j = Math.abs( d );
for ( i = 0; i < j; ++i ) {
if ( d > 0 ) {
freq *= 2;
}
else {
freq *= 0.5;
}
}
return freq;
}
};
/* internal methods */
/**
* pitch table for all notes from C to B at octave 4
* which is used for calculating all pitches at other octaves
*/
const OCTAVE: Array<number> = [
261.626, 277.183, 293.665, 311.127, 329.628, 349.228, 369.994, 391.995, 415.305, 440, 466.164, 493.883
];
/**
* retrieves the index in the octave array for a given note
* modifier enharmonic returns the previous ( for a 'flat' note )
* or next ( for a 'sharp' note ) index
*
* @param {string} aNote ( A, B, C, D, E, F, G )
* @param {number=} aEnharmonic optional, defaults to 0 ( 0, -1 for flat, 1 for sharp )
* @return {number}
*/
function getOctaveIndex( aNote: string, aEnharmonic?: number ): number {
if ( typeof aEnharmonic !== "number" ) {
aEnharmonic = 0;
}
for ( let i = 0, j = OCTAVE.length; i < j; ++i ) {
if ( OCTAVE_SCALE[ i ] === aNote ) {
let k = i + aEnharmonic;
if ( k > j ) {
return OCTAVE[ 0 ];
}
if ( k < 0 ) {
return OCTAVE[ OCTAVE.length - 1 ];
}
return OCTAVE[ k ];
}
}
return NaN;
}
| 32.686957 | 111 | 0.58872 | 53 | 2 | 0 | 4 | 11 | 0 | 1 | 0 | 8 | 0 | 1 | 22.5 | 1,157 | 0.005186 | 0.009507 | 0 | 0 | 0.000864 | 0 | 0.470588 | 0.212809 | /**
* The MIT License (MIT)
*
* Igor Zinken 2016-2022 - https://www.igorski.nl
*
* 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.
*/
/**
* order of note names within a single octave
*/
export const OCTAVE_SCALE = [ "C", "C#", "D", "D#", "E", "F", "F#", "G", "G#", "A", "A#", "B" ];
/**
* @param {string} aNote - musical note to return ( A, B, C, D, E, F, G with
* possible enharmonic notes ( 'b' meaning 'flat', '#' meaning 'sharp' )
* NOTE: flats are CASE sensitive ( to prevent seeing the note 'B' instead of 'b' )
* @param {number} aOctave - the octave to return ( accepted range 0 - 9 )
* @return {number} containing exact frequency in Hz for requested note
*/
export const getFrequency = ( aNote, aOctave ) => {
let freq;
let enharmonic = 0;
// detect flat enharmonic
let i = aNote.indexOf( "b" );
if ( i > -1 ) {
aNote = aNote.substr( i - 1, 1 );
enharmonic = -1;
}
// detect sharp enharmonic
i = aNote.indexOf( "#" );
if ( i > -1 ) {
aNote = aNote.substr( i - 1, 1 );
enharmonic = 1;
}
freq = getOctaveIndex( aNote, enharmonic );
if ( aOctave === 4 ) {
return freq;
}
else {
// translate the pitches to the requested octave
const d = aOctave - 4;
let j = Math.abs( d );
for ( i = 0; i < j; ++i ) {
if ( d > 0 ) {
freq *= 2;
}
else {
freq *= 0.5;
}
}
return freq;
}
};
/* internal methods */
/**
* pitch table for all notes from C to B at octave 4
* which is used for calculating all pitches at other octaves
*/
const OCTAVE = [
261.626, 277.183, 293.665, 311.127, 329.628, 349.228, 369.994, 391.995, 415.305, 440, 466.164, 493.883
];
/**
* retrieves the index in the octave array for a given note
* modifier enharmonic returns the previous ( for a 'flat' note )
* or next ( for a 'sharp' note ) index
*
* @param {string} aNote ( A, B, C, D, E, F, G )
* @param {number=} aEnharmonic optional, defaults to 0 ( 0, -1 for flat, 1 for sharp )
* @return {number}
*/
/* Example usages of 'getOctaveIndex' are shown below:
freq = getOctaveIndex(aNote, enharmonic);
*/
function getOctaveIndex( aNote, aEnharmonic? ) {
if ( typeof aEnharmonic !== "number" ) {
aEnharmonic = 0;
}
for ( let i = 0, j = OCTAVE.length; i < j; ++i ) {
if ( OCTAVE_SCALE[ i ] === aNote ) {
let k = i + aEnharmonic;
if ( k > j ) {
return OCTAVE[ 0 ];
}
if ( k < 0 ) {
return OCTAVE[ OCTAVE.length - 1 ];
}
return OCTAVE[ k ];
}
}
return NaN;
}
|
57c96f4bfc6c09374f01c03292bc09d487ea9ade | 2,263 | ts | TypeScript | src/note_durations.ts | bawierino/noiez | c2649008a29b8e811f77c14832c4bfd52e3fd94a | [
"MIT"
] | 1 | 2022-02-11T07:51:37.000Z | 2022-02-11T07:51:37.000Z | src/note_durations.ts | bawierino/noiez | c2649008a29b8e811f77c14832c4bfd52e3fd94a | [
"MIT"
] | null | null | null | src/note_durations.ts | bawierino/noiez | c2649008a29b8e811f77c14832c4bfd52e3fd94a | [
"MIT"
] | null | null | null | const noteDurationModifiers = {
dotted: 3 / 2,
triplet: 2 / 3,
quintuplet: 4 / 5,
septuplet: 4 / 7,
nonuplet: 8 / 9,
};
export type NTupletValue = 3 | 5 | 7 | 9;
export enum NoteDivision {
FULL = "FULL",
HALF = "HALF",
QUARTER = "QUARTER",
EIGHTH = "EIGHTH",
SIXTEENTH = "SIXTEENTH",
THIRTYSECOND = "THIRTYSECOND",
SIXTYFOURTH = "SIXTYFOURTH",
ONEHUNDERDANDTWENTYEIGHTH = "ONEHUNDERDANDTWENTYEIGHTH",
}
export function getNoteDuration(model: {
bpm: number;
noteDivision: NoteDivision;
nTupletValue?: NTupletValue;
dotted?: boolean;
}): number {
const {
bpm,
noteDivision,
dotted = false,
nTupletValue = undefined,
} = model;
const noteDivisionRatio = getNoteDivisionRatio(noteDivision);
const nTupletRatio = nTupletValue ? getNTupletRatio(nTupletValue) : 1;
const dottedRatio = dotted ? noteDurationModifiers.dotted : 1;
const durationOfOneMeasure = (60 * 1000 * 4) / bpm;
return (
durationOfOneMeasure * noteDivisionRatio * nTupletRatio * dottedRatio
);
}
function getNoteDivisionRatio(noteDivision: NoteDivision): number {
switch (noteDivision) {
case NoteDivision.FULL:
return 1;
case NoteDivision.HALF:
return 1 / 2;
case NoteDivision.QUARTER:
return 1 / 4;
case NoteDivision.EIGHTH:
return 1 / 8;
case NoteDivision.SIXTEENTH:
return 1 / 16;
case NoteDivision.THIRTYSECOND:
return 1 / 32;
case NoteDivision.SIXTYFOURTH:
return 1 / 64;
case NoteDivision.ONEHUNDERDANDTWENTYEIGHTH:
return 1 / 128;
default:
throw new Error(`Unknown note division ${noteDivision}`);
}
}
function getNTupletRatio(nTupletValue: NTupletValue): number {
switch (nTupletValue) {
case 3:
return noteDurationModifiers.triplet;
case 5:
return noteDurationModifiers.quintuplet;
case 7:
return noteDurationModifiers.septuplet;
case 9:
return noteDurationModifiers.nonuplet;
default:
throw new Error(`Unknown nTupletValue ${nTupletValue}`);
}
}
| 26.940476 | 77 | 0.615996 | 74 | 3 | 0 | 3 | 6 | 0 | 2 | 0 | 5 | 1 | 0 | 15 | 680 | 0.008824 | 0.008824 | 0 | 0.001471 | 0 | 0 | 0.416667 | 0.221884 | const noteDurationModifiers = {
dotted: 3 / 2,
triplet: 2 / 3,
quintuplet: 4 / 5,
septuplet: 4 / 7,
nonuplet: 8 / 9,
};
export type NTupletValue = 3 | 5 | 7 | 9;
export enum NoteDivision {
FULL = "FULL",
HALF = "HALF",
QUARTER = "QUARTER",
EIGHTH = "EIGHTH",
SIXTEENTH = "SIXTEENTH",
THIRTYSECOND = "THIRTYSECOND",
SIXTYFOURTH = "SIXTYFOURTH",
ONEHUNDERDANDTWENTYEIGHTH = "ONEHUNDERDANDTWENTYEIGHTH",
}
export function getNoteDuration(model) {
const {
bpm,
noteDivision,
dotted = false,
nTupletValue = undefined,
} = model;
const noteDivisionRatio = getNoteDivisionRatio(noteDivision);
const nTupletRatio = nTupletValue ? getNTupletRatio(nTupletValue) : 1;
const dottedRatio = dotted ? noteDurationModifiers.dotted : 1;
const durationOfOneMeasure = (60 * 1000 * 4) / bpm;
return (
durationOfOneMeasure * noteDivisionRatio * nTupletRatio * dottedRatio
);
}
/* Example usages of 'getNoteDivisionRatio' are shown below:
getNoteDivisionRatio(noteDivision);
*/
function getNoteDivisionRatio(noteDivision) {
switch (noteDivision) {
case NoteDivision.FULL:
return 1;
case NoteDivision.HALF:
return 1 / 2;
case NoteDivision.QUARTER:
return 1 / 4;
case NoteDivision.EIGHTH:
return 1 / 8;
case NoteDivision.SIXTEENTH:
return 1 / 16;
case NoteDivision.THIRTYSECOND:
return 1 / 32;
case NoteDivision.SIXTYFOURTH:
return 1 / 64;
case NoteDivision.ONEHUNDERDANDTWENTYEIGHTH:
return 1 / 128;
default:
throw new Error(`Unknown note division ${noteDivision}`);
}
}
/* Example usages of 'getNTupletRatio' are shown below:
nTupletValue ? getNTupletRatio(nTupletValue) : 1;
*/
function getNTupletRatio(nTupletValue) {
switch (nTupletValue) {
case 3:
return noteDurationModifiers.triplet;
case 5:
return noteDurationModifiers.quintuplet;
case 7:
return noteDurationModifiers.septuplet;
case 9:
return noteDurationModifiers.nonuplet;
default:
throw new Error(`Unknown nTupletValue ${nTupletValue}`);
}
}
|
57d87d12960f35a593f6da68902f487a24c0f939 | 2,016 | ts | TypeScript | tmp/2-function/examples/1-structures/structures_ok.ts | LabsAdemy/Docs-CleanCode-Intro | fb5e7908ab52f6b6adbab62fa41e84401c119e4c | [
"MIT"
] | 1 | 2022-02-17T10:19:04.000Z | 2022-02-17T10:19:04.000Z | tmp/2-function/examples/1-structures/structures_ok.ts | LabsAdemy/Docs-CleanCode-Intro | fb5e7908ab52f6b6adbab62fa41e84401c119e4c | [
"MIT"
] | null | null | null | tmp/2-function/examples/1-structures/structures_ok.ts | LabsAdemy/Docs-CleanCode-Intro | fb5e7908ab52f6b6adbab62fa41e84401c119e4c | [
"MIT"
] | null | null | null | // ✔️ Define types (or interfaces, os structs... or even classes)
type Currency = 'EUR' | 'USD';
type Money = { amount: number; currency: Currency };
type SavingsCondition = { principal: Money; rate: number; years: number };
export function calculateInterest(): Money {
// ✔️ object literal
const mySavingsConditionsLit: SavingsCondition = {
principal: { amount: 1000, currency: 'EUR' },
rate: 3.5,
years: 1,
};
// ✔️ object factory
const mySavingsConditions: SavingsCondition = conditionsFactory(100, 3.5);
// ✔️ single parameter
const interest = getSimpleInterest(mySavingsConditions);
return interest;
}
function moneyFactory(amount: number, currency: Currency = 'EUR') {
// ✔️ parameter validation, and default value
assertAmountPositive(amount);
return {
amount,
currency,
};
}
function conditionsFactory(
amount: number,
rate: number,
years: number = 1,
currency: Currency = 'EUR'
) {
// ✔️ parameter validation
assertAmountPositive(amount);
assertRateRange(rate);
assertYearsRange(years);
const conditions: SavingsCondition = {
principal: moneyFactory(amount, currency),
rate: rate,
years: years,
};
return conditions;
}
function assertYearsRange(years: number) {
const MIN_YEARS = 0;
const MAX_YEARS = 100;
if (years < MIN_YEARS || years > MAX_YEARS)
throw new Error(`Year must be between ${MIN_YEARS} and ${MAX_YEARS}`);
}
function assertRateRange(rate: number) {
const MIN_RATE = 1;
const MAX_RATE = 10;
if (rate < MIN_RATE || rate > MAX_RATE)
throw new Error(`Rate must be between ${MIN_RATE} and ${MAX_RATE}`);
}
function assertAmountPositive(amount: number) {
if (amount < 0) throw new Error(`Amount must be positive`);
}
function getSimpleInterest(conditions: SavingsCondition): Money {
const PER_CENT = 100;
const interestAmount =
(conditions.principal.amount * conditions.rate * conditions.years) / PER_CENT;
return moneyFactory(interestAmount, conditions.principal.currency);
}
| 26.88 | 82 | 0.701885 | 57 | 7 | 0 | 10 | 10 | 5 | 6 | 0 | 10 | 3 | 0 | 5 | 588 | 0.028912 | 0.017007 | 0.008503 | 0.005102 | 0 | 0 | 0.3125 | 0.302623 | // ✔️ Define types (or interfaces, os structs... or even classes)
type Currency = 'EUR' | 'USD';
type Money = { amount; currency };
type SavingsCondition = { principal; rate; years };
export function calculateInterest() {
// ✔️ object literal
const mySavingsConditionsLit = {
principal: { amount: 1000, currency: 'EUR' },
rate: 3.5,
years: 1,
};
// ✔️ object factory
const mySavingsConditions = conditionsFactory(100, 3.5);
// ✔️ single parameter
const interest = getSimpleInterest(mySavingsConditions);
return interest;
}
/* Example usages of 'moneyFactory' are shown below:
moneyFactory(amount, currency);
moneyFactory(interestAmount, conditions.principal.currency);
*/
function moneyFactory(amount, currency = 'EUR') {
// ✔️ parameter validation, and default value
assertAmountPositive(amount);
return {
amount,
currency,
};
}
/* Example usages of 'conditionsFactory' are shown below:
conditionsFactory(100, 3.5);
*/
function conditionsFactory(
amount,
rate,
years = 1,
currency = 'EUR'
) {
// ✔️ parameter validation
assertAmountPositive(amount);
assertRateRange(rate);
assertYearsRange(years);
const conditions = {
principal: moneyFactory(amount, currency),
rate: rate,
years: years,
};
return conditions;
}
/* Example usages of 'assertYearsRange' are shown below:
assertYearsRange(years);
*/
function assertYearsRange(years) {
const MIN_YEARS = 0;
const MAX_YEARS = 100;
if (years < MIN_YEARS || years > MAX_YEARS)
throw new Error(`Year must be between ${MIN_YEARS} and ${MAX_YEARS}`);
}
/* Example usages of 'assertRateRange' are shown below:
assertRateRange(rate);
*/
function assertRateRange(rate) {
const MIN_RATE = 1;
const MAX_RATE = 10;
if (rate < MIN_RATE || rate > MAX_RATE)
throw new Error(`Rate must be between ${MIN_RATE} and ${MAX_RATE}`);
}
/* Example usages of 'assertAmountPositive' are shown below:
// ✔️ parameter validation, and default value
assertAmountPositive(amount);
// ✔️ parameter validation
assertAmountPositive(amount);
*/
function assertAmountPositive(amount) {
if (amount < 0) throw new Error(`Amount must be positive`);
}
/* Example usages of 'getSimpleInterest' are shown below:
getSimpleInterest(mySavingsConditions);
*/
function getSimpleInterest(conditions) {
const PER_CENT = 100;
const interestAmount =
(conditions.principal.amount * conditions.rate * conditions.years) / PER_CENT;
return moneyFactory(interestAmount, conditions.principal.currency);
}
|
8d18343dd4de319dd4ace0d978101024dfde816a | 4,874 | ts | TypeScript | src/Random.ts | merakigenart/meraki-js-sdk | 975536ee5b0fa997c7222d68e9574ac7acf08fdd | [
"MIT"
] | 3 | 2022-01-20T23:02:12.000Z | 2022-02-05T10:27:55.000Z | src/Random.ts | merakigenart/meraki-js-sdk | 975536ee5b0fa997c7222d68e9574ac7acf08fdd | [
"MIT"
] | 8 | 2022-01-17T19:18:03.000Z | 2022-03-30T19:29:21.000Z | src/Random.ts | merakigenart/meraki-js-sdk | 975536ee5b0fa997c7222d68e9574ac7acf08fdd | [
"MIT"
] | null | null | null | /* eslint-disable no-unused-vars */
// @ts-nocheck
//import { generateRandomTokenData } from './helpers';
export class Random {
protected state: Record<string, any>;
protected seedValues: Record<string, any>;
constructor(public tokenData = { tokenHash: '', tokenId: '' }) {
if (this.tokenData.tokenHash === '') {
this.tokenData.tokenHash = '0x940cca72744643225ef08d17711cb873940cca72744643225ef08d17711cb873';
}
const seeds = this.generateSeeds(this.tokenData.tokenHash);
this.state = this.initializeState().state;
this.seedValues = this.initializeSeeds(seeds);
this.rnd();
}
// random number between 0 (inclusive) and 1 (exclusive)
decimal() {
return this.rnd();
}
// random number between a (inclusive) and b (exclusive)
number(a = undefined, b = undefined) {
if (a === undefined && b === undefined) {
a = 0;
b = Number.MAX_VALUE - 2;
}
if (b === undefined) {
b = a;
a = 0;
}
if (a === undefined) {
a = 0;
}
return a + (b - a) * this.decimal();
}
// random integer between a (inclusive) and b (inclusive)
// requires a < b for proper probability distribution
integer(a = undefined, b = undefined) {
if (a === undefined && b === undefined) {
a = 0;
b = Number.MAX_VALUE - 2;
}
if (b === undefined) {
b = a;
a = 0;
}
if (a === undefined) {
a = 0;
}
return Math.floor(this.number(a, b + 1));
}
// random boolean with p as percent likelihood of true
boolean(p = 50) {
return this.decimal() < p * 0.1;
}
// random value in an array of items
element(list) {
return list[this.integer(0, list.length - 1)];
}
generateSeeds(str: string): number[] {
let part = 0;
const seeds: number[] = [];
str = `${str}`;
if (str.startsWith('0x')) {
str = str.slice(2);
}
for (let i = 0; i < str.length; i++) {
part = str.slice(i, i + 4);
seeds.push(parseInt(part, 16));
i += 4;
}
for (let i = 0; i < str.length; i++) {
part = str.slice(i, i + 4);
seeds.push(parseInt(part, 16));
i += 2;
}
for (let i = 0; i < str.length; i++) {
part = str.slice(i, i + 4);
seeds.push(parseInt(part, 16));
i += 1;
}
for (let i = 0; i < str.length; i++) {
part = str.substring(str.length - i - 4, str.length - i);
part = part.substring(2, 4) + part.substring(0, 2);
seeds.push(parseInt(part, 16));
i += 4;
}
return seeds;
}
protected initializeSeeds(seeds: number[]) {
const seedValues = Object.assign(
{},
{
eps: Math.pow(2, -32),
m0: seeds[0],
m1: seeds[1],
m2: seeds[2],
m3: seeds[3],
a0: seeds[4],
a1: seeds[5],
a2: seeds[6],
a3: seeds[7],
},
);
return seedValues;
}
protected initializeState(stateSize = 4, integerSize: 8 | 16 | 32 | 64 = 16) {
const intMap = {
8: Uint8Array,
16: Uint16Array,
32: Uint32Array,
64: BigUint64Array,
};
const intClass = intMap[integerSize];
const state = new intClass(stateSize);
const dataView = new DataView(state.buffer);
return {
integerSize,
stateSize,
state,
dataView,
};
}
rnd() {
const { eps, a0, a1, a2, a3, m0, m1, m2, m3 } = this.seedValues;
const a = this.state[0],
b = this.state[1],
c = this.state[2],
e = this.state[3],
f = 0 | (a0 + m0 * a),
g = 0 | (a1 + m0 * b + (m1 * a + (f >>> 16))),
h = 0 | (a2 + m0 * c + m1 * b + (m2 * a + (g >>> 16)));
this.state[0] = f;
this.state[1] = g;
this.state[2] = h;
this.state[3] = a3 + m0 * e + (m1 * c + m2 * b) + (m3 * a + (h >>> 16));
const i = (e << 21) + (((e >> 2) ^ c) << 5) + (((c >> 2) ^ b) >> 11);
return eps * (((i >>> (e >> 11)) | (i << (31 & -(e >> 11)))) >>> 0);
}
shuffle(a: any[]) {
const f = [...a];
let b,
c,
e = a.length;
for (let i = 0; i < e; i++) {
b = ~~(this.rnd() * e - 1);
c = f[e];
f[e] = f[b];
f[b] = c;
e--;
}
return f;
}
}
| 25.123711 | 108 | 0.431268 | 144 | 11 | 0 | 12 | 26 | 2 | 7 | 3 | 6 | 1 | 0 | 10.727273 | 1,490 | 0.015436 | 0.01745 | 0.001342 | 0.000671 | 0 | 0.058824 | 0.117647 | 0.264971 | /* eslint-disable no-unused-vars */
// @ts-nocheck
//import { generateRandomTokenData } from './helpers';
export class Random {
protected state;
protected seedValues;
constructor(public tokenData = { tokenHash: '', tokenId: '' }) {
if (this.tokenData.tokenHash === '') {
this.tokenData.tokenHash = '0x940cca72744643225ef08d17711cb873940cca72744643225ef08d17711cb873';
}
const seeds = this.generateSeeds(this.tokenData.tokenHash);
this.state = this.initializeState().state;
this.seedValues = this.initializeSeeds(seeds);
this.rnd();
}
// random number between 0 (inclusive) and 1 (exclusive)
decimal() {
return this.rnd();
}
// random number between a (inclusive) and b (exclusive)
number(a = undefined, b = undefined) {
if (a === undefined && b === undefined) {
a = 0;
b = Number.MAX_VALUE - 2;
}
if (b === undefined) {
b = a;
a = 0;
}
if (a === undefined) {
a = 0;
}
return a + (b - a) * this.decimal();
}
// random integer between a (inclusive) and b (inclusive)
// requires a < b for proper probability distribution
integer(a = undefined, b = undefined) {
if (a === undefined && b === undefined) {
a = 0;
b = Number.MAX_VALUE - 2;
}
if (b === undefined) {
b = a;
a = 0;
}
if (a === undefined) {
a = 0;
}
return Math.floor(this.number(a, b + 1));
}
// random boolean with p as percent likelihood of true
boolean(p = 50) {
return this.decimal() < p * 0.1;
}
// random value in an array of items
element(list) {
return list[this.integer(0, list.length - 1)];
}
generateSeeds(str) {
let part = 0;
const seeds = [];
str = `${str}`;
if (str.startsWith('0x')) {
str = str.slice(2);
}
for (let i = 0; i < str.length; i++) {
part = str.slice(i, i + 4);
seeds.push(parseInt(part, 16));
i += 4;
}
for (let i = 0; i < str.length; i++) {
part = str.slice(i, i + 4);
seeds.push(parseInt(part, 16));
i += 2;
}
for (let i = 0; i < str.length; i++) {
part = str.slice(i, i + 4);
seeds.push(parseInt(part, 16));
i += 1;
}
for (let i = 0; i < str.length; i++) {
part = str.substring(str.length - i - 4, str.length - i);
part = part.substring(2, 4) + part.substring(0, 2);
seeds.push(parseInt(part, 16));
i += 4;
}
return seeds;
}
protected initializeSeeds(seeds) {
const seedValues = Object.assign(
{},
{
eps: Math.pow(2, -32),
m0: seeds[0],
m1: seeds[1],
m2: seeds[2],
m3: seeds[3],
a0: seeds[4],
a1: seeds[5],
a2: seeds[6],
a3: seeds[7],
},
);
return seedValues;
}
protected initializeState(stateSize = 4, integerSize = 16) {
const intMap = {
8: Uint8Array,
16: Uint16Array,
32: Uint32Array,
64: BigUint64Array,
};
const intClass = intMap[integerSize];
const state = new intClass(stateSize);
const dataView = new DataView(state.buffer);
return {
integerSize,
stateSize,
state,
dataView,
};
}
rnd() {
const { eps, a0, a1, a2, a3, m0, m1, m2, m3 } = this.seedValues;
const a = this.state[0],
b = this.state[1],
c = this.state[2],
e = this.state[3],
f = 0 | (a0 + m0 * a),
g = 0 | (a1 + m0 * b + (m1 * a + (f >>> 16))),
h = 0 | (a2 + m0 * c + m1 * b + (m2 * a + (g >>> 16)));
this.state[0] = f;
this.state[1] = g;
this.state[2] = h;
this.state[3] = a3 + m0 * e + (m1 * c + m2 * b) + (m3 * a + (h >>> 16));
const i = (e << 21) + (((e >> 2) ^ c) << 5) + (((c >> 2) ^ b) >> 11);
return eps * (((i >>> (e >> 11)) | (i << (31 & -(e >> 11)))) >>> 0);
}
shuffle(a) {
const f = [...a];
let b,
c,
e = a.length;
for (let i = 0; i < e; i++) {
b = ~~(this.rnd() * e - 1);
c = f[e];
f[e] = f[b];
f[b] = c;
e--;
}
return f;
}
}
|
8d3bf72ed17bb55c1069d0cfbf9974cd71ba2ac9 | 3,053 | ts | TypeScript | lib/Models/BaseModel.ts | pangyunchuan/testOrm | a9c928cfad5a1d75feffd5c33ce6b222f6f93f00 | [
"MIT"
] | 1 | 2022-02-26T09:49:56.000Z | 2022-02-26T09:49:56.000Z | lib/Models/BaseModel.ts | pangyunchuan/testOrm | a9c928cfad5a1d75feffd5c33ce6b222f6f93f00 | [
"MIT"
] | null | null | null | lib/Models/BaseModel.ts | pangyunchuan/testOrm | a9c928cfad5a1d75feffd5c33ce6b222f6f93f00 | [
"MIT"
] | 1 | 2022-02-22T11:47:37.000Z | 2022-02-22T11:47:37.000Z | export default abstract class BaseModel<ModelData extends object = {}> {
/**
* 模型数据类型,只用于获取类型,无用途
*/
_data?: ModelData;
// protected abstract table: string
//
// protected abstract getTable(): string
/**
* 模型数据
* @protected
*/
protected abstract data: ModelData;
/**
* 模型主键
* @protected
*/
protected primaryKey:string = 'id';
//是否已代理数据
private isProxyData: boolean = false;
//无法做到,会让后代提示,this类型问题
// constructor() {
// // super(props);
// return this.proxyData()
// }
/**
* 创建一个代理模型数据的模型实例
* @param data 模型数据
* @param call
*/
static createModel<M extends BaseModel, Da extends Partial<NonNullable<M['_data']>> = NonNullable<M['_data']>>(
this: new () => M, data?: Da, call?: (model: M & Da) => void
): M & Da {
return new this().createModel(data, call)
}
/**
* 创建一个代理模型数据的模型实例
* @param data 模型数据
* @param call 模型建立后回调
* @param newInst 是否新建模型
*/
createModel<Da extends Partial<ModelData> = ModelData>(data?: Da, call?: (model: this & Da) => void, newInst = false): this & Da {
const self = newInst ? <this>new (<any>this.constructor)() : this;
const selfProxyData = self.proxyData<Da>()
data && (selfProxyData.data = <any>data);
call && call(selfProxyData)
return selfProxyData
}
/**
* 代理模型数据 data,让模型实例可以直接访问
* @protected
*/
protected proxyData<MD extends Partial<ModelData> = ModelData>(): this & MD {
if (this.isProxyData) {
return <this & MD>this
}
this.isProxyData = true;
return <this & MD>new Proxy(this, {
get(target: any, p: string | symbol) {
if (p in target) {
return target[p];
}
if (target.data) {
return target.data[p];
}
return undefined;
},
set(target: any, p: string | symbol, value: any) {
if (p in target) {
target[p] = value;
return true;
}
if (target.data && p in target.data) {
target.data[p] = value;
return true;
}
target[p] = value;
return true;
// throw new Error('不存在的属性')
// return true;
},
has(target: any, p: string | symbol) {
return (p in target) || (target.data && p in target.data);
}
// deleteProperty(target: any, p: string | symbol): boolean {
// if (p in target) {
// delete target[p];
// return true;
// }
// if (p in target.data) {
// delete target.data[p];
// return true;
// }
// return false;
// }
});
}
}
| 28.268519 | 134 | 0.466426 | 50 | 6 | 0 | 13 | 2 | 4 | 2 | 6 | 11 | 1 | 0 | 9 | 771 | 0.024643 | 0.002594 | 0.005188 | 0.001297 | 0 | 0.24 | 0.44 | 0.234403 | export default abstract class BaseModel<ModelData extends object = {}> {
/**
* 模型数据类型,只用于获取类型,无用途
*/
_data?;
// protected abstract table: string
//
// protected abstract getTable(): string
/**
* 模型数据
* @protected
*/
protected abstract data;
/**
* 模型主键
* @protected
*/
protected primaryKey = 'id';
//是否已代理数据
private isProxyData = false;
//无法做到,会让后代提示,this类型问题
// constructor() {
// // super(props);
// return this.proxyData()
// }
/**
* 创建一个代理模型数据的模型实例
* @param data 模型数据
* @param call
*/
static createModel<M extends BaseModel, Da extends Partial<NonNullable<M['_data']>> = NonNullable<M['_data']>>(
this, data?, call?
) {
return new this().createModel(data, call)
}
/**
* 创建一个代理模型数据的模型实例
* @param data 模型数据
* @param call 模型建立后回调
* @param newInst 是否新建模型
*/
createModel<Da extends Partial<ModelData> = ModelData>(data?, call?, newInst = false) {
const self = newInst ? <this>new (<any>this.constructor)() : this;
const selfProxyData = self.proxyData<Da>()
data && (selfProxyData.data = <any>data);
call && call(selfProxyData)
return selfProxyData
}
/**
* 代理模型数据 data,让模型实例可以直接访问
* @protected
*/
protected proxyData<MD extends Partial<ModelData> = ModelData>() {
if (this.isProxyData) {
return <this & MD>this
}
this.isProxyData = true;
return <this & MD>new Proxy(this, {
get(target, p) {
if (p in target) {
return target[p];
}
if (target.data) {
return target.data[p];
}
return undefined;
},
set(target, p, value) {
if (p in target) {
target[p] = value;
return true;
}
if (target.data && p in target.data) {
target.data[p] = value;
return true;
}
target[p] = value;
return true;
// throw new Error('不存在的属性')
// return true;
},
has(target, p) {
return (p in target) || (target.data && p in target.data);
}
// deleteProperty(target: any, p: string | symbol): boolean {
// if (p in target) {
// delete target[p];
// return true;
// }
// if (p in target.data) {
// delete target.data[p];
// return true;
// }
// return false;
// }
});
}
}
|
8d8e0680708b7322d95d0440ee9a53c1c5f7ec52 | 2,205 | ts | TypeScript | cli/src/protocol/render/typescript/static/protocol.validator.ts | DmitryAstafyev/fiber | 82b4c585ea811769a0b228445dc40bab9a4f875f | [
"Apache-2.0"
] | 9 | 2022-01-03T16:04:34.000Z | 2022-02-12T10:22:19.000Z | cli/src/protocol/render/typescript/static/protocol.validator.ts | DmitryAstafyev/fiber | 82b4c585ea811769a0b228445dc40bab9a4f875f | [
"Apache-2.0"
] | null | null | null | cli/src/protocol/render/typescript/static/protocol.validator.ts | DmitryAstafyev/fiber | 82b4c585ea811769a0b228445dc40bab9a4f875f | [
"Apache-2.0"
] | 1 | 2022-02-07T21:54:16.000Z | 2022-02-07T21:54:16.000Z | // injectable
export interface IValidator {
validate(value: any): Error | undefined;
}
export interface IPropScheme {
prop: string;
optional?: boolean;
types?: Required<IValidator>;
options?: IPropScheme[];
}
export function validate(obj: any, scheme: IPropScheme[]): Error | undefined {
if (typeof obj !== "object" || obj === null) {
return new Error(`Expecting input to be object`);
}
const errors: string[] = scheme
.map((property: IPropScheme) => {
if (property.optional && obj[property.prop] === undefined) {
return undefined;
}
if (property.types !== undefined) {
const err: Error | undefined = property.types.validate(
obj[property.prop]
);
if (err instanceof Error) {
return err.message;
} else {
return undefined;
}
} else if (property.options instanceof Array) {
if (
typeof obj[property.prop] !== "object" ||
obj[property.prop] === null
) {
return `Property "${property.prop}" should be an object, because it's enum`;
}
const target: any = obj[property.prop];
const options: string[] = [];
try {
property.options.forEach((prop: IPropScheme) => {
if (prop.types === undefined) {
throw new Error(
`Invalid option description for option "${prop.prop}" of option "${property.prop}"`
);
}
if (target[prop.prop] !== undefined) {
options.push(prop.prop);
const err: Error | undefined = prop.types.validate(
target[prop.prop]
);
if (err instanceof Error) {
throw new Error(
`Fail to validate option "${prop.prop}" of option "${property.prop}" due: ${err.message}`
);
}
}
});
} catch (err) {
return err instanceof Error
? err.message
: `Unknown error: ${err}`;
}
if (options.length > 1) {
return `Enum should have only one definition or nothing. Found values for: ${options.join(
", "
)}`;
}
return undefined;
} else {
return `Invalid map definition for property ${property.prop}`;
}
})
.filter((err) => err !== undefined) as string[];
return errors.length > 0 ? new Error(errors.join("\n")) : undefined;
}
| 28.636364 | 98 | 0.597279 | 73 | 4 | 1 | 6 | 5 | 4 | 1 | 3 | 5 | 2 | 7 | 33.25 | 633 | 0.015798 | 0.007899 | 0.006319 | 0.00316 | 0.011058 | 0.15 | 0.25 | 0.233905 | // injectable
export interface IValidator {
validate(value);
}
export interface IPropScheme {
prop;
optional?;
types?;
options?;
}
export /* Example usages of 'validate' are shown below:
;
property.types.validate(obj[property.prop]);
prop.types.validate(target[prop.prop]);
*/
function validate(obj, scheme) {
if (typeof obj !== "object" || obj === null) {
return new Error(`Expecting input to be object`);
}
const errors = scheme
.map((property) => {
if (property.optional && obj[property.prop] === undefined) {
return undefined;
}
if (property.types !== undefined) {
const err = property.types.validate(
obj[property.prop]
);
if (err instanceof Error) {
return err.message;
} else {
return undefined;
}
} else if (property.options instanceof Array) {
if (
typeof obj[property.prop] !== "object" ||
obj[property.prop] === null
) {
return `Property "${property.prop}" should be an object, because it's enum`;
}
const target = obj[property.prop];
const options = [];
try {
property.options.forEach((prop) => {
if (prop.types === undefined) {
throw new Error(
`Invalid option description for option "${prop.prop}" of option "${property.prop}"`
);
}
if (target[prop.prop] !== undefined) {
options.push(prop.prop);
const err = prop.types.validate(
target[prop.prop]
);
if (err instanceof Error) {
throw new Error(
`Fail to validate option "${prop.prop}" of option "${property.prop}" due: ${err.message}`
);
}
}
});
} catch (err) {
return err instanceof Error
? err.message
: `Unknown error: ${err}`;
}
if (options.length > 1) {
return `Enum should have only one definition or nothing. Found values for: ${options.join(
", "
)}`;
}
return undefined;
} else {
return `Invalid map definition for property ${property.prop}`;
}
})
.filter((err) => err !== undefined) as string[];
return errors.length > 0 ? new Error(errors.join("\n")) : undefined;
}
|
8d948986abaf04bbce20a35d6e23ee5152559bc8 | 1,654 | tsx | TypeScript | apps/mobile-ctc/src/@libs/elsa-ui/theme/default.tsx | Elsa-Health/mammoth | afdf8453b75ed414a1438bb78309e8649ae7e20b | [
"Apache-2.0"
] | 3 | 2022-03-03T17:43:39.000Z | 2022-03-08T23:26:23.000Z | apps/mobile-ctc/src/@libs/elsa-ui/theme/default.tsx | Elsa-Health/mammoth | afdf8453b75ed414a1438bb78309e8649ae7e20b | [
"Apache-2.0"
] | 3 | 2022-03-10T09:23:00.000Z | 2022-03-18T14:14:16.000Z | apps/mobile-ctc/src/@libs/elsa-ui/theme/default.tsx | Elsa-Health/mammoth | afdf8453b75ed414a1438bb78309e8649ae7e20b | [
"Apache-2.0"
] | null | null | null | export type fontFamiliStyleType =
| 'light'
| 'normal'
| 'medium'
| 'bold'
| 'black'
| 'extra-black';
export const fontFamilyStyle = (
props: {italic?: boolean; font?: fontFamiliStyleType} = {},
) => {
if (props.italic !== undefined) {
if (props.italic) {
// italic fonts
switch (props.font || 'normal') {
case 'light':
return 'AvenirLTStd-LightOblique';
case 'medium':
return 'AvenirLTStd-MediumOblique';
case 'bold':
return 'AvenirLTStd-HeavyOblique';
case 'black':
return 'AvenirLTStd-BookOblique';
case 'extra-black':
return 'AvenirLTStd-BlackOblique';
case 'normal':
default:
return 'AvenirLTStd-Oblique';
}
}
}
switch (props.font || 'normal') {
case 'light':
return 'AvenirLTStd-Light';
case 'medium':
return 'AvenirLTStd-Medium';
case 'bold':
return 'AvenirLTStd-Heavy';
case 'black':
return 'AvenirLTStd-Book';
case 'extra-black':
return 'AvenirLTStd-Black';
case 'normal':
default:
return 'AvenirLTStd-Roman';
}
};
export const DefaultColor = {
primary: {
base: '#4665AF',
light: '#7992e1',
dark: '#003b7f',
},
secondary: {
base: '#5558A6',
light: '#8685d8',
dark: '#222f77', // can change in the future
},
};
export const DefaultSpacing = {
xs: 4,
sm: 8,
md: 16,
lg: 24,
xl: 32,
'2xl': 48,
};
export const DefaultTypography = {
fontFamilyStyle,
sizes: {
xs: '12px',
sm: '14px',
md: '16px',
lg: '20px',
xl: '24px',
'2xl': '28px',
},
};
| 19.458824 | 61 | 0.549577 | 76 | 1 | 0 | 1 | 4 | 0 | 0 | 0 | 1 | 1 | 0 | 34 | 561 | 0.003565 | 0.00713 | 0 | 0.001783 | 0 | 0 | 0.166667 | 0.204441 | export type fontFamiliStyleType =
| 'light'
| 'normal'
| 'medium'
| 'bold'
| 'black'
| 'extra-black';
export /* Example usages of 'fontFamilyStyle' are shown below:
;
*/
const fontFamilyStyle = (
props = {},
) => {
if (props.italic !== undefined) {
if (props.italic) {
// italic fonts
switch (props.font || 'normal') {
case 'light':
return 'AvenirLTStd-LightOblique';
case 'medium':
return 'AvenirLTStd-MediumOblique';
case 'bold':
return 'AvenirLTStd-HeavyOblique';
case 'black':
return 'AvenirLTStd-BookOblique';
case 'extra-black':
return 'AvenirLTStd-BlackOblique';
case 'normal':
default:
return 'AvenirLTStd-Oblique';
}
}
}
switch (props.font || 'normal') {
case 'light':
return 'AvenirLTStd-Light';
case 'medium':
return 'AvenirLTStd-Medium';
case 'bold':
return 'AvenirLTStd-Heavy';
case 'black':
return 'AvenirLTStd-Book';
case 'extra-black':
return 'AvenirLTStd-Black';
case 'normal':
default:
return 'AvenirLTStd-Roman';
}
};
export const DefaultColor = {
primary: {
base: '#4665AF',
light: '#7992e1',
dark: '#003b7f',
},
secondary: {
base: '#5558A6',
light: '#8685d8',
dark: '#222f77', // can change in the future
},
};
export const DefaultSpacing = {
xs: 4,
sm: 8,
md: 16,
lg: 24,
xl: 32,
'2xl': 48,
};
export const DefaultTypography = {
fontFamilyStyle,
sizes: {
xs: '12px',
sm: '14px',
md: '16px',
lg: '20px',
xl: '24px',
'2xl': '28px',
},
};
|
8dcef4976e2861209d2b66ec9ff2808b56c0bf9b | 1,971 | ts | TypeScript | src/TeaProgram.ts | lydell/elm-watch | d1511b24940db26d25f256ecec0f5beb82d4c34c | [
"MIT"
] | 14 | 2022-03-12T19:21:46.000Z | 2022-03-25T10:17:47.000Z | src/TeaProgram.ts | lydell/elm-watch | d1511b24940db26d25f256ecec0f5beb82d4c34c | [
"MIT"
] | 1 | 2022-03-15T14:53:51.000Z | 2022-03-15T14:53:51.000Z | src/TeaProgram.ts | lydell/elm-watch | d1511b24940db26d25f256ecec0f5beb82d4c34c | [
"MIT"
] | 2 | 2022-03-13T16:15:33.000Z | 2022-03-15T14:23:23.000Z | export async function runTeaProgram<Mutable, Msg, Model, Cmd, Result>(options: {
initMutable: (
dispatch: (msg: Msg) => void,
resolvePromise: (result: Result) => void,
rejectPromise: (error: Error) => void
) => Mutable;
init: [Model, Array<Cmd>];
update: (msg: Msg, model: Model) => [Model, Array<Cmd>];
runCmd: (
cmd: Cmd,
mutable: Mutable,
dispatch: (msg: Msg) => void,
resolvePromise: (result: Result) => void,
rejectPromise: (error: Error) => void
) => void;
}): Promise<Result> {
return new Promise((resolve, reject) => {
const [initialModel, initialCmds] = options.init;
let model: Model = initialModel;
const msgQueue: Array<Msg> = [];
let killed = false;
const dispatch = (dispatchedMsg: Msg): void => {
if (killed) {
return;
}
const alreadyRunning = msgQueue.length > 0;
msgQueue.push(dispatchedMsg);
if (alreadyRunning) {
return;
}
for (const msg of msgQueue) {
const [newModel, cmds] = options.update(msg, model);
model = newModel;
runCmds(cmds);
}
msgQueue.length = 0;
};
const runCmds = (cmds: Array<Cmd>): void => {
for (const cmd of cmds) {
options.runCmd(
cmd,
mutable,
dispatch,
(result) => {
cmds.length = 0;
killed = true;
resolve(result);
},
// istanbul ignore next
(error) => {
cmds.length = 0;
killed = true;
reject(error);
}
);
// istanbul ignore next
if (killed) {
break;
}
}
};
const mutable = options.initMutable(
dispatch,
(result) => {
killed = true;
resolve(result);
},
// istanbul ignore next
(error) => {
killed = true;
reject(error);
}
);
runCmds(initialCmds);
});
}
| 24.333333 | 80 | 0.512938 | 73 | 8 | 0 | 9 | 9 | 0 | 1 | 0 | 9 | 0 | 0 | 19.25 | 508 | 0.033465 | 0.017717 | 0 | 0 | 0 | 0 | 0.346154 | 0.306111 | export async function runTeaProgram<Mutable, Msg, Model, Cmd, Result>(options) {
return new Promise((resolve, reject) => {
const [initialModel, initialCmds] = options.init;
let model = initialModel;
const msgQueue = [];
let killed = false;
/* Example usages of 'dispatch' are shown below:
options.runCmd(cmd, mutable, dispatch, (result) => {
cmds.length = 0;
killed = true;
resolve(result);
},
// istanbul ignore next
(error) => {
cmds.length = 0;
killed = true;
reject(error);
});
options.initMutable(dispatch, (result) => {
killed = true;
resolve(result);
},
// istanbul ignore next
(error) => {
killed = true;
reject(error);
});
*/
const dispatch = (dispatchedMsg) => {
if (killed) {
return;
}
const alreadyRunning = msgQueue.length > 0;
msgQueue.push(dispatchedMsg);
if (alreadyRunning) {
return;
}
for (const msg of msgQueue) {
const [newModel, cmds] = options.update(msg, model);
model = newModel;
runCmds(cmds);
}
msgQueue.length = 0;
};
/* Example usages of 'runCmds' are shown below:
runCmds(cmds);
runCmds(initialCmds);
*/
const runCmds = (cmds) => {
for (const cmd of cmds) {
options.runCmd(
cmd,
mutable,
dispatch,
(result) => {
cmds.length = 0;
killed = true;
resolve(result);
},
// istanbul ignore next
(error) => {
cmds.length = 0;
killed = true;
reject(error);
}
);
// istanbul ignore next
if (killed) {
break;
}
}
};
const mutable = options.initMutable(
dispatch,
(result) => {
killed = true;
resolve(result);
},
// istanbul ignore next
(error) => {
killed = true;
reject(error);
}
);
runCmds(initialCmds);
});
}
|
8dd4eba467cc4f8c283713bdfc23d3b71e87f31d | 3,216 | ts | TypeScript | packages/typescript/src/lib.ts | mxenabled/widget-post-message-definitions | 5de58da92fe4c12a5c2e8210b237e638ab2d8d73 | [
"MIT"
] | null | null | null | packages/typescript/src/lib.ts | mxenabled/widget-post-message-definitions | 5de58da92fe4c12a5c2e8210b237e638ab2d8d73 | [
"MIT"
] | 1 | 2022-03-23T22:15:42.000Z | 2022-03-23T22:15:42.000Z | packages/typescript/src/lib.ts | mxenabled/widget-post-message-definitions | 5de58da92fe4c12a5c2e8210b237e638ab2d8d73 | [
"MIT"
] | null | null | null | export type BasePostMessageCallbackProps<T> = {
onMessage?: (message: T) => void
onInvalidMessageError?: (message: T, error: Error) => void
}
// This is an internal error. Thrown when we are decoding a post message's
// metadata and we encourntered a missing field or an invalid value. This
// likely means there has been a change to the definition of a post message
// that we do not know about.
export class PostMessageFieldDecodeError extends Error {
public messageType: string
public field: string
public expectedType: TypeDef
public gotValue: unknown
constructor(messageType: string, field: string, expectedType: TypeDef, gotValue: unknown) {
super(`Unable to decode '${field}' from '${messageType}'`)
this.messageType = messageType
this.field = field
this.expectedType = expectedType
this.gotValue = gotValue
Object.setPrototypeOf(this, PostMessageFieldDecodeError.prototype)
}
}
// This is an internal error. Thrown when we get a post message we don't konw
// about. This likely means there is a new post message that this package needs
// to define.
export class PostMessageUnknownTypeError extends Error {
public postMessageType: string
constructor(postMessageType: string) {
super(`Unknown post message: ${postMessageType}`)
this.postMessageType = postMessageType
Object.setPrototypeOf(this, PostMessageUnknownTypeError.prototype)
}
}
export type MessageEventData = {
mx?: boolean
metadata?: Metadata
type?: string
}
export type Value = string | number
export type NestedValue = Record<string, Value>
export type TypeDef = string | Array<string> | Record<string, string>
export type Metadata = Record<string, Value | NestedValue>
export function assertMessageProp(
container: Metadata,
postMessageType: string,
field: string,
expectedType: TypeDef,
) {
const value = container[field]
const valueIsDefined = typeof value !== "undefined"
const valueIsString = typeof value === "string"
const valueIsNumber = typeof value === "number"
const valueIsObject = typeof value === "object" && !Array.isArray(value)
const typeIsString = expectedType === "string"
const typeIsNumber = expectedType === "number"
const typeIsArray = expectedType instanceof Array
const typeIsObject = typeof expectedType === "object" && !Array.isArray(expectedType)
if (!valueIsDefined) {
throw new PostMessageFieldDecodeError(postMessageType, field, expectedType, value)
} else if (typeIsString && !valueIsString) {
throw new PostMessageFieldDecodeError(postMessageType, field, expectedType, value)
} else if (typeIsNumber && !valueIsNumber) {
throw new PostMessageFieldDecodeError(postMessageType, field, expectedType, value)
} else if (typeIsArray && !(valueIsString && expectedType.includes(value))) {
throw new PostMessageFieldDecodeError(postMessageType, field, expectedType, value)
} else if (typeIsObject && !valueIsObject) {
throw new PostMessageFieldDecodeError(postMessageType, field, expectedType, value)
} else if (typeIsObject && valueIsObject) {
Object.keys(expectedType).forEach((field) => {
assertMessageProp(value, postMessageType, field, expectedType[field])
})
}
}
| 36.545455 | 93 | 0.745025 | 66 | 4 | 0 | 10 | 9 | 10 | 1 | 0 | 22 | 8 | 6 | 8.5 | 771 | 0.018158 | 0.011673 | 0.01297 | 0.010376 | 0.007782 | 0 | 0.666667 | 0.265642 | export type BasePostMessageCallbackProps<T> = {
onMessage?
onInvalidMessageError?
}
// This is an internal error. Thrown when we are decoding a post message's
// metadata and we encourntered a missing field or an invalid value. This
// likely means there has been a change to the definition of a post message
// that we do not know about.
export class PostMessageFieldDecodeError extends Error {
public messageType
public field
public expectedType
public gotValue
constructor(messageType, field, expectedType, gotValue) {
super(`Unable to decode '${field}' from '${messageType}'`)
this.messageType = messageType
this.field = field
this.expectedType = expectedType
this.gotValue = gotValue
Object.setPrototypeOf(this, PostMessageFieldDecodeError.prototype)
}
}
// This is an internal error. Thrown when we get a post message we don't konw
// about. This likely means there is a new post message that this package needs
// to define.
export class PostMessageUnknownTypeError extends Error {
public postMessageType
constructor(postMessageType) {
super(`Unknown post message: ${postMessageType}`)
this.postMessageType = postMessageType
Object.setPrototypeOf(this, PostMessageUnknownTypeError.prototype)
}
}
export type MessageEventData = {
mx?
metadata?
type?
}
export type Value = string | number
export type NestedValue = Record<string, Value>
export type TypeDef = string | Array<string> | Record<string, string>
export type Metadata = Record<string, Value | NestedValue>
export /* Example usages of 'assertMessageProp' are shown below:
assertMessageProp(value, postMessageType, field, expectedType[field]);
*/
function assertMessageProp(
container,
postMessageType,
field,
expectedType,
) {
const value = container[field]
const valueIsDefined = typeof value !== "undefined"
const valueIsString = typeof value === "string"
const valueIsNumber = typeof value === "number"
const valueIsObject = typeof value === "object" && !Array.isArray(value)
const typeIsString = expectedType === "string"
const typeIsNumber = expectedType === "number"
const typeIsArray = expectedType instanceof Array
const typeIsObject = typeof expectedType === "object" && !Array.isArray(expectedType)
if (!valueIsDefined) {
throw new PostMessageFieldDecodeError(postMessageType, field, expectedType, value)
} else if (typeIsString && !valueIsString) {
throw new PostMessageFieldDecodeError(postMessageType, field, expectedType, value)
} else if (typeIsNumber && !valueIsNumber) {
throw new PostMessageFieldDecodeError(postMessageType, field, expectedType, value)
} else if (typeIsArray && !(valueIsString && expectedType.includes(value))) {
throw new PostMessageFieldDecodeError(postMessageType, field, expectedType, value)
} else if (typeIsObject && !valueIsObject) {
throw new PostMessageFieldDecodeError(postMessageType, field, expectedType, value)
} else if (typeIsObject && valueIsObject) {
Object.keys(expectedType).forEach((field) => {
assertMessageProp(value, postMessageType, field, expectedType[field])
})
}
}
|
8debaa49041fffba960b6052b906718c2db42bf8 | 3,956 | ts | TypeScript | src/lib/markdown.ts | Lantern-chat/frontend | 9bf63a15e45329a46415e954efdb263860a22a67 | [
"FSFAP"
] | 4 | 2022-01-26T20:07:24.000Z | 2022-03-23T06:10:08.000Z | src/lib/markdown.ts | Lantern-chat/frontend | 9bf63a15e45329a46415e954efdb263860a22a67 | [
"FSFAP"
] | 2 | 2022-01-26T19:27:06.000Z | 2022-02-23T15:53:11.000Z | src/lib/markdown.ts | Lantern-chat/frontend | 9bf63a15e45329a46415e954efdb263860a22a67 | [
"FSFAP"
] | null | null | null | interface FreeState {
// consecutive_spoiler
cs: number,
// consecutive_code
cc: number,
// flags
f: number,
// position
p: number,
// prefixes that make it not free
r: string[],
}
const INSIDE_CODE_BLOCK: number = 1 << 0;
const INSIDE_SPOILER: number = 1 << 1;
const INSIDE_INLINE_CODE: number = 1 << 2;
const INSIDE_ANY_CODE: number = INSIDE_CODE_BLOCK | INSIDE_INLINE_CODE;
const INSIDE_EMOTE: number = 1 << 3;
const ESCAPED: number = 1 << 4;
const DEFAULT_FREE_FLAGS: number = INSIDE_INLINE_CODE | INSIDE_SPOILER | INSIDE_INLINE_CODE;
const DEFAULT_PREFIXES: string[] = ['<', '\\', ':'];
export function create(prefixes: string[] = DEFAULT_PREFIXES): FreeState {
return { cs: 0, cc: 0, f: 0, p: 0, r: prefixes };
}
const VALID_EMOTE_CHAR: RegExp = /[\w\-]/;
export function incr(self: FreeState, input: string, new_position: number) {
let c, i, { f, cc, cs, p } = self;
input = input.slice(p, new_position);
for(i = 0; i < input.length; i += 1) {
if(f & ESCAPED) {
f &= ~ESCAPED; continue;
}
c = input[i];
if(c == '\\') {
f |= ESCAPED; continue;
}
if(c == '`') {
cc++;
} else {
// if this character is not part of a code token,
// but there were two consecitive code tokens,
// then it was probably a zero-length inline code span
if(cc == 2 && !(f & INSIDE_CODE_BLOCK)) {
f ^= INSIDE_INLINE_CODE;
}
cc = 0;
}
if(c == '|') {
cs++;
} else {
cs = 0;
}
if(cc == 3) {
// toggle code block flag
f ^= INSIDE_CODE_BLOCK;
// remove inline code flag
f &= ~INSIDE_INLINE_CODE;
} else {
if(!(f & INSIDE_CODE_BLOCK)) {
// if does not contain code block flag
if(cc == 1) {
f ^= INSIDE_INLINE_CODE;
}
if(cs == 2) {
f ^= INSIDE_SPOILER;
}
}
// if not in any code
if(!(f & INSIDE_ANY_CODE)) {
if(c == ':') {
f ^= INSIDE_EMOTE;
} else if(!VALID_EMOTE_CHAR.test(c)) {
f &= ~INSIDE_EMOTE;
}
}
}
}
self.p = new_position;
self.f = f;
self.cc = cc;
self.cs = cs;
}
export function is_free(self: FreeState, input: string, new_position: number, flags: number = DEFAULT_FREE_FLAGS): boolean {
// start of the string is trivially free
if(new_position == 0) return true;
// if the position is prefixed by escaped
if(self.r.includes(input[new_position - 1])) return false;
incr(self, input, new_position);
// if the flags intersect
if((self.f & flags) != 0) return false;
return true;
}
export function is_free_simple(input: string, position: number, prefixes: string[] = DEFAULT_PREFIXES, flags: number = DEFAULT_FREE_FLAGS): boolean {
return is_free(create(prefixes), input, position, flags);
}
export function is_inside_code(input: string, position: number): boolean {
if(position == 0) return false;
let f = create([]);
incr(f, input, position);
return !!(f.f & (INSIDE_INLINE_CODE | INSIDE_CODE_BLOCK));
}
export function is_inside_spoiler(input: string, position: number): boolean {
if(position == 0) return false;
let f = create([]);
incr(f, input, position);
return !!(f.f & INSIDE_SPOILER);
}
export function emote_start(input: string, position: number): number {
let start = position;
while(start > 0 && input[start] != ':') { start--; }
let is_valid = /^:[\w\-]*$/.test(input.slice(start, position)) &&
input.slice(0, position).match(/:/g)!.length % 2 == 1;
return is_valid ? start : -1;
}
| 26.373333 | 149 | 0.543478 | 98 | 7 | 0 | 18 | 16 | 5 | 3 | 0 | 34 | 1 | 0 | 9.714286 | 1,169 | 0.021386 | 0.013687 | 0.004277 | 0.000855 | 0 | 0 | 0.73913 | 0.26601 | interface FreeState {
// consecutive_spoiler
cs,
// consecutive_code
cc,
// flags
f,
// position
p,
// prefixes that make it not free
r,
}
const INSIDE_CODE_BLOCK = 1 << 0;
const INSIDE_SPOILER = 1 << 1;
const INSIDE_INLINE_CODE = 1 << 2;
const INSIDE_ANY_CODE = INSIDE_CODE_BLOCK | INSIDE_INLINE_CODE;
const INSIDE_EMOTE = 1 << 3;
const ESCAPED = 1 << 4;
const DEFAULT_FREE_FLAGS = INSIDE_INLINE_CODE | INSIDE_SPOILER | INSIDE_INLINE_CODE;
const DEFAULT_PREFIXES = ['<', '\\', ':'];
export /* Example usages of 'create' are shown below:
is_free(create(prefixes), input, position, flags);
create([]);
*/
function create(prefixes = DEFAULT_PREFIXES) {
return { cs: 0, cc: 0, f: 0, p: 0, r: prefixes };
}
const VALID_EMOTE_CHAR = /[\w\-]/;
export /* Example usages of 'incr' are shown below:
incr(self, input, new_position);
incr(f, input, position);
*/
function incr(self, input, new_position) {
let c, i, { f, cc, cs, p } = self;
input = input.slice(p, new_position);
for(i = 0; i < input.length; i += 1) {
if(f & ESCAPED) {
f &= ~ESCAPED; continue;
}
c = input[i];
if(c == '\\') {
f |= ESCAPED; continue;
}
if(c == '`') {
cc++;
} else {
// if this character is not part of a code token,
// but there were two consecitive code tokens,
// then it was probably a zero-length inline code span
if(cc == 2 && !(f & INSIDE_CODE_BLOCK)) {
f ^= INSIDE_INLINE_CODE;
}
cc = 0;
}
if(c == '|') {
cs++;
} else {
cs = 0;
}
if(cc == 3) {
// toggle code block flag
f ^= INSIDE_CODE_BLOCK;
// remove inline code flag
f &= ~INSIDE_INLINE_CODE;
} else {
if(!(f & INSIDE_CODE_BLOCK)) {
// if does not contain code block flag
if(cc == 1) {
f ^= INSIDE_INLINE_CODE;
}
if(cs == 2) {
f ^= INSIDE_SPOILER;
}
}
// if not in any code
if(!(f & INSIDE_ANY_CODE)) {
if(c == ':') {
f ^= INSIDE_EMOTE;
} else if(!VALID_EMOTE_CHAR.test(c)) {
f &= ~INSIDE_EMOTE;
}
}
}
}
self.p = new_position;
self.f = f;
self.cc = cc;
self.cs = cs;
}
export /* Example usages of 'is_free' are shown below:
is_free(create(prefixes), input, position, flags);
*/
function is_free(self, input, new_position, flags = DEFAULT_FREE_FLAGS) {
// start of the string is trivially free
if(new_position == 0) return true;
// if the position is prefixed by escaped
if(self.r.includes(input[new_position - 1])) return false;
incr(self, input, new_position);
// if the flags intersect
if((self.f & flags) != 0) return false;
return true;
}
export function is_free_simple(input, position, prefixes = DEFAULT_PREFIXES, flags = DEFAULT_FREE_FLAGS) {
return is_free(create(prefixes), input, position, flags);
}
export function is_inside_code(input, position) {
if(position == 0) return false;
let f = create([]);
incr(f, input, position);
return !!(f.f & (INSIDE_INLINE_CODE | INSIDE_CODE_BLOCK));
}
export function is_inside_spoiler(input, position) {
if(position == 0) return false;
let f = create([]);
incr(f, input, position);
return !!(f.f & INSIDE_SPOILER);
}
export function emote_start(input, position) {
let start = position;
while(start > 0 && input[start] != ':') { start--; }
let is_valid = /^:[\w\-]*$/.test(input.slice(start, position)) &&
input.slice(0, position).match(/:/g)!.length % 2 == 1;
return is_valid ? start : -1;
}
|
9a7c699fe8f449d3a7a939d3dca5b7e6442a9fd0 | 21,203 | ts | TypeScript | Web Site/React/src/scripts/aes.ts | mr-bwnz/SplendidAppBuilder | 79ec92d4cb805ccf408ff95103a1a0a78bc765b7 | [
"MIT"
] | 1 | 2022-03-01T10:27:25.000Z | 2022-03-01T10:27:25.000Z | Web Site/React/src/scripts/aes.ts | mr-bwnz/SplendidAppBuilder | 79ec92d4cb805ccf408ff95103a1a0a78bc765b7 | [
"MIT"
] | null | null | null | Web Site/React/src/scripts/aes.ts | mr-bwnz/SplendidAppBuilder | 79ec92d4cb805ccf408ff95103a1a0a78bc765b7 | [
"MIT"
] | 3 | 2022-02-21T13:28:37.000Z | 2022-03-18T06:42:07.000Z | /* - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */
/* AES implementation in JavaScript (c) Chris Veness 2005-2011 */
/* http://www.movable-type.co.uk/scripts/aes.html */
/* http://www.movable-type.co.uk/scripts/aes.js */
/* - see http://csrc.nist.gov/publications/PubsFIPS.html#197 */
/* - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */
export default class Aes
{
/**
* AES Cipher function: encrypt 'input' state with Rijndael algorithm
* applies Nr rounds (10/12/14) using key schedule w for 'add round key' stage
*
* @param {Number[]} input 16-byte (128-bit) input state array
* @param {Number[][]} w Key schedule as 2D byte-array (Nr+1 x Nb bytes)
* @returns {Number[]} Encrypted output state array
*/
static cipher( input, w )
{ // main Cipher function [§5.1]
var Nb = 4; // block size (in words): no of columns in state (fixed at 4 for AES)
var Nr = w.length / Nb - 1; // no of rounds: 10/12/14 for 128/192/256-bit keys
var state = [[], [], [], []]; // initialise 4xNb byte-array 'state' with input [§3.4]
for ( var i = 0; i < 4 * Nb; i++ )
state[i % 4][Math.floor( i / 4 )] = input[i];
state = Aes.addRoundKey( state, w, 0, Nb );
for ( var round = 1; round < Nr; round++ )
{
state = Aes.subBytes( state, Nb );
state = Aes.shiftRows( state, Nb );
state = Aes.mixColumns( state, Nb );
state = Aes.addRoundKey( state, w, round, Nb );
}
state = Aes.subBytes( state, Nb );
state = Aes.shiftRows( state, Nb );
state = Aes.addRoundKey( state, w, Nr, Nb );
var output = new Array( 4 * Nb ); // convert state to 1-d array before returning [§3.4]
for ( var i = 0; i < 4 * Nb; i++ )
output[i] = state[i % 4][Math.floor( i / 4 )];
return output;
}
/**
* Perform Key Expansion to generate a Key Schedule
*
* @param {Number[]} key Key as 16/24/32-byte array
* @returns {Number[][]} Expanded key schedule as 2D byte-array (Nr+1 x Nb bytes)
*/
static keyExpansion( key )
{ // generate Key Schedule (byte-array Nr+1 x Nb) from Key [§5.2]
var Nb = 4; // block size (in words): no of columns in state (fixed at 4 for AES)
var Nk = key.length / 4 // key length (in words): 4/6/8 for 128/192/256-bit keys
var Nr = Nk + 6; // no of rounds: 10/12/14 for 128/192/256-bit keys
var w = new Array( Nb * ( Nr + 1 ) );
var temp = new Array( 4 );
for ( var i = 0; i < Nk; i++ )
{
var r = [key[4 * i], key[4 * i + 1], key[4 * i + 2], key[4 * i + 3]];
w[i] = r;
}
for ( var i = Nk; i < ( Nb * ( Nr + 1 ) ); i++ )
{
w[i] = new Array( 4 );
for ( var t = 0; t < 4; t++ )
temp[t] = w[i - 1][t];
if ( i % Nk == 0 )
{
temp = Aes.subWord( Aes.rotWord( temp ) );
for ( var t = 0; t < 4; t++ )
temp[t] ^= Aes.rCon[i / Nk][t];
}
else if ( Nk > 6 && i % Nk == 4 )
{
temp = Aes.subWord( temp );
}
for ( var t = 0; t < 4; t++ )
w[i][t] = w[i - Nk][t] ^ temp[t];
}
return w;
}
/*
* ---- remaining routines are private, not called externally ----
*/
static subBytes( s, Nb )
{ // apply SBox to state S [§5.1.1]
for ( var r = 0; r < 4; r++ )
{
for ( var c = 0; c < Nb; c++ )
s[r][c] = Aes.sBox[s[r][c]];
}
return s;
}
static shiftRows( s, Nb )
{ // shift row r of state S left by r bytes [§5.1.2]
var t = new Array( 4 );
for ( var r = 1; r < 4; r++ )
{
for ( var c = 0; c < 4; c++ )
t[c] = s[r][( c + r ) % Nb]; // shift into temp copy
for ( var c = 0; c < 4; c++ )
s[r][c] = t[c]; // and copy back
} // note that this will work for Nb=4,5,6, but not 7,8 (always 4 for AES):
return s; // see asmaes.sourceforge.net/rijndael/rijndaelImplementation.pdf
}
static mixColumns( s, Nb )
{ // combine bytes of each col of state S [§5.1.3]
for ( var c = 0; c < 4; c++ )
{
var a = new Array( 4 ); // 'a' is a copy of the current column from 's'
var b = new Array( 4 ); // 'b' is a•{02} in GF(2^8)
for ( var i = 0; i < 4; i++ )
{
a[i] = s[i][c];
b[i] = s[i][c] & 0x80 ? s[i][c] << 1 ^ 0x011b : s[i][c] << 1;
}
// a[n] ^ b[n] is a•{03} in GF(2^8)
s[0][c] = b[0] ^ a[1] ^ b[1] ^ a[2] ^ a[3]; // 2*a0 + 3*a1 + a2 + a3
s[1][c] = a[0] ^ b[1] ^ a[2] ^ b[2] ^ a[3]; // a0 * 2*a1 + 3*a2 + a3
s[2][c] = a[0] ^ a[1] ^ b[2] ^ a[3] ^ b[3]; // a0 + a1 + 2*a2 + 3*a3
s[3][c] = a[0] ^ b[0] ^ a[1] ^ a[2] ^ b[3]; // 3*a0 + a1 + a2 + 2*a3
}
return s;
}
static addRoundKey( state, w, rnd, Nb )
{ // xor Round Key into state S [§5.1.4]
for ( var r = 0; r < 4; r++ )
{
for ( var c = 0; c < Nb; c++ )
state[r][c] ^= w[rnd * 4 + c][r];
}
return state;
}
static subWord( w )
{ // apply SBox to 4-byte word w
for ( var i = 0; i < 4; i++ )
w[i] = Aes.sBox[w[i]];
return w;
}
static rotWord( w )
{ // rotate 4-byte word w left by one byte
var tmp = w[0];
for ( var i = 0; i < 3; i++ )
w[i] = w[i + 1];
w[3] = tmp;
return w;
}
// sBox is pre-computed multiplicative inverse in GF(2^8) used in subBytes and keyExpansion [§5.1.1]
static sBox = [0x63, 0x7c, 0x77, 0x7b, 0xf2, 0x6b, 0x6f, 0xc5, 0x30, 0x01, 0x67, 0x2b, 0xfe, 0xd7, 0xab, 0x76,
0xca, 0x82, 0xc9, 0x7d, 0xfa, 0x59, 0x47, 0xf0, 0xad, 0xd4, 0xa2, 0xaf, 0x9c, 0xa4, 0x72, 0xc0,
0xb7, 0xfd, 0x93, 0x26, 0x36, 0x3f, 0xf7, 0xcc, 0x34, 0xa5, 0xe5, 0xf1, 0x71, 0xd8, 0x31, 0x15,
0x04, 0xc7, 0x23, 0xc3, 0x18, 0x96, 0x05, 0x9a, 0x07, 0x12, 0x80, 0xe2, 0xeb, 0x27, 0xb2, 0x75,
0x09, 0x83, 0x2c, 0x1a, 0x1b, 0x6e, 0x5a, 0xa0, 0x52, 0x3b, 0xd6, 0xb3, 0x29, 0xe3, 0x2f, 0x84,
0x53, 0xd1, 0x00, 0xed, 0x20, 0xfc, 0xb1, 0x5b, 0x6a, 0xcb, 0xbe, 0x39, 0x4a, 0x4c, 0x58, 0xcf,
0xd0, 0xef, 0xaa, 0xfb, 0x43, 0x4d, 0x33, 0x85, 0x45, 0xf9, 0x02, 0x7f, 0x50, 0x3c, 0x9f, 0xa8,
0x51, 0xa3, 0x40, 0x8f, 0x92, 0x9d, 0x38, 0xf5, 0xbc, 0xb6, 0xda, 0x21, 0x10, 0xff, 0xf3, 0xd2,
0xcd, 0x0c, 0x13, 0xec, 0x5f, 0x97, 0x44, 0x17, 0xc4, 0xa7, 0x7e, 0x3d, 0x64, 0x5d, 0x19, 0x73,
0x60, 0x81, 0x4f, 0xdc, 0x22, 0x2a, 0x90, 0x88, 0x46, 0xee, 0xb8, 0x14, 0xde, 0x5e, 0x0b, 0xdb,
0xe0, 0x32, 0x3a, 0x0a, 0x49, 0x06, 0x24, 0x5c, 0xc2, 0xd3, 0xac, 0x62, 0x91, 0x95, 0xe4, 0x79,
0xe7, 0xc8, 0x37, 0x6d, 0x8d, 0xd5, 0x4e, 0xa9, 0x6c, 0x56, 0xf4, 0xea, 0x65, 0x7a, 0xae, 0x08,
0xba, 0x78, 0x25, 0x2e, 0x1c, 0xa6, 0xb4, 0xc6, 0xe8, 0xdd, 0x74, 0x1f, 0x4b, 0xbd, 0x8b, 0x8a,
0x70, 0x3e, 0xb5, 0x66, 0x48, 0x03, 0xf6, 0x0e, 0x61, 0x35, 0x57, 0xb9, 0x86, 0xc1, 0x1d, 0x9e,
0xe1, 0xf8, 0x98, 0x11, 0x69, 0xd9, 0x8e, 0x94, 0x9b, 0x1e, 0x87, 0xe9, 0xce, 0x55, 0x28, 0xdf,
0x8c, 0xa1, 0x89, 0x0d, 0xbf, 0xe6, 0x42, 0x68, 0x41, 0x99, 0x2d, 0x0f, 0xb0, 0x54, 0xbb, 0x16];
// rCon is Round Constant used for the Key Expansion [1st col is 2^(r-1) in GF(2^8)] [§5.2]
static rCon = [[0x00, 0x00, 0x00, 0x00],
[0x01, 0x00, 0x00, 0x00],
[0x02, 0x00, 0x00, 0x00],
[0x04, 0x00, 0x00, 0x00],
[0x08, 0x00, 0x00, 0x00],
[0x10, 0x00, 0x00, 0x00],
[0x20, 0x00, 0x00, 0x00],
[0x40, 0x00, 0x00, 0x00],
[0x80, 0x00, 0x00, 0x00],
[0x1b, 0x00, 0x00, 0x00],
[0x36, 0x00, 0x00, 0x00]];
/* - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */
/* Utf8 class: encode / decode between multi-byte Unicode characters and UTF-8 multiple */
/* http://www.movable-type.co.uk/scripts/utf8.js */
/* single-byte character encoding (c) Chris Veness 2002-2011 */
/* - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */
/* changelog
* 2010-09-29: fixed decode order of operation to avoid falsely recognising decoded string as 3-byte
* utf-8 charaacter
*/
static Ctr = class // Aes.Ctr namespace: a subclass or extension of Aes
{
/**
* Encrypt a text using AES encryption in Counter mode of operation
*
* Unicode multi-byte character safe
*
* @param {String} plaintext Source text to be encrypted
* @param {String} password The password to use to generate a key
* @param {Number} nBits Number of bits to be used in the key (128, 192, or 256)
* @returns {string} Encrypted text
*/
static encrypt( plaintext, password, nBits )
{
var blockSize = 16; // block size fixed at 16 bytes / 128 bits (Nb=4) for AES
if ( !( nBits == 128 || nBits == 192 || nBits == 256 ) ) return ''; // standard allows 128/192/256 bit keys
plaintext = Utf8.encode( plaintext );
password = Utf8.encode( password );
//var t = new Date(); // timer
// use AES itself to encrypt password to get cipher key (using plain password as source for key
// expansion) - gives us well encrypted key (though hashed key might be preferred for prod'n use)
var nBytes = nBits / 8; // no bytes in key (16/24/32)
var pwBytes = new Array( nBytes );
for ( var i = 0; i < nBytes; i++ )
{ // use 1st 16/24/32 chars of password for key
pwBytes[i] = isNaN( password.charCodeAt( i ) ) ? 0 : password.charCodeAt( i );
}
var key = Aes.cipher( pwBytes, Aes.keyExpansion( pwBytes ) ); // gives us 16-byte key
key = key.concat( key.slice( 0, nBytes - 16 ) ); // expand key to 16/24/32 bytes long
// initialise 1st 8 bytes of counter block with nonce (NIST SP800-38A §B.2): [0-1] = millisec,
// [2-3] = random, [4-7] = seconds, together giving full sub-millisec uniqueness up to Feb 2106
var counterBlock = new Array( blockSize );
var nonce = ( new Date() ).getTime(); // timestamp: milliseconds since 1-Jan-1970
var nonceMs = nonce % 1000;
var nonceSec = Math.floor( nonce / 1000 );
var nonceRnd = Math.floor( Math.random() * 0xffff );
for ( var i = 0; i < 2; i++ )
counterBlock[i] = ( nonceMs >>> i * 8 ) & 0xff;
for ( var i = 0; i < 2; i++ )
counterBlock[i + 2] = ( nonceRnd >>> i * 8 ) & 0xff;
for ( var i = 0; i < 4; i++ )
counterBlock[i + 4] = ( nonceSec >>> i * 8 ) & 0xff;
// and convert it to a string to go on the front of the ciphertext
var ctrTxt = '';
for ( var i = 0; i < 8; i++ )
ctrTxt += String.fromCharCode( counterBlock[i] );
// generate key schedule - an expansion of the key into distinct Key Rounds for each round
var keySchedule = Aes.keyExpansion( key );
var blockCount = Math.ceil( plaintext.length / blockSize );
var ciphertxt = new Array( blockCount ); // ciphertext as array of strings
for ( var b = 0; b < blockCount; b++ )
{
// set counter (block #) in last 8 bytes of counter block (leaving nonce in 1st 8 bytes)
// done in two stages for 32-bit ops: using two words allows us to go past 2^32 blocks (68GB)
for ( var c = 0; c < 4; c++ )
counterBlock[15 - c] = ( b >>> c * 8 ) & 0xff;
for ( var c = 0; c < 4; c++ )
counterBlock[15 - c - 4] = ( b / 0x100000000 >>> c * 8 )
var cipherCntr = Aes.cipher( counterBlock, keySchedule ); // -- encrypt counter block --
// block size is reduced on final block
var blockLength = b < blockCount - 1 ? blockSize : ( plaintext.length - 1 ) % blockSize + 1;
var cipherChar = new Array( blockLength );
for ( var i = 0; i < blockLength; i++ )
{ // -- xor plaintext with ciphered counter char-by-char --
cipherChar[i] = cipherCntr[i] ^ plaintext.charCodeAt( b * blockSize + i );
cipherChar[i] = String.fromCharCode( cipherChar[i] );
}
ciphertxt[b] = cipherChar.join( '' );
}
// Array.join is more efficient than repeated string concatenation in IE
var ciphertext = ctrTxt + ciphertxt.join( '' );
ciphertext = Base64.encode( ciphertext ); // encode in base64
//alert((new Date()) - t);
return ciphertext;
}
/**
* Decrypt a text encrypted by AES in counter mode of operation
*
* @param {String} ciphertext Source text to be encrypted
* @param {String} password The password to use to generate a key
* @param {Number} nBits Number of bits to be used in the key (128, 192, or 256)
* @returns {String} Decrypted text
*/
static decrypt = function ( ciphertext, password, nBits )
{
var blockSize = 16; // block size fixed at 16 bytes / 128 bits (Nb=4) for AES
if ( !( nBits == 128 || nBits == 192 || nBits == 256 ) ) return ''; // standard allows 128/192/256 bit keys
ciphertext = Base64.decode( ciphertext );
password = Utf8.encode( password );
//var t = new Date(); // timer
// use AES to encrypt password (mirroring encrypt routine)
var nBytes = nBits / 8; // no bytes in key
var pwBytes = new Array( nBytes );
for ( var i = 0; i < nBytes; i++ )
{
pwBytes[i] = isNaN( password.charCodeAt( i ) ) ? 0 : password.charCodeAt( i );
}
var key = Aes.cipher( pwBytes, Aes.keyExpansion( pwBytes ) );
key = key.concat( key.slice( 0, nBytes - 16 ) ); // expand key to 16/24/32 bytes long
// recover nonce from 1st 8 bytes of ciphertext
var counterBlock = new Array( 8 );
var ctrTxt = ciphertext.slice( 0, 8 );
for ( var i = 0; i < 8; i++ )
counterBlock[i] = ctrTxt.charCodeAt( i );
// generate key schedule
var keySchedule = Aes.keyExpansion( key );
// separate ciphertext into blocks (skipping past initial 8 bytes)
var nBlocks = Math.ceil( ( ciphertext.length - 8 ) / blockSize );
var ct = new Array( nBlocks );
for ( var b = 0; b < nBlocks; b++ )
ct[b] = ciphertext.slice( 8 + b * blockSize, 8 + b * blockSize + blockSize );
ciphertext = ct; // ciphertext is now array of block-length strings
// plaintext will get generated block-by-block into array of block-length strings
var plaintxt = new Array( ciphertext.length );
for ( var b = 0; b < nBlocks; b++ )
{
// set counter (block #) in last 8 bytes of counter block (leaving nonce in 1st 8 bytes)
for ( var c = 0; c < 4; c++ )
counterBlock[15 - c] = ( ( b ) >>> c * 8 ) & 0xff;
for ( var c = 0; c < 4; c++ )
counterBlock[15 - c - 4] = ( ( ( b + 1 ) / 0x100000000 - 1 ) >>> c * 8 ) & 0xff;
var cipherCntr = Aes.cipher( counterBlock, keySchedule ); // encrypt counter block
var plaintxtByte = new Array( ciphertext[b].length );
for ( var i = 0; i < ciphertext[b].length; i++ )
{
// -- xor plaintxt with ciphered counter byte-by-byte --
plaintxtByte[i] = cipherCntr[i] ^ ciphertext[b].charCodeAt( i );
plaintxtByte[i] = String.fromCharCode( plaintxtByte[i] );
}
plaintxt[b] = plaintxtByte.join( '' );
}
// join array of blocks into single plaintext string
var plaintext = plaintxt.join( '' );
plaintext = Utf8.decode( plaintext ); // decode from UTF8 back to Unicode multi-byte chars
//alert((new Date()) - t);
return plaintext;
}
}
}
class Utf8
{
/**
* Encode multi-byte Unicode string into utf-8 multiple single-byte characters
* (BMP / basic multilingual plane only)
*
* Chars in range U+0080 - U+07FF are encoded in 2 chars, U+0800 - U+FFFF in 3 chars
*
* @param {String} strUni Unicode string to be encoded as UTF-8
* @returns {String} encoded string
*/
static encode( strUni )
{
// use regular expressions & String.replace callback function for better efficiency
// than procedural approaches
var strUtf = strUni.replace(
/[\u0080-\u07ff]/g, // U+0080 - U+07FF => 2 bytes 110yyyyy, 10zzzzzz
function ( c )
{
var cc = c.charCodeAt( 0 );
return String.fromCharCode( 0xc0 | cc >> 6, 0x80 | cc & 0x3f );
}
);
strUtf = strUtf.replace(
/[\u0800-\uffff]/g, // U+0800 - U+FFFF => 3 bytes 1110xxxx, 10yyyyyy, 10zzzzzz
function ( c )
{
var cc = c.charCodeAt( 0 );
return String.fromCharCode( 0xe0 | cc >> 12, 0x80 | cc >> 6 & 0x3F, 0x80 | cc & 0x3f );
}
);
return strUtf;
}
/**
* Decode utf-8 encoded string back into multi-byte Unicode characters
*
* @param {String} strUtf UTF-8 string to be decoded back to Unicode
* @returns {String} decoded string
*/
static decode( strUtf )
{
// note: decode 3-byte chars first as decoded 2-byte strings could appear to be 3-byte char!
var strUni = strUtf.replace(
/[\u00e0-\u00ef][\u0080-\u00bf][\u0080-\u00bf]/g, // 3-byte chars
function ( c )
{ // (note parentheses for precence)
var cc = ( ( c.charCodeAt( 0 ) & 0x0f ) << 12 ) | ( ( c.charCodeAt( 1 ) & 0x3f ) << 6 ) | ( c.charCodeAt( 2 ) & 0x3f );
return String.fromCharCode( cc );
}
);
strUni = strUni.replace(
/[\u00c0-\u00df][\u0080-\u00bf]/g, // 2-byte chars
function ( c )
{ // (note parentheses for precence)
var cc = ( c.charCodeAt( 0 ) & 0x1f ) << 6 | c.charCodeAt( 1 ) & 0x3f;
return String.fromCharCode( cc );
}
);
return strUni;
}
/* - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */
/* Base64 class: Base 64 encoding / decoding (c) Chris Veness 2002-2011 */
/* http://www.movable-type.co.uk/scripts/base64.js */
/* note: depends on Utf8 class */
/* - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */
}
class Base64
{
static code = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";
/**
* Encode string into Base64, as defined by RFC 4648 [http://tools.ietf.org/html/rfc4648]
* (instance method extending String object). As per RFC 4648, no newlines are added.
*
* @param {String} str The string to be encoded as base-64
* @param {Boolean} [utf8encode=false] Flag to indicate whether str is Unicode string to be encoded
* to UTF8 before conversion to base64; otherwise string is assumed to be 8-bit characters
* @returns {String} Base64-encoded string
*/
static encode( str, utf8encode?)
{ // http://tools.ietf.org/html/rfc4648
utf8encode = ( typeof utf8encode == 'undefined' ) ? false : utf8encode;
var o1, o2, o3, bits, h1, h2, h3, h4, e = [], pad = '', c, plain, coded;
var b64 = Base64.code;
plain = utf8encode ? Utf8.encode( str ) : str;
c = plain.length % 3; // pad string to length of multiple of 3
if ( c > 0 )
{
while ( c++ < 3 )
{
pad += '='; plain += '\0';
}
}
// note: doing padding here saves us doing special-case packing for trailing 1 or 2 chars
for ( c = 0; c < plain.length; c += 3 )
{ // pack three octets into four hexets
o1 = plain.charCodeAt( c );
o2 = plain.charCodeAt( c + 1 );
o3 = plain.charCodeAt( c + 2 );
bits = o1 << 16 | o2 << 8 | o3;
h1 = bits >> 18 & 0x3f;
h2 = bits >> 12 & 0x3f;
h3 = bits >> 6 & 0x3f;
h4 = bits & 0x3f;
// use hextets to index into code string
e[c / 3] = b64.charAt( h1 ) + b64.charAt( h2 ) + b64.charAt( h3 ) + b64.charAt( h4 );
}
coded = e.join( '' ); // join() is far faster than repeated string concatenation in IE
// replace 'A's from padded nulls with '='s
coded = coded.slice( 0, coded.length - pad.length ) + pad;
return coded;
}
/**
* Decode string from Base64, as defined by RFC 4648 [http://tools.ietf.org/html/rfc4648]
* (instance method extending String object). As per RFC 4648, newlines are not catered for.
*
* @param {String} str The string to be decoded from base-64
* @param {Boolean} [utf8decode=false] Flag to indicate whether str is Unicode string to be decoded
* from UTF8 after conversion from base64
* @returns {String} decoded string
*/
static decode( str, utf8decode?)
{
utf8decode = ( typeof utf8decode == 'undefined' ) ? false : utf8decode;
var o1, o2, o3, h1, h2, h3, h4, bits, d = [], plain, coded;
var b64 = Base64.code;
coded = utf8decode ? Utf8.decode( str ) : str;
for ( var c = 0; c < coded.length; c += 4 )
{ // unpack four hexets into three octets
h1 = b64.indexOf( coded.charAt( c ) );
h2 = b64.indexOf( coded.charAt( c + 1 ) );
h3 = b64.indexOf( coded.charAt( c + 2 ) );
h4 = b64.indexOf( coded.charAt( c + 3 ) );
bits = h1 << 18 | h2 << 12 | h3 << 6 | h4;
o1 = bits >>> 16 & 0xff;
o2 = bits >>> 8 & 0xff;
o3 = bits & 0xff;
d[c / 4] = String.fromCharCode( o1, o2, o3 );
// check for padding
if ( h4 == 0x40 ) d[c / 4] = String.fromCharCode( o1, o2 );
if ( h3 == 0x40 ) d[c / 4] = String.fromCharCode( o1 );
}
plain = d.join( '' ); // join() is far faster than repeated string concatenation in IE
return utf8decode ? Utf8.decode( plain ) : plain;
}
}
/* - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */
/* AES Counter-mode implementation in JavaScript (c) Chris Veness 2005-2011 */
/* http://www.movable-type.co.uk/scripts/aes-ctr.js */
/* - see http://csrc.nist.gov/publications/nistpubs/800-38a/sp800-38a.pdf */
/* - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */
| 39.192237 | 123 | 0.559072 | 345 | 18 | 0 | 31 | 112 | 5 | 10 | 0 | 0 | 3 | 2 | 15.055556 | 9,045 | 0.005417 | 0.012383 | 0.000553 | 0.000332 | 0.000221 | 0 | 0 | 0.22625 | /* - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */
/* AES implementation in JavaScript (c) Chris Veness 2005-2011 */
/* http://www.movable-type.co.uk/scripts/aes.html */
/* http://www.movable-type.co.uk/scripts/aes.js */
/* - see http://csrc.nist.gov/publications/PubsFIPS.html#197 */
/* - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */
export default class Aes
{
/**
* AES Cipher function: encrypt 'input' state with Rijndael algorithm
* applies Nr rounds (10/12/14) using key schedule w for 'add round key' stage
*
* @param {Number[]} input 16-byte (128-bit) input state array
* @param {Number[][]} w Key schedule as 2D byte-array (Nr+1 x Nb bytes)
* @returns {Number[]} Encrypted output state array
*/
static cipher( input, w )
{ // main Cipher function [§5.1]
var Nb = 4; // block size (in words): no of columns in state (fixed at 4 for AES)
var Nr = w.length / Nb - 1; // no of rounds: 10/12/14 for 128/192/256-bit keys
var state = [[], [], [], []]; // initialise 4xNb byte-array 'state' with input [§3.4]
for ( var i = 0; i < 4 * Nb; i++ )
state[i % 4][Math.floor( i / 4 )] = input[i];
state = Aes.addRoundKey( state, w, 0, Nb );
for ( var round = 1; round < Nr; round++ )
{
state = Aes.subBytes( state, Nb );
state = Aes.shiftRows( state, Nb );
state = Aes.mixColumns( state, Nb );
state = Aes.addRoundKey( state, w, round, Nb );
}
state = Aes.subBytes( state, Nb );
state = Aes.shiftRows( state, Nb );
state = Aes.addRoundKey( state, w, Nr, Nb );
var output = new Array( 4 * Nb ); // convert state to 1-d array before returning [§3.4]
for ( var i = 0; i < 4 * Nb; i++ )
output[i] = state[i % 4][Math.floor( i / 4 )];
return output;
}
/**
* Perform Key Expansion to generate a Key Schedule
*
* @param {Number[]} key Key as 16/24/32-byte array
* @returns {Number[][]} Expanded key schedule as 2D byte-array (Nr+1 x Nb bytes)
*/
static keyExpansion( key )
{ // generate Key Schedule (byte-array Nr+1 x Nb) from Key [§5.2]
var Nb = 4; // block size (in words): no of columns in state (fixed at 4 for AES)
var Nk = key.length / 4 // key length (in words): 4/6/8 for 128/192/256-bit keys
var Nr = Nk + 6; // no of rounds: 10/12/14 for 128/192/256-bit keys
var w = new Array( Nb * ( Nr + 1 ) );
var temp = new Array( 4 );
for ( var i = 0; i < Nk; i++ )
{
var r = [key[4 * i], key[4 * i + 1], key[4 * i + 2], key[4 * i + 3]];
w[i] = r;
}
for ( var i = Nk; i < ( Nb * ( Nr + 1 ) ); i++ )
{
w[i] = new Array( 4 );
for ( var t = 0; t < 4; t++ )
temp[t] = w[i - 1][t];
if ( i % Nk == 0 )
{
temp = Aes.subWord( Aes.rotWord( temp ) );
for ( var t = 0; t < 4; t++ )
temp[t] ^= Aes.rCon[i / Nk][t];
}
else if ( Nk > 6 && i % Nk == 4 )
{
temp = Aes.subWord( temp );
}
for ( var t = 0; t < 4; t++ )
w[i][t] = w[i - Nk][t] ^ temp[t];
}
return w;
}
/*
* ---- remaining routines are private, not called externally ----
*/
static subBytes( s, Nb )
{ // apply SBox to state S [§5.1.1]
for ( var r = 0; r < 4; r++ )
{
for ( var c = 0; c < Nb; c++ )
s[r][c] = Aes.sBox[s[r][c]];
}
return s;
}
static shiftRows( s, Nb )
{ // shift row r of state S left by r bytes [§5.1.2]
var t = new Array( 4 );
for ( var r = 1; r < 4; r++ )
{
for ( var c = 0; c < 4; c++ )
t[c] = s[r][( c + r ) % Nb]; // shift into temp copy
for ( var c = 0; c < 4; c++ )
s[r][c] = t[c]; // and copy back
} // note that this will work for Nb=4,5,6, but not 7,8 (always 4 for AES):
return s; // see asmaes.sourceforge.net/rijndael/rijndaelImplementation.pdf
}
static mixColumns( s, Nb )
{ // combine bytes of each col of state S [§5.1.3]
for ( var c = 0; c < 4; c++ )
{
var a = new Array( 4 ); // 'a' is a copy of the current column from 's'
var b = new Array( 4 ); // 'b' is a•{02} in GF(2^8)
for ( var i = 0; i < 4; i++ )
{
a[i] = s[i][c];
b[i] = s[i][c] & 0x80 ? s[i][c] << 1 ^ 0x011b : s[i][c] << 1;
}
// a[n] ^ b[n] is a•{03} in GF(2^8)
s[0][c] = b[0] ^ a[1] ^ b[1] ^ a[2] ^ a[3]; // 2*a0 + 3*a1 + a2 + a3
s[1][c] = a[0] ^ b[1] ^ a[2] ^ b[2] ^ a[3]; // a0 * 2*a1 + 3*a2 + a3
s[2][c] = a[0] ^ a[1] ^ b[2] ^ a[3] ^ b[3]; // a0 + a1 + 2*a2 + 3*a3
s[3][c] = a[0] ^ b[0] ^ a[1] ^ a[2] ^ b[3]; // 3*a0 + a1 + a2 + 2*a3
}
return s;
}
static addRoundKey( state, w, rnd, Nb )
{ // xor Round Key into state S [§5.1.4]
for ( var r = 0; r < 4; r++ )
{
for ( var c = 0; c < Nb; c++ )
state[r][c] ^= w[rnd * 4 + c][r];
}
return state;
}
static subWord( w )
{ // apply SBox to 4-byte word w
for ( var i = 0; i < 4; i++ )
w[i] = Aes.sBox[w[i]];
return w;
}
static rotWord( w )
{ // rotate 4-byte word w left by one byte
var tmp = w[0];
for ( var i = 0; i < 3; i++ )
w[i] = w[i + 1];
w[3] = tmp;
return w;
}
// sBox is pre-computed multiplicative inverse in GF(2^8) used in subBytes and keyExpansion [§5.1.1]
static sBox = [0x63, 0x7c, 0x77, 0x7b, 0xf2, 0x6b, 0x6f, 0xc5, 0x30, 0x01, 0x67, 0x2b, 0xfe, 0xd7, 0xab, 0x76,
0xca, 0x82, 0xc9, 0x7d, 0xfa, 0x59, 0x47, 0xf0, 0xad, 0xd4, 0xa2, 0xaf, 0x9c, 0xa4, 0x72, 0xc0,
0xb7, 0xfd, 0x93, 0x26, 0x36, 0x3f, 0xf7, 0xcc, 0x34, 0xa5, 0xe5, 0xf1, 0x71, 0xd8, 0x31, 0x15,
0x04, 0xc7, 0x23, 0xc3, 0x18, 0x96, 0x05, 0x9a, 0x07, 0x12, 0x80, 0xe2, 0xeb, 0x27, 0xb2, 0x75,
0x09, 0x83, 0x2c, 0x1a, 0x1b, 0x6e, 0x5a, 0xa0, 0x52, 0x3b, 0xd6, 0xb3, 0x29, 0xe3, 0x2f, 0x84,
0x53, 0xd1, 0x00, 0xed, 0x20, 0xfc, 0xb1, 0x5b, 0x6a, 0xcb, 0xbe, 0x39, 0x4a, 0x4c, 0x58, 0xcf,
0xd0, 0xef, 0xaa, 0xfb, 0x43, 0x4d, 0x33, 0x85, 0x45, 0xf9, 0x02, 0x7f, 0x50, 0x3c, 0x9f, 0xa8,
0x51, 0xa3, 0x40, 0x8f, 0x92, 0x9d, 0x38, 0xf5, 0xbc, 0xb6, 0xda, 0x21, 0x10, 0xff, 0xf3, 0xd2,
0xcd, 0x0c, 0x13, 0xec, 0x5f, 0x97, 0x44, 0x17, 0xc4, 0xa7, 0x7e, 0x3d, 0x64, 0x5d, 0x19, 0x73,
0x60, 0x81, 0x4f, 0xdc, 0x22, 0x2a, 0x90, 0x88, 0x46, 0xee, 0xb8, 0x14, 0xde, 0x5e, 0x0b, 0xdb,
0xe0, 0x32, 0x3a, 0x0a, 0x49, 0x06, 0x24, 0x5c, 0xc2, 0xd3, 0xac, 0x62, 0x91, 0x95, 0xe4, 0x79,
0xe7, 0xc8, 0x37, 0x6d, 0x8d, 0xd5, 0x4e, 0xa9, 0x6c, 0x56, 0xf4, 0xea, 0x65, 0x7a, 0xae, 0x08,
0xba, 0x78, 0x25, 0x2e, 0x1c, 0xa6, 0xb4, 0xc6, 0xe8, 0xdd, 0x74, 0x1f, 0x4b, 0xbd, 0x8b, 0x8a,
0x70, 0x3e, 0xb5, 0x66, 0x48, 0x03, 0xf6, 0x0e, 0x61, 0x35, 0x57, 0xb9, 0x86, 0xc1, 0x1d, 0x9e,
0xe1, 0xf8, 0x98, 0x11, 0x69, 0xd9, 0x8e, 0x94, 0x9b, 0x1e, 0x87, 0xe9, 0xce, 0x55, 0x28, 0xdf,
0x8c, 0xa1, 0x89, 0x0d, 0xbf, 0xe6, 0x42, 0x68, 0x41, 0x99, 0x2d, 0x0f, 0xb0, 0x54, 0xbb, 0x16];
// rCon is Round Constant used for the Key Expansion [1st col is 2^(r-1) in GF(2^8)] [§5.2]
static rCon = [[0x00, 0x00, 0x00, 0x00],
[0x01, 0x00, 0x00, 0x00],
[0x02, 0x00, 0x00, 0x00],
[0x04, 0x00, 0x00, 0x00],
[0x08, 0x00, 0x00, 0x00],
[0x10, 0x00, 0x00, 0x00],
[0x20, 0x00, 0x00, 0x00],
[0x40, 0x00, 0x00, 0x00],
[0x80, 0x00, 0x00, 0x00],
[0x1b, 0x00, 0x00, 0x00],
[0x36, 0x00, 0x00, 0x00]];
/* - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */
/* Utf8 class: encode / decode between multi-byte Unicode characters and UTF-8 multiple */
/* http://www.movable-type.co.uk/scripts/utf8.js */
/* single-byte character encoding (c) Chris Veness 2002-2011 */
/* - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */
/* changelog
* 2010-09-29: fixed decode order of operation to avoid falsely recognising decoded string as 3-byte
* utf-8 charaacter
*/
static Ctr = class // Aes.Ctr namespace: a subclass or extension of Aes
{
/**
* Encrypt a text using AES encryption in Counter mode of operation
*
* Unicode multi-byte character safe
*
* @param {String} plaintext Source text to be encrypted
* @param {String} password The password to use to generate a key
* @param {Number} nBits Number of bits to be used in the key (128, 192, or 256)
* @returns {string} Encrypted text
*/
static encrypt( plaintext, password, nBits )
{
var blockSize = 16; // block size fixed at 16 bytes / 128 bits (Nb=4) for AES
if ( !( nBits == 128 || nBits == 192 || nBits == 256 ) ) return ''; // standard allows 128/192/256 bit keys
plaintext = Utf8.encode( plaintext );
password = Utf8.encode( password );
//var t = new Date(); // timer
// use AES itself to encrypt password to get cipher key (using plain password as source for key
// expansion) - gives us well encrypted key (though hashed key might be preferred for prod'n use)
var nBytes = nBits / 8; // no bytes in key (16/24/32)
var pwBytes = new Array( nBytes );
for ( var i = 0; i < nBytes; i++ )
{ // use 1st 16/24/32 chars of password for key
pwBytes[i] = isNaN( password.charCodeAt( i ) ) ? 0 : password.charCodeAt( i );
}
var key = Aes.cipher( pwBytes, Aes.keyExpansion( pwBytes ) ); // gives us 16-byte key
key = key.concat( key.slice( 0, nBytes - 16 ) ); // expand key to 16/24/32 bytes long
// initialise 1st 8 bytes of counter block with nonce (NIST SP800-38A §B.2): [0-1] = millisec,
// [2-3] = random, [4-7] = seconds, together giving full sub-millisec uniqueness up to Feb 2106
var counterBlock = new Array( blockSize );
var nonce = ( new Date() ).getTime(); // timestamp: milliseconds since 1-Jan-1970
var nonceMs = nonce % 1000;
var nonceSec = Math.floor( nonce / 1000 );
var nonceRnd = Math.floor( Math.random() * 0xffff );
for ( var i = 0; i < 2; i++ )
counterBlock[i] = ( nonceMs >>> i * 8 ) & 0xff;
for ( var i = 0; i < 2; i++ )
counterBlock[i + 2] = ( nonceRnd >>> i * 8 ) & 0xff;
for ( var i = 0; i < 4; i++ )
counterBlock[i + 4] = ( nonceSec >>> i * 8 ) & 0xff;
// and convert it to a string to go on the front of the ciphertext
var ctrTxt = '';
for ( var i = 0; i < 8; i++ )
ctrTxt += String.fromCharCode( counterBlock[i] );
// generate key schedule - an expansion of the key into distinct Key Rounds for each round
var keySchedule = Aes.keyExpansion( key );
var blockCount = Math.ceil( plaintext.length / blockSize );
var ciphertxt = new Array( blockCount ); // ciphertext as array of strings
for ( var b = 0; b < blockCount; b++ )
{
// set counter (block #) in last 8 bytes of counter block (leaving nonce in 1st 8 bytes)
// done in two stages for 32-bit ops: using two words allows us to go past 2^32 blocks (68GB)
for ( var c = 0; c < 4; c++ )
counterBlock[15 - c] = ( b >>> c * 8 ) & 0xff;
for ( var c = 0; c < 4; c++ )
counterBlock[15 - c - 4] = ( b / 0x100000000 >>> c * 8 )
var cipherCntr = Aes.cipher( counterBlock, keySchedule ); // -- encrypt counter block --
// block size is reduced on final block
var blockLength = b < blockCount - 1 ? blockSize : ( plaintext.length - 1 ) % blockSize + 1;
var cipherChar = new Array( blockLength );
for ( var i = 0; i < blockLength; i++ )
{ // -- xor plaintext with ciphered counter char-by-char --
cipherChar[i] = cipherCntr[i] ^ plaintext.charCodeAt( b * blockSize + i );
cipherChar[i] = String.fromCharCode( cipherChar[i] );
}
ciphertxt[b] = cipherChar.join( '' );
}
// Array.join is more efficient than repeated string concatenation in IE
var ciphertext = ctrTxt + ciphertxt.join( '' );
ciphertext = Base64.encode( ciphertext ); // encode in base64
//alert((new Date()) - t);
return ciphertext;
}
/**
* Decrypt a text encrypted by AES in counter mode of operation
*
* @param {String} ciphertext Source text to be encrypted
* @param {String} password The password to use to generate a key
* @param {Number} nBits Number of bits to be used in the key (128, 192, or 256)
* @returns {String} Decrypted text
*/
static decrypt = function ( ciphertext, password, nBits )
{
var blockSize = 16; // block size fixed at 16 bytes / 128 bits (Nb=4) for AES
if ( !( nBits == 128 || nBits == 192 || nBits == 256 ) ) return ''; // standard allows 128/192/256 bit keys
ciphertext = Base64.decode( ciphertext );
password = Utf8.encode( password );
//var t = new Date(); // timer
// use AES to encrypt password (mirroring encrypt routine)
var nBytes = nBits / 8; // no bytes in key
var pwBytes = new Array( nBytes );
for ( var i = 0; i < nBytes; i++ )
{
pwBytes[i] = isNaN( password.charCodeAt( i ) ) ? 0 : password.charCodeAt( i );
}
var key = Aes.cipher( pwBytes, Aes.keyExpansion( pwBytes ) );
key = key.concat( key.slice( 0, nBytes - 16 ) ); // expand key to 16/24/32 bytes long
// recover nonce from 1st 8 bytes of ciphertext
var counterBlock = new Array( 8 );
var ctrTxt = ciphertext.slice( 0, 8 );
for ( var i = 0; i < 8; i++ )
counterBlock[i] = ctrTxt.charCodeAt( i );
// generate key schedule
var keySchedule = Aes.keyExpansion( key );
// separate ciphertext into blocks (skipping past initial 8 bytes)
var nBlocks = Math.ceil( ( ciphertext.length - 8 ) / blockSize );
var ct = new Array( nBlocks );
for ( var b = 0; b < nBlocks; b++ )
ct[b] = ciphertext.slice( 8 + b * blockSize, 8 + b * blockSize + blockSize );
ciphertext = ct; // ciphertext is now array of block-length strings
// plaintext will get generated block-by-block into array of block-length strings
var plaintxt = new Array( ciphertext.length );
for ( var b = 0; b < nBlocks; b++ )
{
// set counter (block #) in last 8 bytes of counter block (leaving nonce in 1st 8 bytes)
for ( var c = 0; c < 4; c++ )
counterBlock[15 - c] = ( ( b ) >>> c * 8 ) & 0xff;
for ( var c = 0; c < 4; c++ )
counterBlock[15 - c - 4] = ( ( ( b + 1 ) / 0x100000000 - 1 ) >>> c * 8 ) & 0xff;
var cipherCntr = Aes.cipher( counterBlock, keySchedule ); // encrypt counter block
var plaintxtByte = new Array( ciphertext[b].length );
for ( var i = 0; i < ciphertext[b].length; i++ )
{
// -- xor plaintxt with ciphered counter byte-by-byte --
plaintxtByte[i] = cipherCntr[i] ^ ciphertext[b].charCodeAt( i );
plaintxtByte[i] = String.fromCharCode( plaintxtByte[i] );
}
plaintxt[b] = plaintxtByte.join( '' );
}
// join array of blocks into single plaintext string
var plaintext = plaintxt.join( '' );
plaintext = Utf8.decode( plaintext ); // decode from UTF8 back to Unicode multi-byte chars
//alert((new Date()) - t);
return plaintext;
}
}
}
class Utf8
{
/**
* Encode multi-byte Unicode string into utf-8 multiple single-byte characters
* (BMP / basic multilingual plane only)
*
* Chars in range U+0080 - U+07FF are encoded in 2 chars, U+0800 - U+FFFF in 3 chars
*
* @param {String} strUni Unicode string to be encoded as UTF-8
* @returns {String} encoded string
*/
static encode( strUni )
{
// use regular expressions & String.replace callback function for better efficiency
// than procedural approaches
var strUtf = strUni.replace(
/[\u0080-\u07ff]/g, // U+0080 - U+07FF => 2 bytes 110yyyyy, 10zzzzzz
function ( c )
{
var cc = c.charCodeAt( 0 );
return String.fromCharCode( 0xc0 | cc >> 6, 0x80 | cc & 0x3f );
}
);
strUtf = strUtf.replace(
/[\u0800-\uffff]/g, // U+0800 - U+FFFF => 3 bytes 1110xxxx, 10yyyyyy, 10zzzzzz
function ( c )
{
var cc = c.charCodeAt( 0 );
return String.fromCharCode( 0xe0 | cc >> 12, 0x80 | cc >> 6 & 0x3F, 0x80 | cc & 0x3f );
}
);
return strUtf;
}
/**
* Decode utf-8 encoded string back into multi-byte Unicode characters
*
* @param {String} strUtf UTF-8 string to be decoded back to Unicode
* @returns {String} decoded string
*/
static decode( strUtf )
{
// note: decode 3-byte chars first as decoded 2-byte strings could appear to be 3-byte char!
var strUni = strUtf.replace(
/[\u00e0-\u00ef][\u0080-\u00bf][\u0080-\u00bf]/g, // 3-byte chars
function ( c )
{ // (note parentheses for precence)
var cc = ( ( c.charCodeAt( 0 ) & 0x0f ) << 12 ) | ( ( c.charCodeAt( 1 ) & 0x3f ) << 6 ) | ( c.charCodeAt( 2 ) & 0x3f );
return String.fromCharCode( cc );
}
);
strUni = strUni.replace(
/[\u00c0-\u00df][\u0080-\u00bf]/g, // 2-byte chars
function ( c )
{ // (note parentheses for precence)
var cc = ( c.charCodeAt( 0 ) & 0x1f ) << 6 | c.charCodeAt( 1 ) & 0x3f;
return String.fromCharCode( cc );
}
);
return strUni;
}
/* - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */
/* Base64 class: Base 64 encoding / decoding (c) Chris Veness 2002-2011 */
/* http://www.movable-type.co.uk/scripts/base64.js */
/* note: depends on Utf8 class */
/* - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */
}
class Base64
{
static code = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";
/**
* Encode string into Base64, as defined by RFC 4648 [http://tools.ietf.org/html/rfc4648]
* (instance method extending String object). As per RFC 4648, no newlines are added.
*
* @param {String} str The string to be encoded as base-64
* @param {Boolean} [utf8encode=false] Flag to indicate whether str is Unicode string to be encoded
* to UTF8 before conversion to base64; otherwise string is assumed to be 8-bit characters
* @returns {String} Base64-encoded string
*/
static encode( str, utf8encode?)
{ // http://tools.ietf.org/html/rfc4648
utf8encode = ( typeof utf8encode == 'undefined' ) ? false : utf8encode;
var o1, o2, o3, bits, h1, h2, h3, h4, e = [], pad = '', c, plain, coded;
var b64 = Base64.code;
plain = utf8encode ? Utf8.encode( str ) : str;
c = plain.length % 3; // pad string to length of multiple of 3
if ( c > 0 )
{
while ( c++ < 3 )
{
pad += '='; plain += '\0';
}
}
// note: doing padding here saves us doing special-case packing for trailing 1 or 2 chars
for ( c = 0; c < plain.length; c += 3 )
{ // pack three octets into four hexets
o1 = plain.charCodeAt( c );
o2 = plain.charCodeAt( c + 1 );
o3 = plain.charCodeAt( c + 2 );
bits = o1 << 16 | o2 << 8 | o3;
h1 = bits >> 18 & 0x3f;
h2 = bits >> 12 & 0x3f;
h3 = bits >> 6 & 0x3f;
h4 = bits & 0x3f;
// use hextets to index into code string
e[c / 3] = b64.charAt( h1 ) + b64.charAt( h2 ) + b64.charAt( h3 ) + b64.charAt( h4 );
}
coded = e.join( '' ); // join() is far faster than repeated string concatenation in IE
// replace 'A's from padded nulls with '='s
coded = coded.slice( 0, coded.length - pad.length ) + pad;
return coded;
}
/**
* Decode string from Base64, as defined by RFC 4648 [http://tools.ietf.org/html/rfc4648]
* (instance method extending String object). As per RFC 4648, newlines are not catered for.
*
* @param {String} str The string to be decoded from base-64
* @param {Boolean} [utf8decode=false] Flag to indicate whether str is Unicode string to be decoded
* from UTF8 after conversion from base64
* @returns {String} decoded string
*/
static decode( str, utf8decode?)
{
utf8decode = ( typeof utf8decode == 'undefined' ) ? false : utf8decode;
var o1, o2, o3, h1, h2, h3, h4, bits, d = [], plain, coded;
var b64 = Base64.code;
coded = utf8decode ? Utf8.decode( str ) : str;
for ( var c = 0; c < coded.length; c += 4 )
{ // unpack four hexets into three octets
h1 = b64.indexOf( coded.charAt( c ) );
h2 = b64.indexOf( coded.charAt( c + 1 ) );
h3 = b64.indexOf( coded.charAt( c + 2 ) );
h4 = b64.indexOf( coded.charAt( c + 3 ) );
bits = h1 << 18 | h2 << 12 | h3 << 6 | h4;
o1 = bits >>> 16 & 0xff;
o2 = bits >>> 8 & 0xff;
o3 = bits & 0xff;
d[c / 4] = String.fromCharCode( o1, o2, o3 );
// check for padding
if ( h4 == 0x40 ) d[c / 4] = String.fromCharCode( o1, o2 );
if ( h3 == 0x40 ) d[c / 4] = String.fromCharCode( o1 );
}
plain = d.join( '' ); // join() is far faster than repeated string concatenation in IE
return utf8decode ? Utf8.decode( plain ) : plain;
}
}
/* - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */
/* AES Counter-mode implementation in JavaScript (c) Chris Veness 2005-2011 */
/* http://www.movable-type.co.uk/scripts/aes-ctr.js */
/* - see http://csrc.nist.gov/publications/nistpubs/800-38a/sp800-38a.pdf */
/* - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */
|
9ada6acc954a701a2ece52a2a58ac02cedcaac80 | 2,711 | tsx | TypeScript | src/util/index.tsx | rBurgett/poktlint.com | df4e6c973bbde258073ff96531492c99bfe5e036 | [
"MIT"
] | null | null | null | src/util/index.tsx | rBurgett/poktlint.com | df4e6c973bbde258073ff96531492c99bfe5e036 | [
"MIT"
] | 2 | 2022-03-25T19:25:26.000Z | 2022-03-25T19:46:02.000Z | src/util/index.tsx | decentralized-authority/poktlint.com | df4e6c973bbde258073ff96531492c99bfe5e036 | [
"MIT"
] | null | null | null | export const relayIdToName = (relayId: string): string => {
switch(relayId) {
case '0029':
return 'algorand-mainnet';
case '0003':
return 'avax-mainnet';
case '00A3':
return 'avax-archival';
case '0004':
return 'bsc-mainnet';
case '0010':
return 'bsc-archival';
case '0021':
return 'eth-mainnet';
case '0022':
return 'eth-archival';
case '0028':
return 'eth-archival-trace';
case '0026':
return 'eth-goerli';
case '0024':
return 'poa-kovan';
case '0025':
return 'eth-rinkeby';
case '0023':
return 'eth-ropsten';
case '0005':
return 'fuse-mainnet';
case '000A':
return 'fuse-archival';
case '0027':
return 'gnosischain-mainnet';
case '000C':
return 'gnosischain-archival';
case '0040':
return 'harmony-0';
case '0044':
return 'iotex-mainnet';
case '0047':
return 'oec-mainnet';
case '0001':
return 'pocket-mainnet';
case '0009':
return 'poly-mainnet';
case '000B':
return 'poly-archival';
case '0006':
return 'sol-mainnet';
default:
return 'unknown';
}
};
const regionDirectionToShortened = (region: string): string => {
switch(region) {
case 'north':
return 'n';
case 'south':
return 's';
case 'east':
return 'e';
case 'west':
return 'w';
case 'central':
return 'c';
case 'northeast':
return 'ne';
case 'southeast':
return 'se';
case 'northwest':
return 'nw';
case 'southwest':
return 'sw';
default:
return region;
}
};
export const regionToShortened = (region: string): string => {
try {
const splitRegion = region.split('-');
splitRegion[1] = regionDirectionToShortened(splitRegion[1]);
return splitRegion.join('-');
} catch(err) {
// ignore error
return region;
}
}
export const regionToName = (region: string): string => {
switch(region) {
case 'us-east-1':
return 'United States East 1';
case 'us-east-2':
return 'United States East 2';
case 'us-west-1':
return 'United States West 1';
case 'us-west-2':
return 'United States West 2';
case 'ap-east-1':
return 'Asia Pacific East 1';
case 'ap-northeast-1':
return 'Asia Pacific Northeast 1';
case 'ap-southeast-1':
return 'Asia Pacific Southeast 1';
case 'eu-central-1':
return 'Europe Central 1';
case 'eu-north-1':
return 'Europe North 1';
case 'eu-south-1':
return 'Europe South 1';
case 'eu-west-1':
return 'Europe West 1';
default:
return region;
}
}
| 22.974576 | 64 | 0.567318 | 113 | 4 | 0 | 4 | 5 | 0 | 1 | 0 | 8 | 0 | 0 | 26.25 | 860 | 0.009302 | 0.005814 | 0 | 0 | 0 | 0 | 0.615385 | 0.210338 | export const relayIdToName = (relayId) => {
switch(relayId) {
case '0029':
return 'algorand-mainnet';
case '0003':
return 'avax-mainnet';
case '00A3':
return 'avax-archival';
case '0004':
return 'bsc-mainnet';
case '0010':
return 'bsc-archival';
case '0021':
return 'eth-mainnet';
case '0022':
return 'eth-archival';
case '0028':
return 'eth-archival-trace';
case '0026':
return 'eth-goerli';
case '0024':
return 'poa-kovan';
case '0025':
return 'eth-rinkeby';
case '0023':
return 'eth-ropsten';
case '0005':
return 'fuse-mainnet';
case '000A':
return 'fuse-archival';
case '0027':
return 'gnosischain-mainnet';
case '000C':
return 'gnosischain-archival';
case '0040':
return 'harmony-0';
case '0044':
return 'iotex-mainnet';
case '0047':
return 'oec-mainnet';
case '0001':
return 'pocket-mainnet';
case '0009':
return 'poly-mainnet';
case '000B':
return 'poly-archival';
case '0006':
return 'sol-mainnet';
default:
return 'unknown';
}
};
/* Example usages of 'regionDirectionToShortened' are shown below:
splitRegion[1] = regionDirectionToShortened(splitRegion[1]);
*/
const regionDirectionToShortened = (region) => {
switch(region) {
case 'north':
return 'n';
case 'south':
return 's';
case 'east':
return 'e';
case 'west':
return 'w';
case 'central':
return 'c';
case 'northeast':
return 'ne';
case 'southeast':
return 'se';
case 'northwest':
return 'nw';
case 'southwest':
return 'sw';
default:
return region;
}
};
export const regionToShortened = (region) => {
try {
const splitRegion = region.split('-');
splitRegion[1] = regionDirectionToShortened(splitRegion[1]);
return splitRegion.join('-');
} catch(err) {
// ignore error
return region;
}
}
export const regionToName = (region) => {
switch(region) {
case 'us-east-1':
return 'United States East 1';
case 'us-east-2':
return 'United States East 2';
case 'us-west-1':
return 'United States West 1';
case 'us-west-2':
return 'United States West 2';
case 'ap-east-1':
return 'Asia Pacific East 1';
case 'ap-northeast-1':
return 'Asia Pacific Northeast 1';
case 'ap-southeast-1':
return 'Asia Pacific Southeast 1';
case 'eu-central-1':
return 'Europe Central 1';
case 'eu-north-1':
return 'Europe North 1';
case 'eu-south-1':
return 'Europe South 1';
case 'eu-west-1':
return 'Europe West 1';
default:
return region;
}
}
|
9ae0d8a6893a908199e9b2369297fd233ae64973 | 2,190 | ts | TypeScript | problemset/mini-parser/index.ts | OUDUIDUI/leet-code | 50e61ce16d1c419ccefc075ae9ead721cdd1cdbb | [
"MIT"
] | 6 | 2022-01-17T03:19:56.000Z | 2022-01-17T05:45:39.000Z | problemset/mini-parser/index.ts | OUDUIDUI/leet-code | 50e61ce16d1c419ccefc075ae9ead721cdd1cdbb | [
"MIT"
] | null | null | null | problemset/mini-parser/index.ts | OUDUIDUI/leet-code | 50e61ce16d1c419ccefc075ae9ead721cdd1cdbb | [
"MIT"
] | null | null | null | export class NestedInteger {
list: NestedInteger[] = []
constructor(public value?: number) {}
isInteger(): boolean {
return this.value !== undefined
}
getInteger(): number | null {
return this.isInteger() ? this.value! : null
}
setInteger(value: number) {
this.value = value
}
add(elem: NestedInteger) {
this.list.push(elem)
}
getList(): NestedInteger[] {
return this.list
}
}
/**
* 深度优先搜索
* @desc 时间复杂度 O(N) 空间复杂度 O(N)
* @param s
* @returns
*/
export function deserialize(s: string): NestedInteger {
let i = 0
return dfs(s)
function dfs(s: string) {
if (s[i] === '[') {
i++
const ni = new NestedInteger()
while (s[i] !== ']') {
ni.add(dfs(s))
if (s[i] === ',') i++
}
i++
return ni
}
else {
let negative = false
if (s[i] === '-') {
negative = true
i++
}
let num = 0
while (i < s.length && isDigit(s[i])) {
num = num * 10 + s[i].charCodeAt(0) - '0'.charCodeAt(0)
i++
}
if (negative)
num = -num
return new NestedInteger(num)
}
}
function isDigit(ch: string): boolean {
return !isNaN(Number(ch))
}
}
/**
* 栈
* @desc 时间复杂度 O(N) 空间复杂度 O(N)
* @param s
* @returns
*/
export function deserialize2(s: string): NestedInteger {
if (s[0] !== '[') return new NestedInteger(Number(s))
const isDigit = (ch: string): boolean => !isNaN(Number(ch))
const stack: NestedInteger[] = []
let num = 0
let negative = false
for (let i = 0; i < s.length; i++) {
const ch = s[i]
if (ch === '-') {
negative = true
}
else if (isDigit(ch)) {
num = num * 10 + ch.charCodeAt(0) - '0'.charCodeAt(0)
}
else if (ch === '[') {
stack.push(new NestedInteger())
}
else if (ch === ',' || ch === ']') {
if (isDigit(s[i - 1])) {
if (negative) num = -num
stack[stack.length - 1].add(new NestedInteger(num))
}
num = 0
negative = false
if (ch === ']' && stack.length > 1) {
const ni = stack.pop()!
stack[stack.length - 1].add(ni)
}
}
}
return stack.pop()!
}
| 19.909091 | 63 | 0.506849 | 85 | 11 | 0 | 8 | 11 | 1 | 4 | 0 | 11 | 1 | 0 | 8.545455 | 708 | 0.026836 | 0.015537 | 0.001412 | 0.001412 | 0 | 0 | 0.354839 | 0.286456 | export class NestedInteger {
list = []
constructor(public value?) {}
isInteger() {
return this.value !== undefined
}
getInteger() {
return this.isInteger() ? this.value! : null
}
setInteger(value) {
this.value = value
}
add(elem) {
this.list.push(elem)
}
getList() {
return this.list
}
}
/**
* 深度优先搜索
* @desc 时间复杂度 O(N) 空间复杂度 O(N)
* @param s
* @returns
*/
export function deserialize(s) {
let i = 0
return dfs(s)
/* Example usages of 'dfs' are shown below:
dfs(s);
ni.add(dfs(s));
*/
function dfs(s) {
if (s[i] === '[') {
i++
const ni = new NestedInteger()
while (s[i] !== ']') {
ni.add(dfs(s))
if (s[i] === ',') i++
}
i++
return ni
}
else {
let negative = false
if (s[i] === '-') {
negative = true
i++
}
let num = 0
while (i < s.length && isDigit(s[i])) {
num = num * 10 + s[i].charCodeAt(0) - '0'.charCodeAt(0)
i++
}
if (negative)
num = -num
return new NestedInteger(num)
}
}
/* Example usages of 'isDigit' are shown below:
i < s.length && isDigit(s[i]);
isDigit(ch);
isDigit(s[i - 1]);
*/
function isDigit(ch) {
return !isNaN(Number(ch))
}
}
/**
* 栈
* @desc 时间复杂度 O(N) 空间复杂度 O(N)
* @param s
* @returns
*/
export function deserialize2(s) {
if (s[0] !== '[') return new NestedInteger(Number(s))
/* Example usages of 'isDigit' are shown below:
i < s.length && isDigit(s[i]);
isDigit(ch);
isDigit(s[i - 1]);
*/
const isDigit = (ch) => !isNaN(Number(ch))
const stack = []
let num = 0
let negative = false
for (let i = 0; i < s.length; i++) {
const ch = s[i]
if (ch === '-') {
negative = true
}
else if (isDigit(ch)) {
num = num * 10 + ch.charCodeAt(0) - '0'.charCodeAt(0)
}
else if (ch === '[') {
stack.push(new NestedInteger())
}
else if (ch === ',' || ch === ']') {
if (isDigit(s[i - 1])) {
if (negative) num = -num
stack[stack.length - 1].add(new NestedInteger(num))
}
num = 0
negative = false
if (ch === ']' && stack.length > 1) {
const ni = stack.pop()!
stack[stack.length - 1].add(ni)
}
}
}
return stack.pop()!
}
|
f239eadf444e4af3e91bed7eb153ee144d34ba78 | 3,040 | ts | TypeScript | day-23.ts | dubzzz/advent-of-pbt-2021 | 7b324588cc582bea60155cc922778f39d503a818 | [
"MIT"
] | 2 | 2022-03-14T00:03:38.000Z | 2022-03-14T11:51:27.000Z | day-23.ts | dubzzz/advent-of-pbt-2021 | 7b324588cc582bea60155cc922778f39d503a818 | [
"MIT"
] | null | null | null | day-23.ts | dubzzz/advent-of-pbt-2021 | 7b324588cc582bea60155cc922778f39d503a818 | [
"MIT"
] | null | null | null | /**
* Each year, Santa receives wish lists coming from everywhere.
*
* Lists are ordered starting by the most important present to the last
* important one. Santa does not always offer the most important one.
* From time to time he wants to wait one more year to check if the
* present stays in the top.
*
* Each year, Santa manually performs a diff of the list with
* the one of the year before. Based on this diff he makes his choice.
*
* You can see the diff manually computed by Santa as an usual git diff
* between two strings including many lines.
*
* Let's take the example:
*
* Year N:
* Cars
* Trains
* Planes
*
* Year N+1:
* Cars
* Buses
* Trains
* Boats
*
* Diff of Santa:
* === Cars
* +++ Buses
* === Trains
* +++ Boats
* --- Planes
*
* @param before - String representing the list of presents (before)
* @param after - String representing the list of presents (after)
*/
export function wishListsDiffer(before: string, after: string): string {
const beforeLines = before.split("\n");
const afterLines = after.split("\n");
const sharedLines = longestCommonSubarray(beforeLines, afterLines, 0, 0, []);
const diffLines: string[] = [];
let indexBefore = 0;
let indexAfter = 0;
for (const sharedLine of sharedLines) {
for (; afterLines[indexAfter] !== sharedLine; ++indexAfter) {
diffLines.push("+++ " + afterLines[indexAfter]);
}
for (; beforeLines[indexBefore] !== sharedLine; ++indexBefore) {
diffLines.push("--- " + beforeLines[indexBefore]);
}
++indexBefore;
++indexAfter;
diffLines.push("=== " + sharedLine);
}
for (; indexAfter !== afterLines.length; ++indexAfter) {
diffLines.push("+++ " + afterLines[indexAfter]);
}
for (; indexBefore !== beforeLines.length; ++indexBefore) {
diffLines.push("--- " + beforeLines[indexBefore]);
}
return diffLines.join("\n");
}
function longestCommonSubarray(
dataA: string[],
dataB: string[],
startA: number,
startB: number,
sharedCache: string[][][]
): string[] {
if (dataA.length <= startA || dataB.length <= startB) {
return [];
}
if (startA in sharedCache) {
if (startB in sharedCache[startA]) {
return sharedCache[startA][startB];
}
} else {
sharedCache[startA] = [];
}
const optionSkippingStartA = longestCommonSubarray(
dataA,
dataB,
startA + 1,
startB,
sharedCache
);
const indexStartAInB = dataB.indexOf(dataA[startA], startB);
if (indexStartAInB === -1) {
sharedCache[startA][startB] = optionSkippingStartA;
return optionSkippingStartA;
}
const optionIncludingStartA = [
dataA[startA],
...longestCommonSubarray(
dataA,
dataB,
startA + 1,
indexStartAInB + 1,
sharedCache
),
];
const bestOption =
optionSkippingStartA.length < optionIncludingStartA.length
? optionIncludingStartA
: optionSkippingStartA;
sharedCache[startA][startB] = bestOption;
return bestOption;
}
| 26.902655 | 79 | 0.64375 | 72 | 2 | 0 | 7 | 10 | 0 | 1 | 0 | 10 | 0 | 0 | 31 | 871 | 0.010333 | 0.011481 | 0 | 0 | 0 | 0 | 0.526316 | 0.231408 | /**
* Each year, Santa receives wish lists coming from everywhere.
*
* Lists are ordered starting by the most important present to the last
* important one. Santa does not always offer the most important one.
* From time to time he wants to wait one more year to check if the
* present stays in the top.
*
* Each year, Santa manually performs a diff of the list with
* the one of the year before. Based on this diff he makes his choice.
*
* You can see the diff manually computed by Santa as an usual git diff
* between two strings including many lines.
*
* Let's take the example:
*
* Year N:
* Cars
* Trains
* Planes
*
* Year N+1:
* Cars
* Buses
* Trains
* Boats
*
* Diff of Santa:
* === Cars
* +++ Buses
* === Trains
* +++ Boats
* --- Planes
*
* @param before - String representing the list of presents (before)
* @param after - String representing the list of presents (after)
*/
export function wishListsDiffer(before, after) {
const beforeLines = before.split("\n");
const afterLines = after.split("\n");
const sharedLines = longestCommonSubarray(beforeLines, afterLines, 0, 0, []);
const diffLines = [];
let indexBefore = 0;
let indexAfter = 0;
for (const sharedLine of sharedLines) {
for (; afterLines[indexAfter] !== sharedLine; ++indexAfter) {
diffLines.push("+++ " + afterLines[indexAfter]);
}
for (; beforeLines[indexBefore] !== sharedLine; ++indexBefore) {
diffLines.push("--- " + beforeLines[indexBefore]);
}
++indexBefore;
++indexAfter;
diffLines.push("=== " + sharedLine);
}
for (; indexAfter !== afterLines.length; ++indexAfter) {
diffLines.push("+++ " + afterLines[indexAfter]);
}
for (; indexBefore !== beforeLines.length; ++indexBefore) {
diffLines.push("--- " + beforeLines[indexBefore]);
}
return diffLines.join("\n");
}
/* Example usages of 'longestCommonSubarray' are shown below:
longestCommonSubarray(beforeLines, afterLines, 0, 0, []);
longestCommonSubarray(dataA, dataB, startA + 1, startB, sharedCache);
longestCommonSubarray(dataA, dataB, startA + 1, indexStartAInB + 1, sharedCache);
*/
function longestCommonSubarray(
dataA,
dataB,
startA,
startB,
sharedCache
) {
if (dataA.length <= startA || dataB.length <= startB) {
return [];
}
if (startA in sharedCache) {
if (startB in sharedCache[startA]) {
return sharedCache[startA][startB];
}
} else {
sharedCache[startA] = [];
}
const optionSkippingStartA = longestCommonSubarray(
dataA,
dataB,
startA + 1,
startB,
sharedCache
);
const indexStartAInB = dataB.indexOf(dataA[startA], startB);
if (indexStartAInB === -1) {
sharedCache[startA][startB] = optionSkippingStartA;
return optionSkippingStartA;
}
const optionIncludingStartA = [
dataA[startA],
...longestCommonSubarray(
dataA,
dataB,
startA + 1,
indexStartAInB + 1,
sharedCache
),
];
const bestOption =
optionSkippingStartA.length < optionIncludingStartA.length
? optionIncludingStartA
: optionSkippingStartA;
sharedCache[startA][startB] = bestOption;
return bestOption;
}
|
f2d62565325ed7fda8208aaa71f5b4b0ffe7f4e8 | 3,114 | ts | TypeScript | src/shared/general.ts | u007/vite-ssg-ant | 271d08f40d08f586dc2d4827e377183001762a19 | [
"MIT"
] | null | null | null | src/shared/general.ts | u007/vite-ssg-ant | 271d08f40d08f586dc2d4827e377183001762a19 | [
"MIT"
] | null | null | null | src/shared/general.ts | u007/vite-ssg-ant | 271d08f40d08f586dc2d4827e377183001762a19 | [
"MIT"
] | 1 | 2022-01-08T14:22:48.000Z | 2022-01-08T14:22:48.000Z |
export const pagination = {
limit: 10,
}
export const cacheDuration = 60 * 10 // 10minutes
// data has to be object or array
export const parseFormForServer = (data: any) => {
let res: any = {}
for (let key in data) {
if (key === '__ob__') {
continue
}
let value = data[key]
// console.log('parseFormForServer', key, value)
if (
value !== undefined &&
value != null &&
typeof value === 'object' &&
!Array.isArray(value) &&
!value._d
) {
// console.log('clone object', key)
res[key] = parseFormForServer(value)
} else if (value !== undefined && value !== null && value._d) {
if (value.isValid()) {
res[key] = value.toDate()
} else {
res[key] = null
}
} else if (Array.isArray(value)) {
// when clone array, map does not include private or observers
// console.log('clone array', key, value)
res[key] = value.map((v, i) => {
// console.log('array ', v, i)
if (typeof v === 'object') {
return parseFormForServer(v)
}
return v
// console.log('arr value', newval)
})
} else if (typeof value === 'function') {
// ignore
} else {
// console.log('normalclone', i, Array.isArray(val), val)
res[key] = value
}
}
return res
}
export const valueOrClone = (i: string | number, value: any) => {
if (
value != null &&
typeof value === 'object' &&
!Array.isArray(value) &&
!value._d
) {
// console.log('clone object', i, val)
return cloneData(value)
} else if (Array.isArray(value)) {
// when clone array, map does not include private or observers
return value.map((v, i) => {
return valueOrClone(i, v)
})
} else if (typeof value === 'function') {
// ignore
return undefined
} else {
// console.log('normalclone', i, Array.isArray(val), val)
return value
}
}
export const formats = {
date: 'dd MMM yyyy',
dateTime: 'dd MMM yyyy HH:mm:ss',
}
export const makeRandomAplhaNumeric = (length: number) => {
let text = ''
let possible =
'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789'
for (let i = 0; i < length; i++) {
text += possible.charAt(Math.floor(Math.random() * possible.length))
}
return text
}
export const makeID = (length: number) => {
return makeRandomAplhaNumeric(length)
}
// not case sensitive and does not contain similar looking charactor like O vs 0
export const makeFriendlyRandomCaseInsentitiveAplhaNumeric = (
length: number
) => {
let text = ''
let possible = 'ABCDEFGHIJKLMNPQRSTUVWXYZ123456789'
for (let i = 0; i < length; i++) {
text += possible.charAt(Math.floor(Math.random() * possible.length))
}
return text
}
export const region = 'asia-northeast1'
export const cloneData = (obj) => {
let clone: any = {}
for (let i in obj) {
// if (typeof obj[i] !== 'function') {
// console.log('clone', i, obj[i], typeof obj[i])
// }
if (obj[i] !== null) {
clone[i] = valueOrClone(i, obj[i])
}
}
return clone
}
| 24.912 | 80 | 0.584136 | 93 | 8 | 0 | 11 | 19 | 0 | 4 | 4 | 5 | 0 | 5 | 9.375 | 921 | 0.02063 | 0.02063 | 0 | 0 | 0.005429 | 0.105263 | 0.131579 | 0.284089 |
export const pagination = {
limit: 10,
}
export const cacheDuration = 60 * 10 // 10minutes
// data has to be object or array
export /* Example usages of 'parseFormForServer' are shown below:
// console.log('clone object', key)
res[key] = parseFormForServer(value);
parseFormForServer(v);
*/
const parseFormForServer = (data) => {
let res = {}
for (let key in data) {
if (key === '__ob__') {
continue
}
let value = data[key]
// console.log('parseFormForServer', key, value)
if (
value !== undefined &&
value != null &&
typeof value === 'object' &&
!Array.isArray(value) &&
!value._d
) {
// console.log('clone object', key)
res[key] = parseFormForServer(value)
} else if (value !== undefined && value !== null && value._d) {
if (value.isValid()) {
res[key] = value.toDate()
} else {
res[key] = null
}
} else if (Array.isArray(value)) {
// when clone array, map does not include private or observers
// console.log('clone array', key, value)
res[key] = value.map((v, i) => {
// console.log('array ', v, i)
if (typeof v === 'object') {
return parseFormForServer(v)
}
return v
// console.log('arr value', newval)
})
} else if (typeof value === 'function') {
// ignore
} else {
// console.log('normalclone', i, Array.isArray(val), val)
res[key] = value
}
}
return res
}
export /* Example usages of 'valueOrClone' are shown below:
valueOrClone(i, v);
clone[i] = valueOrClone(i, obj[i]);
*/
const valueOrClone = (i, value) => {
if (
value != null &&
typeof value === 'object' &&
!Array.isArray(value) &&
!value._d
) {
// console.log('clone object', i, val)
return cloneData(value)
} else if (Array.isArray(value)) {
// when clone array, map does not include private or observers
return value.map((v, i) => {
return valueOrClone(i, v)
})
} else if (typeof value === 'function') {
// ignore
return undefined
} else {
// console.log('normalclone', i, Array.isArray(val), val)
return value
}
}
export const formats = {
date: 'dd MMM yyyy',
dateTime: 'dd MMM yyyy HH:mm:ss',
}
export /* Example usages of 'makeRandomAplhaNumeric' are shown below:
makeRandomAplhaNumeric(length);
*/
const makeRandomAplhaNumeric = (length) => {
let text = ''
let possible =
'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789'
for (let i = 0; i < length; i++) {
text += possible.charAt(Math.floor(Math.random() * possible.length))
}
return text
}
export const makeID = (length) => {
return makeRandomAplhaNumeric(length)
}
// not case sensitive and does not contain similar looking charactor like O vs 0
export const makeFriendlyRandomCaseInsentitiveAplhaNumeric = (
length
) => {
let text = ''
let possible = 'ABCDEFGHIJKLMNPQRSTUVWXYZ123456789'
for (let i = 0; i < length; i++) {
text += possible.charAt(Math.floor(Math.random() * possible.length))
}
return text
}
export const region = 'asia-northeast1'
export /* Example usages of 'cloneData' are shown below:
cloneData(value);
*/
const cloneData = (obj) => {
let clone = {}
for (let i in obj) {
// if (typeof obj[i] !== 'function') {
// console.log('clone', i, obj[i], typeof obj[i])
// }
if (obj[i] !== null) {
clone[i] = valueOrClone(i, obj[i])
}
}
return clone
}
|
f2f61b40b240c398abf6f8f23862d7db05a4ccde | 2,589 | ts | TypeScript | src/authorization/lib/Utils.ts | api-client/core | aa157d09b39efa77d49f2d425e7b37828abe0c5b | [
"Apache-2.0"
] | null | null | null | src/authorization/lib/Utils.ts | api-client/core | aa157d09b39efa77d49f2d425e7b37828abe0c5b | [
"Apache-2.0"
] | 1 | 2022-02-14T00:01:04.000Z | 2022-02-14T00:04:07.000Z | src/authorization/lib/Utils.ts | advanced-rest-client/core | 2efb946f786d8b46e7131c62e0011f6e090ddec3 | [
"Apache-2.0"
] | null | null | null | /**
* Normalizes type name to a string identifier.
* It casts input to a string and lowercase it.
* @param type Type value
* @return Normalized value.
*/
export const normalizeType = (type?: string): string => String(type).toLowerCase();
export const METHOD_BASIC = "basic";
export const METHOD_BEARER = "bearer";
export const METHOD_NTLM = "ntlm";
export const METHOD_DIGEST = "digest";
export const METHOD_OAUTH2 = "oauth 2";
export const METHOD_OIDC = "open id";
export const METHOD_CC = 'client certificate';
export const CUSTOM_CREDENTIALS = "Custom credentials";
/**
* @param value The value to validate
* @returns True if the redirect URI can be considered valid.
*/
export function validateRedirectUri(value: unknown): boolean {
let result = true;
if (!value || typeof value !== 'string') {
result = false;
}
// the redirect URI can have any value, especially for installed apps which
// may use custom schemes. We do very basic sanity check for any script content
// validation to make sure we are not passing any script.
if (result) {
const u = String(value).toLowerCase();
if (u.startsWith("javascript:") || u.startsWith("data:") || u.startsWith("vbscript:")) {
result = false;
}
}
return result;
}
/**
* Generates client nonce for Digest authorization.
*
* @return Generated client nonce.
*/
export function generateCnonce(): string {
const characters = 'abcdef0123456789';
let token = '';
for (let i = 0; i < 16; i++) {
const randNum = Math.round(Math.random() * characters.length);
token += characters.substring(randNum, 1);
}
return token;
}
/**
* Generates `state` parameter for the OAuth2 call.
*
* @return Generated state string.
*/
export function generateState(): string {
let text = '';
const possible = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789';
for (let i = 0; i < 6; i++) {
text += possible.charAt(Math.floor(Math.random() * possible.length));
}
return text;
}
/**
* When defined and the `url` is a relative path staring with `/` then it
* adds base URI to the path and returns concatenated value.
*
* @param url The URL to process
* @param baseUri Base URI to use.
* @returns Final URL value.
*/
export function readUrlValue(url?: string, baseUri?: string): string {
if (!url) {
return '';
}
const result = String(url);
if (!baseUri) {
return result;
}
if (result[0] === '/') {
let uri = baseUri;
if (uri[uri.length - 1] === '/') {
uri = uri.substring(0, uri.length - 1);
}
return `${uri}${result}`;
}
return result;
}
| 27.83871 | 92 | 0.662418 | 56 | 5 | 0 | 4 | 20 | 0 | 0 | 0 | 9 | 0 | 1 | 8 | 720 | 0.0125 | 0.027778 | 0 | 0 | 0.001389 | 0 | 0.310345 | 0.289443 | /**
* Normalizes type name to a string identifier.
* It casts input to a string and lowercase it.
* @param type Type value
* @return Normalized value.
*/
export const normalizeType = (type?) => String(type).toLowerCase();
export const METHOD_BASIC = "basic";
export const METHOD_BEARER = "bearer";
export const METHOD_NTLM = "ntlm";
export const METHOD_DIGEST = "digest";
export const METHOD_OAUTH2 = "oauth 2";
export const METHOD_OIDC = "open id";
export const METHOD_CC = 'client certificate';
export const CUSTOM_CREDENTIALS = "Custom credentials";
/**
* @param value The value to validate
* @returns True if the redirect URI can be considered valid.
*/
export function validateRedirectUri(value) {
let result = true;
if (!value || typeof value !== 'string') {
result = false;
}
// the redirect URI can have any value, especially for installed apps which
// may use custom schemes. We do very basic sanity check for any script content
// validation to make sure we are not passing any script.
if (result) {
const u = String(value).toLowerCase();
if (u.startsWith("javascript:") || u.startsWith("data:") || u.startsWith("vbscript:")) {
result = false;
}
}
return result;
}
/**
* Generates client nonce for Digest authorization.
*
* @return Generated client nonce.
*/
export function generateCnonce() {
const characters = 'abcdef0123456789';
let token = '';
for (let i = 0; i < 16; i++) {
const randNum = Math.round(Math.random() * characters.length);
token += characters.substring(randNum, 1);
}
return token;
}
/**
* Generates `state` parameter for the OAuth2 call.
*
* @return Generated state string.
*/
export function generateState() {
let text = '';
const possible = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789';
for (let i = 0; i < 6; i++) {
text += possible.charAt(Math.floor(Math.random() * possible.length));
}
return text;
}
/**
* When defined and the `url` is a relative path staring with `/` then it
* adds base URI to the path and returns concatenated value.
*
* @param url The URL to process
* @param baseUri Base URI to use.
* @returns Final URL value.
*/
export function readUrlValue(url?, baseUri?) {
if (!url) {
return '';
}
const result = String(url);
if (!baseUri) {
return result;
}
if (result[0] === '/') {
let uri = baseUri;
if (uri[uri.length - 1] === '/') {
uri = uri.substring(0, uri.length - 1);
}
return `${uri}${result}`;
}
return result;
}
|
605858e60bc493837d811926d2e93af92a0ec0eb | 4,354 | ts | TypeScript | src/utils/dateTime.ts | ben-garcia/stack-client | 5d8d24163106b5e3dbb0e25969c8dc726b576fb7 | [
"MIT"
] | null | null | null | src/utils/dateTime.ts | ben-garcia/stack-client | 5d8d24163106b5e3dbb0e25969c8dc726b576fb7 | [
"MIT"
] | 1 | 2022-02-26T20:53:24.000Z | 2022-02-26T20:53:24.000Z | src/utils/dateTime.ts | ben-garcia/stack-client | 5d8d24163106b5e3dbb0e25969c8dc726b576fb7 | [
"MIT"
] | null | null | null | // helper functions to format ISO string to local time and day
const getDay = (day: number): string => {
switch (day + 1) {
case 1:
return 'Sunday';
case 2:
return 'Monday';
case 3:
return 'Tuesday';
case 4:
return 'Wednesday';
case 5:
return 'Thursday';
case 6:
return 'Friday';
default:
return 'Saturday';
}
};
const getDate = (date: number): string => {
switch (date) {
case 1:
return `${date}st`;
case 2:
return `${date}nd`;
case 3:
return `${date}rd`;
default:
return `${date}th`;
}
};
const getMonth = (month: number): string => {
switch (month + 1) {
case 1:
return 'January';
case 2:
return 'February';
case 3:
return 'March';
case 4:
return 'April';
case 5:
return 'May';
case 6:
return 'June';
case 7:
return 'July';
case 8:
return 'August';
case 9:
return 'September';
case 10:
return 'October';
case 11:
return 'November';
default:
return 'December';
}
};
const setupMap = (date: string): Map<number, number> => {
const monthMaxDays = new Map<number, number>();
monthMaxDays.set(1, 31);
// check for leap year
if (Number(date.split('/')[2]) / 4 === 0) {
monthMaxDays.set(2, 29);
} else {
monthMaxDays.set(2, 28);
}
monthMaxDays.set(3, 31);
monthMaxDays.set(4, 30);
monthMaxDays.set(5, 31);
monthMaxDays.set(6, 30);
monthMaxDays.set(7, 31);
monthMaxDays.set(8, 31);
monthMaxDays.set(9, 30);
monthMaxDays.set(10, 31);
monthMaxDays.set(11, 30);
monthMaxDays.set(12, 31);
return monthMaxDays;
};
const isMessageFromYesterday = (
today: string,
dateInQuestion: string
): boolean => {
const monthMaxDays = setupMap(today);
const month = Number(dateInQuestion.split('/')[0]);
const date = Number(dateInQuestion.split('/')[1]);
const year = Number(dateInQuestion.split('/')[2]);
const todayMonth = Number(today.split('/')[0]);
const todayDate = Number(today.split('/')[1]);
const todayYear = Number(today.split('/')[2]);
let dateToCompare;
let todayToCompare;
// check that it isn't the 1st of the month
if (date === 1) {
todayToCompare = `${todayMonth}/${todayDate - 1}/${todayYear}`;
if (todayToCompare === dateInQuestion) {
return true;
}
// check that month isn't January and date is 1
} else if (date === 1 && month !== 1) {
const newDate = monthMaxDays.get(month - 1);
dateToCompare = `${month - 1}/${newDate}/${year}`;
todayToCompare = `${todayMonth}/${todayDate - 1}/${todayYear}`;
if (dateToCompare === todayToCompare) {
return true;
}
} else {
dateToCompare = `${month}/${date}/${year}`;
todayToCompare = `${todayMonth}/${todayDate - 1}/${todayYear}`;
if (dateToCompare === todayToCompare) {
return true;
}
}
return false;
};
const getCurrentYear = (): number => new Date().getFullYear();
export const printFormattedDate = (ISOString: string): string => {
const dateToFormat = new Date(ISOString);
// if the current year is equal to the ISOString year
// then format string like so: month date, year
if (getCurrentYear() === dateToFormat.getFullYear()) {
const todaysDate = new Date().toLocaleDateString();
const dateInQuestion = dateToFormat.toLocaleDateString();
// for those messages that were created in the current day month and year
if (todaysDate === dateInQuestion) {
return 'Today';
}
if (isMessageFromYesterday(todaysDate, dateInQuestion)) {
// messages created 1 day before
return 'Yesterday';
}
// otherwise: day, month date
return `${getDay(dateToFormat.getDay())}, ${getMonth(
dateToFormat.getMonth()
)} ${getDate(dateToFormat.getDate())}`;
}
// format ISOString like so: month date, year
return `${getMonth(dateToFormat.getMonth())} ${getDate(
dateToFormat.getDate()
)}, ${dateToFormat.getFullYear()}`;
};
export const getTime = (ISOString: string, amOrPm: boolean = true): string => {
const date = new Date(ISOString).toLocaleTimeString().split(':');
const hour = date[0];
const minutes = date[1];
const pmOrAm = date[2].split(' ')[1];
if (amOrPm) {
return `${hour}:${minutes} ${pmOrAm}`;
}
return `${hour}:${minutes}`;
};
| 26.54878 | 79 | 0.608865 | 142 | 8 | 0 | 9 | 26 | 0 | 6 | 0 | 20 | 0 | 0 | 15.625 | 1,289 | 0.013189 | 0.020171 | 0 | 0 | 0 | 0 | 0.465116 | 0.267776 | // helper functions to format ISO string to local time and day
/* Example usages of 'getDay' are shown below:
getDay(dateToFormat.getDay());
*/
const getDay = (day) => {
switch (day + 1) {
case 1:
return 'Sunday';
case 2:
return 'Monday';
case 3:
return 'Tuesday';
case 4:
return 'Wednesday';
case 5:
return 'Thursday';
case 6:
return 'Friday';
default:
return 'Saturday';
}
};
/* Example usages of 'getDate' are shown below:
getDate(dateToFormat.getDate());
*/
const getDate = (date) => {
switch (date) {
case 1:
return `${date}st`;
case 2:
return `${date}nd`;
case 3:
return `${date}rd`;
default:
return `${date}th`;
}
};
/* Example usages of 'getMonth' are shown below:
getMonth(dateToFormat.getMonth());
*/
const getMonth = (month) => {
switch (month + 1) {
case 1:
return 'January';
case 2:
return 'February';
case 3:
return 'March';
case 4:
return 'April';
case 5:
return 'May';
case 6:
return 'June';
case 7:
return 'July';
case 8:
return 'August';
case 9:
return 'September';
case 10:
return 'October';
case 11:
return 'November';
default:
return 'December';
}
};
/* Example usages of 'setupMap' are shown below:
setupMap(today);
*/
const setupMap = (date) => {
const monthMaxDays = new Map<number, number>();
monthMaxDays.set(1, 31);
// check for leap year
if (Number(date.split('/')[2]) / 4 === 0) {
monthMaxDays.set(2, 29);
} else {
monthMaxDays.set(2, 28);
}
monthMaxDays.set(3, 31);
monthMaxDays.set(4, 30);
monthMaxDays.set(5, 31);
monthMaxDays.set(6, 30);
monthMaxDays.set(7, 31);
monthMaxDays.set(8, 31);
monthMaxDays.set(9, 30);
monthMaxDays.set(10, 31);
monthMaxDays.set(11, 30);
monthMaxDays.set(12, 31);
return monthMaxDays;
};
/* Example usages of 'isMessageFromYesterday' are shown below:
isMessageFromYesterday(todaysDate, dateInQuestion);
*/
const isMessageFromYesterday = (
today,
dateInQuestion
) => {
const monthMaxDays = setupMap(today);
const month = Number(dateInQuestion.split('/')[0]);
const date = Number(dateInQuestion.split('/')[1]);
const year = Number(dateInQuestion.split('/')[2]);
const todayMonth = Number(today.split('/')[0]);
const todayDate = Number(today.split('/')[1]);
const todayYear = Number(today.split('/')[2]);
let dateToCompare;
let todayToCompare;
// check that it isn't the 1st of the month
if (date === 1) {
todayToCompare = `${todayMonth}/${todayDate - 1}/${todayYear}`;
if (todayToCompare === dateInQuestion) {
return true;
}
// check that month isn't January and date is 1
} else if (date === 1 && month !== 1) {
const newDate = monthMaxDays.get(month - 1);
dateToCompare = `${month - 1}/${newDate}/${year}`;
todayToCompare = `${todayMonth}/${todayDate - 1}/${todayYear}`;
if (dateToCompare === todayToCompare) {
return true;
}
} else {
dateToCompare = `${month}/${date}/${year}`;
todayToCompare = `${todayMonth}/${todayDate - 1}/${todayYear}`;
if (dateToCompare === todayToCompare) {
return true;
}
}
return false;
};
/* Example usages of 'getCurrentYear' are shown below:
getCurrentYear() === dateToFormat.getFullYear();
*/
const getCurrentYear = () => new Date().getFullYear();
export const printFormattedDate = (ISOString) => {
const dateToFormat = new Date(ISOString);
// if the current year is equal to the ISOString year
// then format string like so: month date, year
if (getCurrentYear() === dateToFormat.getFullYear()) {
const todaysDate = new Date().toLocaleDateString();
const dateInQuestion = dateToFormat.toLocaleDateString();
// for those messages that were created in the current day month and year
if (todaysDate === dateInQuestion) {
return 'Today';
}
if (isMessageFromYesterday(todaysDate, dateInQuestion)) {
// messages created 1 day before
return 'Yesterday';
}
// otherwise: day, month date
return `${getDay(dateToFormat.getDay())}, ${getMonth(
dateToFormat.getMonth()
)} ${getDate(dateToFormat.getDate())}`;
}
// format ISOString like so: month date, year
return `${getMonth(dateToFormat.getMonth())} ${getDate(
dateToFormat.getDate()
)}, ${dateToFormat.getFullYear()}`;
};
export const getTime = (ISOString, amOrPm = true) => {
const date = new Date(ISOString).toLocaleTimeString().split(':');
const hour = date[0];
const minutes = date[1];
const pmOrAm = date[2].split(' ')[1];
if (amOrPm) {
return `${hour}:${minutes} ${pmOrAm}`;
}
return `${hour}:${minutes}`;
};
|
6098211daafdab1fe8de0c09c0ecd62b337844c8 | 10,563 | ts | TypeScript | lib/index.ts | princess-rosella/spu-md5 | ddfae1ee439a5e7238e23a5f2c66f80d94aab651 | [
"MIT"
] | 1 | 2021-12-31T03:11:45.000Z | 2021-12-31T03:11:45.000Z | lib/index.ts | princess-rosella/spu-md5 | ddfae1ee439a5e7238e23a5f2c66f80d94aab651 | [
"MIT"
] | null | null | null | lib/index.ts | princess-rosella/spu-md5 | ddfae1ee439a5e7238e23a5f2c66f80d94aab651 | [
"MIT"
] | null | null | null | /*
* Copyright (c) 2018 Princess Rosella. All rights reserved.
*
* @LICENSE_HEADER_START@
*
* 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.
*
* @LICENSE_HEADER_END@
*/
export const BLOCK_SIZE = 64;
export const BLOCK_LENGTH = 16;
const isLittleEndian = new Uint8Array(new Uint32Array([0x12345678]).buffer)[0] === 0x78;
const rotl = function(n: number, b: number): number {
return (n << b) | (n >>> (32 - b));
};
const swab32s = function(n: number): number {
return (rotl(n, 8) & 0x00FF00FF) | (rotl(n, 24) & 0xFF00FF00);
};
const le32_to_cpu_uint32array = function(array: Uint32Array) {
if (isLittleEndian)
return;
for (let i = 0; i < array.length; i++)
array[i] = swab32s(array[i]);
};
const cpu_to_le32_uint32array = function(array: Uint32Array) {
if (isLittleEndian)
return;
for (let i = 0; i < array.length; i++)
array[i] = swab32s(array[i]);
};
const memcpy = function(dest: Uint8Array, destOffset: number, src: Uint8Array, srcOffset: number, length: number): void {
dest.set(src.subarray(srcOffset, srcOffset + length), destOffset);
};
const bzero = function(dest: Uint8Array, offset: number, length: number): void {
while (length--)
dest[offset++] = 0;
}
const FF = function(a: number, b: number, c: number, d: number, x: number, s: number, t: number): number {
const n = a + (b & c | ~b & d) + (x >>> 0) + t;
return ((n << s) | (n >>> (32 - s))) + b;
};
const GG = function(a: number, b: number, c: number, d: number, x: number, s: number, t: number): number {
const n = a + (b & d | c & ~d) + (x >>> 0) + t;
return ((n << s) | (n >>> (32 - s))) + b;
};
const HH = function(a: number, b: number, c: number, d: number, x: number, s: number, t: number): number {
const n = a + (b ^ c ^ d) + (x >>> 0) + t;
return ((n << s) | (n >>> (32 - s))) + b;
};
const II = function(a: number, b: number, c: number, d: number, x: number, s: number, t: number): number {
const n = a + (c ^ (b | ~d)) + (x >>> 0) + t;
return ((n << s) | (n >>> (32 - s))) + b;
};
const transform = function(block: Uint32Array, hash: Uint32Array) {
const aa = hash[0];
const bb = hash[1];
const cc = hash[2];
const dd = hash[3];
let a = aa;
let b = bb;
let c = cc;
let d = dd;
a = FF(a, b, c, d, block[ 0], 7, -680876936);
d = FF(d, a, b, c, block[ 1], 12, -389564586);
c = FF(c, d, a, b, block[ 2], 17, 606105819);
b = FF(b, c, d, a, block[ 3], 22, -1044525330);
a = FF(a, b, c, d, block[ 4], 7, -176418897);
d = FF(d, a, b, c, block[ 5], 12, 1200080426);
c = FF(c, d, a, b, block[ 6], 17, -1473231341);
b = FF(b, c, d, a, block[ 7], 22, -45705983);
a = FF(a, b, c, d, block[ 8], 7, 1770035416);
d = FF(d, a, b, c, block[ 9], 12, -1958414417);
c = FF(c, d, a, b, block[10], 17, -42063);
b = FF(b, c, d, a, block[11], 22, -1990404162);
a = FF(a, b, c, d, block[12], 7, 1804603682);
d = FF(d, a, b, c, block[13], 12, -40341101);
c = FF(c, d, a, b, block[14], 17, -1502002290);
b = FF(b, c, d, a, block[15], 22, 1236535329);
a = GG(a, b, c, d, block[ 1]|0, 5, -165796510);
d = GG(d, a, b, c, block[ 6]|0, 9, -1069501632);
c = GG(c, d, a, b, block[11]|0, 14, 643717713);
b = GG(b, c, d, a, block[ 0]|0, 20, -373897302);
a = GG(a, b, c, d, block[ 5]|0, 5, -701558691);
d = GG(d, a, b, c, block[10]|0, 9, 38016083);
c = GG(c, d, a, b, block[15]|0, 14, -660478335);
b = GG(b, c, d, a, block[ 4]|0, 20, -405537848);
a = GG(a, b, c, d, block[ 9]|0, 5, 568446438);
d = GG(d, a, b, c, block[14]|0, 9, -1019803690);
c = GG(c, d, a, b, block[ 3]|0, 14, -187363961);
b = GG(b, c, d, a, block[ 8]|0, 20, 1163531501);
a = GG(a, b, c, d, block[13]|0, 5, -1444681467);
d = GG(d, a, b, c, block[ 2]|0, 9, -51403784);
c = GG(c, d, a, b, block[ 7]|0, 14, 1735328473);
b = GG(b, c, d, a, block[12]|0, 20, -1926607734);
a = HH(a, b, c, d, block[ 5]|0, 4, -378558);
d = HH(d, a, b, c, block[ 8]|0, 11, -2022574463);
c = HH(c, d, a, b, block[11]|0, 16, 1839030562);
b = HH(b, c, d, a, block[14]|0, 23, -35309556);
a = HH(a, b, c, d, block[ 1]|0, 4, -1530992060);
d = HH(d, a, b, c, block[ 4]|0, 11, 1272893353);
c = HH(c, d, a, b, block[ 7]|0, 16, -155497632);
b = HH(b, c, d, a, block[10]|0, 23, -1094730640);
a = HH(a, b, c, d, block[13]|0, 4, 681279174);
d = HH(d, a, b, c, block[ 0]|0, 11, -358537222);
c = HH(c, d, a, b, block[ 3]|0, 16, -722521979);
b = HH(b, c, d, a, block[ 6]|0, 23, 76029189);
a = HH(a, b, c, d, block[ 9]|0, 4, -640364487);
d = HH(d, a, b, c, block[12]|0, 11, -421815835);
c = HH(c, d, a, b, block[15]|0, 16, 530742520);
b = HH(b, c, d, a, block[ 2]|0, 23, -995338651);
a = II(a, b, c, d, block[ 0]|0, 6, -198630844);
d = II(d, a, b, c, block[ 7]|0, 10, 1126891415);
c = II(c, d, a, b, block[14]|0, 15, -1416354905);
b = II(b, c, d, a, block[ 5]|0, 21, -57434055);
a = II(a, b, c, d, block[12]|0, 6, 1700485571);
d = II(d, a, b, c, block[ 3]|0, 10, -1894986606);
c = II(c, d, a, b, block[10]|0, 15, -1051523);
b = II(b, c, d, a, block[ 1]|0, 21, -2054922799);
a = II(a, b, c, d, block[ 8]|0, 6, 1873313359);
d = II(d, a, b, c, block[15]|0, 10, -30611744);
c = II(c, d, a, b, block[ 6]|0, 15, -1560198380);
b = II(b, c, d, a, block[13]|0, 21, 1309151649);
a = II(a, b, c, d, block[ 4]|0, 6, -145523070);
d = II(d, a, b, c, block[11]|0, 10, -1120210379);
c = II(c, d, a, b, block[ 2]|0, 15, 718787259);
b = II(b, c, d, a, block[ 9]|0, 21, -343485551);
hash[0] = (a + aa) >>> 0;
hash[1] = (b + bb) >>> 0;
hash[2] = (c + cc) >>> 0;
hash[3] = (d + dd) >>> 0;
};
/**
* MD5 message-digest algorithm
*/
export class MD5 {
private hash = new Uint32Array([1732584193, -271733879, -1732584194, 271733878]);
private block = new Uint32Array(16);
private block8: Uint8Array;
private byteCount = 0;
constructor() {
this.block8 = new Uint8Array(this.block.buffer, this.block.byteOffset, this.block.byteLength);
}
/**
* Dynamic version of MD5.update that accepts different types to binary data as parameters.
*
* @param data Data to hash
* @see MD5.update
*/
dynamicUpdate(data: Uint8Array | DataView | ArrayBuffer): void {
if (data instanceof DataView)
data = new Uint8Array(data.buffer, data.byteOffset, data.byteLength);
else if (data instanceof ArrayBuffer)
data = new Uint8Array(data);
if (!(data instanceof Uint8Array))
throw new Error(`Expected a Uint8Array, a DataView or an ArrayBuffer. Received ${data.constructor.name}`);
return this.update(data);
}
/**
* Process an array of bytes to hash.
*
* @param data Bytes to hash
*/
update(data: Uint8Array): void {
const avail = (BLOCK_SIZE - (this.byteCount & 0x3f))|0;
let length = data.length;
this.byteCount += length;
if (avail > length) {
memcpy(this.block8, BLOCK_SIZE - avail, data, 0, length);
return;
}
memcpy(this.block8, BLOCK_SIZE - avail, data, 0, avail);
this.transformHelper();
let offset = avail;
length -= avail;
while (length >= BLOCK_SIZE) {
memcpy(this.block8, 0, data, offset, BLOCK_SIZE);
this.transformHelper();
offset += BLOCK_SIZE;
length -= BLOCK_SIZE;
}
memcpy(this.block8, 0, data, offset, length);
}
/**
* Produce the hash as a sequence of 16 bytes.
*/
toUint8Array(): Uint8Array {
const offset = this.byteCount & 0x3f;
let p = offset;
let padding = 56 - (offset + 1);
const block8 = this.block8.slice(0);
const block = new Uint32Array(block8.buffer);
const hash = this.hash.slice(0);
block8[p++] = 0x80;
if (padding < 0) {
bzero(block8, p, padding + 8);
if (!isLittleEndian)
le32_to_cpu_uint32array(block);
transform(block, hash);
p = 0;
padding = 56;
}
bzero(block8, p, padding);
block[14] = this.byteCount << 3;
block[15] = this.byteCount >>> 29;
if (!isLittleEndian) {
le32_to_cpu_uint32array(block.subarray(0, BLOCK_LENGTH - 2));
transform(block, hash);
cpu_to_le32_uint32array(hash);
}
else {
transform(block, hash);
}
return new Uint8Array(hash.buffer);
}
/**
* Produce the hash as string in hexadecimal format.
*/
toString(): string {
let hex = "";
const hash = this.toUint8Array();
const hashLength = hash.byteLength;
for (let i = 0; i < hashLength; i++) {
hex += ((hash[i] >>> 4) & 0xF).toString(16);
hex += ((hash[i] >>> 0) & 0xF).toString(16);
}
return hex;
}
private transformHelper() {
if (!isLittleEndian)
le32_to_cpu_uint32array(this.block);
return transform(this.block, this.hash);
}
static process(data: Uint8Array | DataView | ArrayBuffer): string {
const md5 = new MD5();
md5.dynamicUpdate(data);
return md5.toString();
}
}
| 35.093023 | 121 | 0.547666 | 209 | 18 | 0 | 46 | 42 | 4 | 16 | 0 | 48 | 1 | 3 | 9.111111 | 4,421 | 0.014476 | 0.0095 | 0.000905 | 0.000226 | 0.000679 | 0 | 0.436364 | 0.238745 | /*
* Copyright (c) 2018 Princess Rosella. All rights reserved.
*
* @LICENSE_HEADER_START@
*
* 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.
*
* @LICENSE_HEADER_END@
*/
export const BLOCK_SIZE = 64;
export const BLOCK_LENGTH = 16;
const isLittleEndian = new Uint8Array(new Uint32Array([0x12345678]).buffer)[0] === 0x78;
/* Example usages of 'rotl' are shown below:
rotl(n, 8) & 0x00FF00FF;
rotl(n, 24) & 0xFF00FF00;
*/
const rotl = function(n, b) {
return (n << b) | (n >>> (32 - b));
};
/* Example usages of 'swab32s' are shown below:
array[i] = swab32s(array[i]);
*/
const swab32s = function(n) {
return (rotl(n, 8) & 0x00FF00FF) | (rotl(n, 24) & 0xFF00FF00);
};
/* Example usages of 'le32_to_cpu_uint32array' are shown below:
le32_to_cpu_uint32array(block);
le32_to_cpu_uint32array(block.subarray(0, BLOCK_LENGTH - 2));
le32_to_cpu_uint32array(this.block);
*/
const le32_to_cpu_uint32array = function(array) {
if (isLittleEndian)
return;
for (let i = 0; i < array.length; i++)
array[i] = swab32s(array[i]);
};
/* Example usages of 'cpu_to_le32_uint32array' are shown below:
cpu_to_le32_uint32array(hash);
*/
const cpu_to_le32_uint32array = function(array) {
if (isLittleEndian)
return;
for (let i = 0; i < array.length; i++)
array[i] = swab32s(array[i]);
};
/* Example usages of 'memcpy' are shown below:
memcpy(this.block8, BLOCK_SIZE - avail, data, 0, length);
memcpy(this.block8, BLOCK_SIZE - avail, data, 0, avail);
memcpy(this.block8, 0, data, offset, BLOCK_SIZE);
memcpy(this.block8, 0, data, offset, length);
*/
const memcpy = function(dest, destOffset, src, srcOffset, length) {
dest.set(src.subarray(srcOffset, srcOffset + length), destOffset);
};
/* Example usages of 'bzero' are shown below:
bzero(block8, p, padding + 8);
bzero(block8, p, padding);
*/
const bzero = function(dest, offset, length) {
while (length--)
dest[offset++] = 0;
}
/* Example usages of 'FF' are shown below:
a = FF(a, b, c, d, block[0], 7, -680876936);
d = FF(d, a, b, c, block[1], 12, -389564586);
c = FF(c, d, a, b, block[2], 17, 606105819);
b = FF(b, c, d, a, block[3], 22, -1044525330);
a = FF(a, b, c, d, block[4], 7, -176418897);
d = FF(d, a, b, c, block[5], 12, 1200080426);
c = FF(c, d, a, b, block[6], 17, -1473231341);
b = FF(b, c, d, a, block[7], 22, -45705983);
a = FF(a, b, c, d, block[8], 7, 1770035416);
d = FF(d, a, b, c, block[9], 12, -1958414417);
c = FF(c, d, a, b, block[10], 17, -42063);
b = FF(b, c, d, a, block[11], 22, -1990404162);
a = FF(a, b, c, d, block[12], 7, 1804603682);
d = FF(d, a, b, c, block[13], 12, -40341101);
c = FF(c, d, a, b, block[14], 17, -1502002290);
b = FF(b, c, d, a, block[15], 22, 1236535329);
*/
const FF = function(a, b, c, d, x, s, t) {
const n = a + (b & c | ~b & d) + (x >>> 0) + t;
return ((n << s) | (n >>> (32 - s))) + b;
};
/* Example usages of 'GG' are shown below:
a = GG(a, b, c, d, block[1] | 0, 5, -165796510);
d = GG(d, a, b, c, block[6] | 0, 9, -1069501632);
c = GG(c, d, a, b, block[11] | 0, 14, 643717713);
b = GG(b, c, d, a, block[0] | 0, 20, -373897302);
a = GG(a, b, c, d, block[5] | 0, 5, -701558691);
d = GG(d, a, b, c, block[10] | 0, 9, 38016083);
c = GG(c, d, a, b, block[15] | 0, 14, -660478335);
b = GG(b, c, d, a, block[4] | 0, 20, -405537848);
a = GG(a, b, c, d, block[9] | 0, 5, 568446438);
d = GG(d, a, b, c, block[14] | 0, 9, -1019803690);
c = GG(c, d, a, b, block[3] | 0, 14, -187363961);
b = GG(b, c, d, a, block[8] | 0, 20, 1163531501);
a = GG(a, b, c, d, block[13] | 0, 5, -1444681467);
d = GG(d, a, b, c, block[2] | 0, 9, -51403784);
c = GG(c, d, a, b, block[7] | 0, 14, 1735328473);
b = GG(b, c, d, a, block[12] | 0, 20, -1926607734);
*/
const GG = function(a, b, c, d, x, s, t) {
const n = a + (b & d | c & ~d) + (x >>> 0) + t;
return ((n << s) | (n >>> (32 - s))) + b;
};
/* Example usages of 'HH' are shown below:
a = HH(a, b, c, d, block[5] | 0, 4, -378558);
d = HH(d, a, b, c, block[8] | 0, 11, -2022574463);
c = HH(c, d, a, b, block[11] | 0, 16, 1839030562);
b = HH(b, c, d, a, block[14] | 0, 23, -35309556);
a = HH(a, b, c, d, block[1] | 0, 4, -1530992060);
d = HH(d, a, b, c, block[4] | 0, 11, 1272893353);
c = HH(c, d, a, b, block[7] | 0, 16, -155497632);
b = HH(b, c, d, a, block[10] | 0, 23, -1094730640);
a = HH(a, b, c, d, block[13] | 0, 4, 681279174);
d = HH(d, a, b, c, block[0] | 0, 11, -358537222);
c = HH(c, d, a, b, block[3] | 0, 16, -722521979);
b = HH(b, c, d, a, block[6] | 0, 23, 76029189);
a = HH(a, b, c, d, block[9] | 0, 4, -640364487);
d = HH(d, a, b, c, block[12] | 0, 11, -421815835);
c = HH(c, d, a, b, block[15] | 0, 16, 530742520);
b = HH(b, c, d, a, block[2] | 0, 23, -995338651);
*/
const HH = function(a, b, c, d, x, s, t) {
const n = a + (b ^ c ^ d) + (x >>> 0) + t;
return ((n << s) | (n >>> (32 - s))) + b;
};
/* Example usages of 'II' are shown below:
a = II(a, b, c, d, block[0] | 0, 6, -198630844);
d = II(d, a, b, c, block[7] | 0, 10, 1126891415);
c = II(c, d, a, b, block[14] | 0, 15, -1416354905);
b = II(b, c, d, a, block[5] | 0, 21, -57434055);
a = II(a, b, c, d, block[12] | 0, 6, 1700485571);
d = II(d, a, b, c, block[3] | 0, 10, -1894986606);
c = II(c, d, a, b, block[10] | 0, 15, -1051523);
b = II(b, c, d, a, block[1] | 0, 21, -2054922799);
a = II(a, b, c, d, block[8] | 0, 6, 1873313359);
d = II(d, a, b, c, block[15] | 0, 10, -30611744);
c = II(c, d, a, b, block[6] | 0, 15, -1560198380);
b = II(b, c, d, a, block[13] | 0, 21, 1309151649);
a = II(a, b, c, d, block[4] | 0, 6, -145523070);
d = II(d, a, b, c, block[11] | 0, 10, -1120210379);
c = II(c, d, a, b, block[2] | 0, 15, 718787259);
b = II(b, c, d, a, block[9] | 0, 21, -343485551);
*/
const II = function(a, b, c, d, x, s, t) {
const n = a + (c ^ (b | ~d)) + (x >>> 0) + t;
return ((n << s) | (n >>> (32 - s))) + b;
};
/* Example usages of 'transform' are shown below:
transform(block, hash);
transform(this.block, this.hash);
*/
const transform = function(block, hash) {
const aa = hash[0];
const bb = hash[1];
const cc = hash[2];
const dd = hash[3];
let a = aa;
let b = bb;
let c = cc;
let d = dd;
a = FF(a, b, c, d, block[ 0], 7, -680876936);
d = FF(d, a, b, c, block[ 1], 12, -389564586);
c = FF(c, d, a, b, block[ 2], 17, 606105819);
b = FF(b, c, d, a, block[ 3], 22, -1044525330);
a = FF(a, b, c, d, block[ 4], 7, -176418897);
d = FF(d, a, b, c, block[ 5], 12, 1200080426);
c = FF(c, d, a, b, block[ 6], 17, -1473231341);
b = FF(b, c, d, a, block[ 7], 22, -45705983);
a = FF(a, b, c, d, block[ 8], 7, 1770035416);
d = FF(d, a, b, c, block[ 9], 12, -1958414417);
c = FF(c, d, a, b, block[10], 17, -42063);
b = FF(b, c, d, a, block[11], 22, -1990404162);
a = FF(a, b, c, d, block[12], 7, 1804603682);
d = FF(d, a, b, c, block[13], 12, -40341101);
c = FF(c, d, a, b, block[14], 17, -1502002290);
b = FF(b, c, d, a, block[15], 22, 1236535329);
a = GG(a, b, c, d, block[ 1]|0, 5, -165796510);
d = GG(d, a, b, c, block[ 6]|0, 9, -1069501632);
c = GG(c, d, a, b, block[11]|0, 14, 643717713);
b = GG(b, c, d, a, block[ 0]|0, 20, -373897302);
a = GG(a, b, c, d, block[ 5]|0, 5, -701558691);
d = GG(d, a, b, c, block[10]|0, 9, 38016083);
c = GG(c, d, a, b, block[15]|0, 14, -660478335);
b = GG(b, c, d, a, block[ 4]|0, 20, -405537848);
a = GG(a, b, c, d, block[ 9]|0, 5, 568446438);
d = GG(d, a, b, c, block[14]|0, 9, -1019803690);
c = GG(c, d, a, b, block[ 3]|0, 14, -187363961);
b = GG(b, c, d, a, block[ 8]|0, 20, 1163531501);
a = GG(a, b, c, d, block[13]|0, 5, -1444681467);
d = GG(d, a, b, c, block[ 2]|0, 9, -51403784);
c = GG(c, d, a, b, block[ 7]|0, 14, 1735328473);
b = GG(b, c, d, a, block[12]|0, 20, -1926607734);
a = HH(a, b, c, d, block[ 5]|0, 4, -378558);
d = HH(d, a, b, c, block[ 8]|0, 11, -2022574463);
c = HH(c, d, a, b, block[11]|0, 16, 1839030562);
b = HH(b, c, d, a, block[14]|0, 23, -35309556);
a = HH(a, b, c, d, block[ 1]|0, 4, -1530992060);
d = HH(d, a, b, c, block[ 4]|0, 11, 1272893353);
c = HH(c, d, a, b, block[ 7]|0, 16, -155497632);
b = HH(b, c, d, a, block[10]|0, 23, -1094730640);
a = HH(a, b, c, d, block[13]|0, 4, 681279174);
d = HH(d, a, b, c, block[ 0]|0, 11, -358537222);
c = HH(c, d, a, b, block[ 3]|0, 16, -722521979);
b = HH(b, c, d, a, block[ 6]|0, 23, 76029189);
a = HH(a, b, c, d, block[ 9]|0, 4, -640364487);
d = HH(d, a, b, c, block[12]|0, 11, -421815835);
c = HH(c, d, a, b, block[15]|0, 16, 530742520);
b = HH(b, c, d, a, block[ 2]|0, 23, -995338651);
a = II(a, b, c, d, block[ 0]|0, 6, -198630844);
d = II(d, a, b, c, block[ 7]|0, 10, 1126891415);
c = II(c, d, a, b, block[14]|0, 15, -1416354905);
b = II(b, c, d, a, block[ 5]|0, 21, -57434055);
a = II(a, b, c, d, block[12]|0, 6, 1700485571);
d = II(d, a, b, c, block[ 3]|0, 10, -1894986606);
c = II(c, d, a, b, block[10]|0, 15, -1051523);
b = II(b, c, d, a, block[ 1]|0, 21, -2054922799);
a = II(a, b, c, d, block[ 8]|0, 6, 1873313359);
d = II(d, a, b, c, block[15]|0, 10, -30611744);
c = II(c, d, a, b, block[ 6]|0, 15, -1560198380);
b = II(b, c, d, a, block[13]|0, 21, 1309151649);
a = II(a, b, c, d, block[ 4]|0, 6, -145523070);
d = II(d, a, b, c, block[11]|0, 10, -1120210379);
c = II(c, d, a, b, block[ 2]|0, 15, 718787259);
b = II(b, c, d, a, block[ 9]|0, 21, -343485551);
hash[0] = (a + aa) >>> 0;
hash[1] = (b + bb) >>> 0;
hash[2] = (c + cc) >>> 0;
hash[3] = (d + dd) >>> 0;
};
/**
* MD5 message-digest algorithm
*/
export class MD5 {
private hash = new Uint32Array([1732584193, -271733879, -1732584194, 271733878]);
private block = new Uint32Array(16);
private block8;
private byteCount = 0;
constructor() {
this.block8 = new Uint8Array(this.block.buffer, this.block.byteOffset, this.block.byteLength);
}
/**
* Dynamic version of MD5.update that accepts different types to binary data as parameters.
*
* @param data Data to hash
* @see MD5.update
*/
dynamicUpdate(data) {
if (data instanceof DataView)
data = new Uint8Array(data.buffer, data.byteOffset, data.byteLength);
else if (data instanceof ArrayBuffer)
data = new Uint8Array(data);
if (!(data instanceof Uint8Array))
throw new Error(`Expected a Uint8Array, a DataView or an ArrayBuffer. Received ${data.constructor.name}`);
return this.update(data);
}
/**
* Process an array of bytes to hash.
*
* @param data Bytes to hash
*/
update(data) {
const avail = (BLOCK_SIZE - (this.byteCount & 0x3f))|0;
let length = data.length;
this.byteCount += length;
if (avail > length) {
memcpy(this.block8, BLOCK_SIZE - avail, data, 0, length);
return;
}
memcpy(this.block8, BLOCK_SIZE - avail, data, 0, avail);
this.transformHelper();
let offset = avail;
length -= avail;
while (length >= BLOCK_SIZE) {
memcpy(this.block8, 0, data, offset, BLOCK_SIZE);
this.transformHelper();
offset += BLOCK_SIZE;
length -= BLOCK_SIZE;
}
memcpy(this.block8, 0, data, offset, length);
}
/**
* Produce the hash as a sequence of 16 bytes.
*/
toUint8Array() {
const offset = this.byteCount & 0x3f;
let p = offset;
let padding = 56 - (offset + 1);
const block8 = this.block8.slice(0);
const block = new Uint32Array(block8.buffer);
const hash = this.hash.slice(0);
block8[p++] = 0x80;
if (padding < 0) {
bzero(block8, p, padding + 8);
if (!isLittleEndian)
le32_to_cpu_uint32array(block);
transform(block, hash);
p = 0;
padding = 56;
}
bzero(block8, p, padding);
block[14] = this.byteCount << 3;
block[15] = this.byteCount >>> 29;
if (!isLittleEndian) {
le32_to_cpu_uint32array(block.subarray(0, BLOCK_LENGTH - 2));
transform(block, hash);
cpu_to_le32_uint32array(hash);
}
else {
transform(block, hash);
}
return new Uint8Array(hash.buffer);
}
/**
* Produce the hash as string in hexadecimal format.
*/
toString() {
let hex = "";
const hash = this.toUint8Array();
const hashLength = hash.byteLength;
for (let i = 0; i < hashLength; i++) {
hex += ((hash[i] >>> 4) & 0xF).toString(16);
hex += ((hash[i] >>> 0) & 0xF).toString(16);
}
return hex;
}
private transformHelper() {
if (!isLittleEndian)
le32_to_cpu_uint32array(this.block);
return transform(this.block, this.hash);
}
static process(data) {
const md5 = new MD5();
md5.dynamicUpdate(data);
return md5.toString();
}
}
|
60baa4be3249fdb09aa4318611c9c4351e704e60 | 1,921 | ts | TypeScript | backend/src/helpers/BaseHelper.ts | verida/Credentials-Management-Platform | 0ab28f637975825a79fc11077bbcff892fc4ba1d | [
"ISC"
] | null | null | null | backend/src/helpers/BaseHelper.ts | verida/Credentials-Management-Platform | 0ab28f637975825a79fc11077bbcff892fc4ba1d | [
"ISC"
] | 8 | 2022-02-10T06:03:31.000Z | 2022-03-30T06:55:59.000Z | backend/src/helpers/BaseHelper.ts | verida/Credentials-Management-Platform | 0ab28f637975825a79fc11077bbcff892fc4ba1d | [
"ISC"
] | null | null | null | export default class BaseHelper {
// Source: https://stackoverflow.com/a/55011290
static convertBase(str: string, fromBase: number, toBase: number): string {
const DIGITS =
'0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ-_';
const add = (x, y, base) => {
const z = [];
const n = Math.max(x.length, y.length);
let carry = 0;
let i = 0;
while (i < n || carry) {
const xi = i < x.length ? x[i] : 0;
const yi = i < y.length ? y[i] : 0;
const zi = carry + xi + yi;
z.push(zi % base);
carry = Math.floor(zi / base);
i++;
}
return z;
};
const multiplyByNumber = (num, x, base) => {
if (num < 0) return null;
if (num == 0) return [];
let result = [];
let power = x;
while (true) {
num & 1 && (result = add(result, power, base));
num = num >> 1;
if (num === 0) break;
power = add(power, power, base);
}
return result;
};
const parseToDigitsArray = str => {
const digits = str.split('');
const arr = [];
for (let i = digits.length - 1; i >= 0; i--) {
const n = DIGITS.indexOf(digits[i]);
if (n == -1) return null;
arr.push(n);
}
return arr;
};
const digits = parseToDigitsArray(str);
if (digits === null) return null;
let outArray = [];
let power = [1];
for (let i = 0; i < digits.length; i++) {
digits[i] &&
(outArray = add(
outArray,
multiplyByNumber(digits[i], power, toBase),
toBase,
));
power = multiplyByNumber(fromBase, power, toBase);
}
let out = '';
for (let i = outArray.length - 1; i >= 0; i--) out += DIGITS[outArray[i]];
// Avoid losing leading zeros
if (str.substring(0, 1) === '0') {
return '0' + out;
}
return out;
}
}
| 25.276316 | 78 | 0.503384 | 63 | 4 | 0 | 10 | 23 | 0 | 3 | 0 | 4 | 1 | 0 | 22.75 | 580 | 0.024138 | 0.039655 | 0 | 0.001724 | 0 | 0 | 0.108108 | 0.359591 | export default class BaseHelper {
// Source: https://stackoverflow.com/a/55011290
static convertBase(str, fromBase, toBase) {
const DIGITS =
'0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ-_';
/* Example usages of 'add' are shown below:
result = add(result, power, base);
power = add(power, power, base);
outArray = add(outArray, multiplyByNumber(digits[i], power, toBase), toBase);
*/
const add = (x, y, base) => {
const z = [];
const n = Math.max(x.length, y.length);
let carry = 0;
let i = 0;
while (i < n || carry) {
const xi = i < x.length ? x[i] : 0;
const yi = i < y.length ? y[i] : 0;
const zi = carry + xi + yi;
z.push(zi % base);
carry = Math.floor(zi / base);
i++;
}
return z;
};
/* Example usages of 'multiplyByNumber' are shown below:
outArray = add(outArray, multiplyByNumber(digits[i], power, toBase), toBase);
power = multiplyByNumber(fromBase, power, toBase);
*/
const multiplyByNumber = (num, x, base) => {
if (num < 0) return null;
if (num == 0) return [];
let result = [];
let power = x;
while (true) {
num & 1 && (result = add(result, power, base));
num = num >> 1;
if (num === 0) break;
power = add(power, power, base);
}
return result;
};
/* Example usages of 'parseToDigitsArray' are shown below:
parseToDigitsArray(str);
*/
const parseToDigitsArray = str => {
const digits = str.split('');
const arr = [];
for (let i = digits.length - 1; i >= 0; i--) {
const n = DIGITS.indexOf(digits[i]);
if (n == -1) return null;
arr.push(n);
}
return arr;
};
const digits = parseToDigitsArray(str);
if (digits === null) return null;
let outArray = [];
let power = [1];
for (let i = 0; i < digits.length; i++) {
digits[i] &&
(outArray = add(
outArray,
multiplyByNumber(digits[i], power, toBase),
toBase,
));
power = multiplyByNumber(fromBase, power, toBase);
}
let out = '';
for (let i = outArray.length - 1; i >= 0; i--) out += DIGITS[outArray[i]];
// Avoid losing leading zeros
if (str.substring(0, 1) === '0') {
return '0' + out;
}
return out;
}
}
|
852db70efa343b318d8a11bc6eb3ef6ab9857b46 | 1,826 | ts | TypeScript | orders/models/validation/validation-error.ts | aguirrerodrigo/ra-order | 3dc660cf8cd221108a70bc1c36b4586c5ee17c7a | [
"MIT"
] | null | null | null | orders/models/validation/validation-error.ts | aguirrerodrigo/ra-order | 3dc660cf8cd221108a70bc1c36b4586c5ee17c7a | [
"MIT"
] | 2 | 2022-01-22T12:49:42.000Z | 2022-01-22T12:49:48.000Z | orders/models/validation/validation-error.ts | aguirrerodrigo/ra-order | 3dc660cf8cd221108a70bc1c36b4586c5ee17c7a | [
"MIT"
] | null | null | null | export class ValidationError {
property = '';
errors: string[] = [];
source?: any;
}
export function parseValidationError(error: any): ValidationError[] {
const result: ValidationError[] = [];
let childErrors: ValidationError[];
const recurseChildErrors = (
err: any,
prevValueIsArray: boolean = false,
prop: string = ''
): void => {
if (err.children != null && err.children.length > 0) {
if (prop.length === 0) {
prop = err.property;
} else {
prop += prevValueIsArray ? `[${err.property}]` : `.${err.property}`;
}
for (const child of err.children) {
recurseChildErrors(
child,
Array.isArray(err.value) ||
err.value instanceof Map ||
err.value instanceof Set,
prop
);
}
} else {
if (err.constraints != null) {
const model = new ValidationError();
model.property = prop + '.' + err.property;
model.errors = [...Object.values(err.constraints)] as string[];
childErrors.push(model);
}
}
};
// class-validator error
if (Array.isArray(error)) {
for (const err of error) {
if (err.property != null) {
if (err.constraints != null) {
const model = new ValidationError();
model.property = err.property;
model.errors = [...Object.values(err.constraints)] as string[];
result.push(model);
} else if (err.children != null && err.children.length > 0) {
childErrors = [];
recurseChildErrors(err);
for (const child of childErrors) {
result.push(child);
}
}
}
}
}
// generic error
else if (error.message != null) {
const model = new ValidationError();
model.errors.push(error.message);
result.push(model);
}
// unkown error
else {
const model = new ValidationError();
model.errors.push('Unknown error.');
model.source = error;
}
return result;
}
| 23.714286 | 72 | 0.616648 | 67 | 2 | 0 | 4 | 7 | 3 | 1 | 3 | 6 | 1 | 4 | 41.5 | 558 | 0.010753 | 0.012545 | 0.005376 | 0.001792 | 0.007168 | 0.1875 | 0.375 | 0.23494 | export class ValidationError {
property = '';
errors = [];
source?;
}
export function parseValidationError(error) {
const result = [];
let childErrors;
/* Example usages of 'recurseChildErrors' are shown below:
recurseChildErrors(child, Array.isArray(err.value) ||
err.value instanceof Map ||
err.value instanceof Set, prop);
recurseChildErrors(err);
*/
const recurseChildErrors = (
err,
prevValueIsArray = false,
prop = ''
) => {
if (err.children != null && err.children.length > 0) {
if (prop.length === 0) {
prop = err.property;
} else {
prop += prevValueIsArray ? `[${err.property}]` : `.${err.property}`;
}
for (const child of err.children) {
recurseChildErrors(
child,
Array.isArray(err.value) ||
err.value instanceof Map ||
err.value instanceof Set,
prop
);
}
} else {
if (err.constraints != null) {
const model = new ValidationError();
model.property = prop + '.' + err.property;
model.errors = [...Object.values(err.constraints)] as string[];
childErrors.push(model);
}
}
};
// class-validator error
if (Array.isArray(error)) {
for (const err of error) {
if (err.property != null) {
if (err.constraints != null) {
const model = new ValidationError();
model.property = err.property;
model.errors = [...Object.values(err.constraints)] as string[];
result.push(model);
} else if (err.children != null && err.children.length > 0) {
childErrors = [];
recurseChildErrors(err);
for (const child of childErrors) {
result.push(child);
}
}
}
}
}
// generic error
else if (error.message != null) {
const model = new ValidationError();
model.errors.push(error.message);
result.push(model);
}
// unkown error
else {
const model = new ValidationError();
model.errors.push('Unknown error.');
model.source = error;
}
return result;
}
|
855274af54f9fb0e9121c4f1c8c601c4cfb743ee | 1,481 | ts | TypeScript | lit-file-router/src/analyze-page.ts | rodydavis/lit-file-based-routing | 9961a9771661bcb7134f2f8cbe3bdd2e4b6786a0 | [
"Apache-2.0"
] | 9 | 2022-01-08T20:43:31.000Z | 2022-01-12T21:59:33.000Z | lit-file-router/src/analyze-page.ts | rodydavis/lit-file-based-routing | 9961a9771661bcb7134f2f8cbe3bdd2e4b6786a0 | [
"Apache-2.0"
] | null | null | null | lit-file-router/src/analyze-page.ts | rodydavis/lit-file-based-routing | 9961a9771661bcb7134f2f8cbe3bdd2e4b6786a0 | [
"Apache-2.0"
] | null | null | null | export function analyzePage(path: string, content: string): WebComponent[] {
const components: WebComponent[] = [];
// Check for export function loader( or export async function loader(
let hasLoader = false;
const lines = content.split("\n");
for (let i = 0; i < lines.length; i++) {
const line = lines[i];
if (
line.includes("export function loader(") ||
line.includes("export async function loader(")
) {
hasLoader = true;
break;
}
}
// Look for @customElement decorator and get the value
const regex = /@customElement\("([^"]+)"\)/g;
const matches = content.match(regex);
if (matches) {
for (const match of matches) {
const result = match.match(/@customElement\("([^"]+)"\)/);
if (result) {
const name = result[1];
components.push({
name,
path,
hasLoader,
});
}
}
}
// Look for customElements.define() and get the value
const regex2 = /customElements\.define\("([^"]+)"/g;
const matches2 = content.match(regex2);
if (matches2) {
for (const match of matches2) {
const result = match.match(/customElements\.define\("([^"]+)"/);
if (result) {
const name = result[1];
components.push({
name,
path,
hasLoader,
});
}
}
}
return components;
}
export interface WebComponent {
name: string;
path: string;
alias?: string;
hasLoader: boolean;
}
| 25.982456 | 76 | 0.571236 | 52 | 1 | 0 | 2 | 13 | 4 | 0 | 0 | 6 | 1 | 0 | 44 | 384 | 0.007813 | 0.033854 | 0.010417 | 0.002604 | 0 | 0 | 0.3 | 0.302923 | export function analyzePage(path, content) {
const components = [];
// Check for export function loader( or export async function loader(
let hasLoader = false;
const lines = content.split("\n");
for (let i = 0; i < lines.length; i++) {
const line = lines[i];
if (
line.includes("export function loader(") ||
line.includes("export async function loader(")
) {
hasLoader = true;
break;
}
}
// Look for @customElement decorator and get the value
const regex = /@customElement\("([^"]+)"\)/g;
const matches = content.match(regex);
if (matches) {
for (const match of matches) {
const result = match.match(/@customElement\("([^"]+)"\)/);
if (result) {
const name = result[1];
components.push({
name,
path,
hasLoader,
});
}
}
}
// Look for customElements.define() and get the value
const regex2 = /customElements\.define\("([^"]+)"/g;
const matches2 = content.match(regex2);
if (matches2) {
for (const match of matches2) {
const result = match.match(/customElements\.define\("([^"]+)"/);
if (result) {
const name = result[1];
components.push({
name,
path,
hasLoader,
});
}
}
}
return components;
}
export interface WebComponent {
name;
path;
alias?;
hasLoader;
}
|
85f3bc6b4d2cdd76d832d0fd3f0c3c3a8efc8d13 | 5,003 | ts | TypeScript | src/index.ts | Garbee/Iso8601 | e3eebb6acc2f0aad16337113fe24b641e0a5f4fc | [
"Unlicense"
] | 1 | 2022-02-20T18:43:08.000Z | 2022-02-20T18:43:08.000Z | src/index.ts | Garbee/Iso8601 | e3eebb6acc2f0aad16337113fe24b641e0a5f4fc | [
"Unlicense"
] | null | null | null | src/index.ts | Garbee/Iso8601 | e3eebb6acc2f0aad16337113fe24b641e0a5f4fc | [
"Unlicense"
] | null | null | null | // A subset of https://en.wikipedia.org/wiki/ISO_8601
/**
* Years are represented from the gregorian calendar only
* as 0000 to 9999. (If anyone has to worry about after 9999
* with this code, I am deeply sorry.) Technically 0000 -
* 1582 are not allowed by the standard except by mutual
* agreement between parties. This is explicitly forced
* when validating in order to ensure we are only working
* with data browsers can reasonably parse and get correct.
*/
const yearPattern = /(?<year>158[3-9]|159\d|1[6-9]\d{2}|[2-9]\d{3})/;
/**
* Months are always 2-digits in a non-index format.
* This differs from JavaScripts Date constructor for
* example where months are 0-11 rather than ISO's 1-12.
*/
const monthPattern = /(?<month>0[1-9]|1[0-2])/;
/**
* Days are always 2 digits.
* 01-09, 10-19, 20-29, 30-31.
*/
const dayPattern = /(?<day>0[1-9]|[12]\d|3[01])/;
/**
* Hours are always 2 digits and in 24 hour time.
* 01-19, 20-23
*/
const hourPattern = /(?<hour>[01]\d|2[0-3])/;
/**
* Minutes are alays 2 digits.
*/
const minutePattern = /(?<minute>[0-5]\d)/;
/**
* Seconds are always 2 digits.
* 60 is used to represent leap seconds.
*/
const secondsPattern = /(?<seconds>([0-5]\d)|60)/;
/**
* Millisesconds are always 3 digits.
* From 000-999.
* The period to denote them is required if MS are present.
*/
const millisecondsPattern = /(?:\.(?<milliseconds>\d{3}))?/;
/**
* Timezone is complex and difficult to break down further
* since it is all one group.
* Gist of it is timezones have 4 possible modes:
* * Positive Offset
* * Negative Offset
* * 'Z' string for UTC time (+00:00)
* * Unqualified (not present) (meaning local time.)
*
* With subgroups this could be made to give specific
* outputs like `positiveOffset`, `negativeOffset`, or
* `utcString` for determining which timezone style is
* present.
* However, without a use-case this effort wasn't completed
* only validated that it could be possible.
*
* This pattern technically allows a bit more than standards
* currently have. Up to +14:45 and down to -12:45. Should
* anyone care to correct this and make it more strict, go
* ahead just add tests to prove it when you do.
*/
const fullTimeZonePattern = /(?<offset>([+]((0\d|1[0-3])(?::(00|15|30|45))?|14(?::00)?)|([-]((0\d|1[0-1])(?::(00|15|30|45))?|12(?::00)?)|Z))?)/;
/**
* Pattern to determine if a full calendar date is present.
*/
const fullCalendarDatePattern = yearPattern.source +
/-/.source +
monthPattern.source +
/-/.source +
dayPattern.source;
/**
* Pattern to validate a complete date and time string.
*/
const fullIso8601DateTimePattern = /^/.source +
yearPattern.source +
/-?/.source +
monthPattern.source +
/-?/.source +
dayPattern.source +
/T/.source +
hourPattern.source +
/:?/.source +
minutePattern.source +
/:?/.source +
secondsPattern.source +
millisecondsPattern.source +
fullTimeZonePattern.source +
/$/.source;
const iso8601Date = new RegExp(
`^${fullCalendarDatePattern}$`,
);
const isIso8601DateTime = new RegExp(
fullIso8601DateTimePattern,
);
export interface DateStructure {
year: number;
month: number;
day: number;
}
export interface TimeStructure {
hour: number;
minute: number;
seconds: number;
milliseconds: number;
offset: string | undefined;
}
export type DateTimeStructure = DateStructure &
TimeStructure;
export const parseDateTimeString = function(value: string):
DateTimeStructure {
const {groups} = isIso8601DateTime.exec(value) || {};
const parseWasUnsuccessful = groups === undefined;
if (parseWasUnsuccessful === true) {
throw new Error(
'Invalid date and time string given to parse',
);
}
const offset = groups.offset !== '' ?
groups.offset :
undefined;
return {
year: parseInt(
groups.year,
10,
),
month: parseInt(
groups.month,
10,
),
day: parseInt(
groups.day,
10,
),
hour: parseInt(
groups.hour,
10,
),
minute: parseInt(
groups.minute,
10,
),
seconds: parseInt(
groups.seconds,
10,
),
milliseconds: parseInt(
groups.milliseconds,
10,
),
offset,
};
};
export const isValidDate = function(value: string):
boolean {
return iso8601Date.test(value);
};
export const isValidDateTime = function(value: string):
boolean {
return isIso8601DateTime.test(value);
};
export const parseDateString = function(value: string):
DateStructure {
const {groups} = iso8601Date.exec(value) || {};
const parseWasUnsuccessful = groups === undefined;
if (parseWasUnsuccessful === true) {
throw new Error('Invalid date string given to parse');
}
return {
year: parseInt(
groups.year,
10,
),
month: parseInt(
groups.month,
10,
),
day: parseInt(
groups.day,
10,
),
};
};
| 24.767327 | 144 | 0.639017 | 122 | 4 | 0 | 4 | 21 | 8 | 0 | 0 | 14 | 3 | 0 | 15.5 | 1,542 | 0.005188 | 0.013619 | 0.005188 | 0.001946 | 0 | 0 | 0.378378 | 0.22935 | // A subset of https://en.wikipedia.org/wiki/ISO_8601
/**
* Years are represented from the gregorian calendar only
* as 0000 to 9999. (If anyone has to worry about after 9999
* with this code, I am deeply sorry.) Technically 0000 -
* 1582 are not allowed by the standard except by mutual
* agreement between parties. This is explicitly forced
* when validating in order to ensure we are only working
* with data browsers can reasonably parse and get correct.
*/
const yearPattern = /(?<year>158[3-9]|159\d|1[6-9]\d{2}|[2-9]\d{3})/;
/**
* Months are always 2-digits in a non-index format.
* This differs from JavaScripts Date constructor for
* example where months are 0-11 rather than ISO's 1-12.
*/
const monthPattern = /(?<month>0[1-9]|1[0-2])/;
/**
* Days are always 2 digits.
* 01-09, 10-19, 20-29, 30-31.
*/
const dayPattern = /(?<day>0[1-9]|[12]\d|3[01])/;
/**
* Hours are always 2 digits and in 24 hour time.
* 01-19, 20-23
*/
const hourPattern = /(?<hour>[01]\d|2[0-3])/;
/**
* Minutes are alays 2 digits.
*/
const minutePattern = /(?<minute>[0-5]\d)/;
/**
* Seconds are always 2 digits.
* 60 is used to represent leap seconds.
*/
const secondsPattern = /(?<seconds>([0-5]\d)|60)/;
/**
* Millisesconds are always 3 digits.
* From 000-999.
* The period to denote them is required if MS are present.
*/
const millisecondsPattern = /(?:\.(?<milliseconds>\d{3}))?/;
/**
* Timezone is complex and difficult to break down further
* since it is all one group.
* Gist of it is timezones have 4 possible modes:
* * Positive Offset
* * Negative Offset
* * 'Z' string for UTC time (+00:00)
* * Unqualified (not present) (meaning local time.)
*
* With subgroups this could be made to give specific
* outputs like `positiveOffset`, `negativeOffset`, or
* `utcString` for determining which timezone style is
* present.
* However, without a use-case this effort wasn't completed
* only validated that it could be possible.
*
* This pattern technically allows a bit more than standards
* currently have. Up to +14:45 and down to -12:45. Should
* anyone care to correct this and make it more strict, go
* ahead just add tests to prove it when you do.
*/
const fullTimeZonePattern = /(?<offset>([+]((0\d|1[0-3])(?::(00|15|30|45))?|14(?::00)?)|([-]((0\d|1[0-1])(?::(00|15|30|45))?|12(?::00)?)|Z))?)/;
/**
* Pattern to determine if a full calendar date is present.
*/
const fullCalendarDatePattern = yearPattern.source +
/-/.source +
monthPattern.source +
/-/.source +
dayPattern.source;
/**
* Pattern to validate a complete date and time string.
*/
const fullIso8601DateTimePattern = /^/.source +
yearPattern.source +
/-?/.source +
monthPattern.source +
/-?/.source +
dayPattern.source +
/T/.source +
hourPattern.source +
/:?/.source +
minutePattern.source +
/:?/.source +
secondsPattern.source +
millisecondsPattern.source +
fullTimeZonePattern.source +
/$/.source;
const iso8601Date = new RegExp(
`^${fullCalendarDatePattern}$`,
);
const isIso8601DateTime = new RegExp(
fullIso8601DateTimePattern,
);
export interface DateStructure {
year;
month;
day;
}
export interface TimeStructure {
hour;
minute;
seconds;
milliseconds;
offset;
}
export type DateTimeStructure = DateStructure &
TimeStructure;
export const parseDateTimeString = function(value) {
const {groups} = isIso8601DateTime.exec(value) || {};
const parseWasUnsuccessful = groups === undefined;
if (parseWasUnsuccessful === true) {
throw new Error(
'Invalid date and time string given to parse',
);
}
const offset = groups.offset !== '' ?
groups.offset :
undefined;
return {
year: parseInt(
groups.year,
10,
),
month: parseInt(
groups.month,
10,
),
day: parseInt(
groups.day,
10,
),
hour: parseInt(
groups.hour,
10,
),
minute: parseInt(
groups.minute,
10,
),
seconds: parseInt(
groups.seconds,
10,
),
milliseconds: parseInt(
groups.milliseconds,
10,
),
offset,
};
};
export const isValidDate = function(value) {
return iso8601Date.test(value);
};
export const isValidDateTime = function(value) {
return isIso8601DateTime.test(value);
};
export const parseDateString = function(value) {
const {groups} = iso8601Date.exec(value) || {};
const parseWasUnsuccessful = groups === undefined;
if (parseWasUnsuccessful === true) {
throw new Error('Invalid date string given to parse');
}
return {
year: parseInt(
groups.year,
10,
),
month: parseInt(
groups.month,
10,
),
day: parseInt(
groups.day,
10,
),
};
};
|
73165b87d19de1a98d98c9f7373a786d14c47a4a | 3,566 | ts | TypeScript | lib/Utils.ts | noreajs/common | e7b94ade985e22a9a9c11cccfeef73807f3032ab | [
"MIT"
] | null | null | null | lib/Utils.ts | noreajs/common | e7b94ade985e22a9a9c11cccfeef73807f3032ab | [
"MIT"
] | 3 | 2022-01-19T14:20:47.000Z | 2022-01-19T14:20:56.000Z | lib/Utils.ts | noreajs/common | e7b94ade985e22a9a9c11cccfeef73807f3032ab | [
"MIT"
] | null | null | null | /**
* Get if the given value is null or undefined
* @param value input
*/
export const isFilled = (value: any) => {
return value !== null && value !== undefined;
};
/**
* Get if the given value is null or undefined and length > 0
* @param value input
*/
export const isQueryParamFilled = (value: any) => {
return value !== null && value !== undefined && `${value}`.length !== 0;
};
/**
* Return 0 if the number in NaN and the number if not
* @param value number
*/
export const forceNumber = (value: any): number => {
const num = Number(value);
return isNaN(num) ? 0 : num;
};
/**
* Assign nested property in object
*
* @deprecated use Obj.assignNestedProperty instead
*
* @param obj object
* @param keyPath key path list
* @param value value to assign
*/
export const assignNestedProperty = (
obj: any,
keyPath: Array<string>,
value: any
) => {
for (let index = 0; index < keyPath.length; index++) {
const key = keyPath[index];
if (index != keyPath.length - 1) {
if (!(key in obj)) {
obj[key] = {};
}
obj = obj[key];
} else {
obj[key] = value;
}
}
};
/**
* Remove all white spaces in string
* @param value string
* @param replacement string that will replace the space
*/
export const removeAllWhiteSpaces = (value: string, replacement?: string) => {
return value.replace(/\s/g, replacement || "");
};
/**
* Replace all occurences of a searched string in another string
*
* @param value target string
* @param search element to replace
* @param replacement replacement
*/
export const replaceAllMatch = (
value: string,
search: RegExp,
replacement: string
) => {
return value.replace(search, replacement);
};
/**
* Return a value of a nested property (last key in the given path)
*
* @deprecated use Obj.readNestedProperty instead
*
* @param obj object
* @param keyPath key path list
*/
export const readNestedProperty = (obj: any, keyPath: Array<string>) => {
for (let index = 0; index < keyPath.length; index++) {
const key = keyPath[index];
if (index != keyPath.length - 1) {
if (!(key in obj)) {
return undefined;
}
obj = obj[key];
} else {
return obj[key];
}
}
return undefined;
};
/**
* Extract language tag
* @param value language string
*/
export const extractLanguageTag = (value?: string) => {
if (value) {
if (value.indexOf("-") != -1) {
return value?.split("-")[0];
} else if (value.indexOf("_") != -1) {
return value?.split("_")[0];
} else {
return "";
}
} else {
return "";
}
};
/**
* Check if the locale string is valid
* @param locale locale
*/
export const isLocaleValid = (locale?: string) => {
if (locale !== null && locale !== undefined && locale.length != 0) {
let parts = locale.split(/[_-]/);
if (parts.length != 2) {
return false;
} else {
for (let index = 0; index < parts.length; index++) {
const tag = parts[index];
if (tag.length != 2) {
return false;
}
}
return true;
}
} else {
return false;
}
};
/**
* Check required keys
* @param attrs object attributes
* @param target object
* @deprecated use Obj.missingKeys instead
*/
export function checkRequiredKeys<T, K = keyof T>(attrs: K[], target: T): K[] {
const r: K[] = [];
for (const attr of attrs) {
const element = (target as any)[attr];
if (!element || (typeof element === "string" && element.length === 0)) {
r.push(attr);
}
}
return r;
}
| 22.56962 | 79 | 0.594504 | 92 | 10 | 0 | 17 | 19 | 0 | 0 | 7 | 9 | 0 | 2 | 6.4 | 1,005 | 0.026866 | 0.018905 | 0 | 0 | 0.00199 | 0.152174 | 0.195652 | 0.291706 | /**
* Get if the given value is null or undefined
* @param value input
*/
export const isFilled = (value) => {
return value !== null && value !== undefined;
};
/**
* Get if the given value is null or undefined and length > 0
* @param value input
*/
export const isQueryParamFilled = (value) => {
return value !== null && value !== undefined && `${value}`.length !== 0;
};
/**
* Return 0 if the number in NaN and the number if not
* @param value number
*/
export const forceNumber = (value) => {
const num = Number(value);
return isNaN(num) ? 0 : num;
};
/**
* Assign nested property in object
*
* @deprecated use Obj.assignNestedProperty instead
*
* @param obj object
* @param keyPath key path list
* @param value value to assign
*/
export const assignNestedProperty = (
obj,
keyPath,
value
) => {
for (let index = 0; index < keyPath.length; index++) {
const key = keyPath[index];
if (index != keyPath.length - 1) {
if (!(key in obj)) {
obj[key] = {};
}
obj = obj[key];
} else {
obj[key] = value;
}
}
};
/**
* Remove all white spaces in string
* @param value string
* @param replacement string that will replace the space
*/
export const removeAllWhiteSpaces = (value, replacement?) => {
return value.replace(/\s/g, replacement || "");
};
/**
* Replace all occurences of a searched string in another string
*
* @param value target string
* @param search element to replace
* @param replacement replacement
*/
export const replaceAllMatch = (
value,
search,
replacement
) => {
return value.replace(search, replacement);
};
/**
* Return a value of a nested property (last key in the given path)
*
* @deprecated use Obj.readNestedProperty instead
*
* @param obj object
* @param keyPath key path list
*/
export const readNestedProperty = (obj, keyPath) => {
for (let index = 0; index < keyPath.length; index++) {
const key = keyPath[index];
if (index != keyPath.length - 1) {
if (!(key in obj)) {
return undefined;
}
obj = obj[key];
} else {
return obj[key];
}
}
return undefined;
};
/**
* Extract language tag
* @param value language string
*/
export const extractLanguageTag = (value?) => {
if (value) {
if (value.indexOf("-") != -1) {
return value?.split("-")[0];
} else if (value.indexOf("_") != -1) {
return value?.split("_")[0];
} else {
return "";
}
} else {
return "";
}
};
/**
* Check if the locale string is valid
* @param locale locale
*/
export const isLocaleValid = (locale?) => {
if (locale !== null && locale !== undefined && locale.length != 0) {
let parts = locale.split(/[_-]/);
if (parts.length != 2) {
return false;
} else {
for (let index = 0; index < parts.length; index++) {
const tag = parts[index];
if (tag.length != 2) {
return false;
}
}
return true;
}
} else {
return false;
}
};
/**
* Check required keys
* @param attrs object attributes
* @param target object
* @deprecated use Obj.missingKeys instead
*/
export function checkRequiredKeys<T, K = keyof T>(attrs, target) {
const r = [];
for (const attr of attrs) {
const element = (target as any)[attr];
if (!element || (typeof element === "string" && element.length === 0)) {
r.push(attr);
}
}
return r;
}
|
7363963d6c6296f85899573195a6a4eeb5571846 | 2,615 | ts | TypeScript | src/query-date.ts | AntonKhorev/osm-note-viewer | 05e5132983c6ea41735e05248141403df711b122 | [
"MIT"
] | 3 | 2022-03-23T10:12:53.000Z | 2022-03-29T04:17:40.000Z | src/query-date.ts | AntonKhorev/osm-note-viewer | 05e5132983c6ea41735e05248141403df711b122 | [
"MIT"
] | null | null | null | src/query-date.ts | AntonKhorev/osm-note-viewer | 05e5132983c6ea41735e05248141403df711b122 | [
"MIT"
] | null | null | null | export interface ValidDateQuery {
dateType: 'valid'
date: number
}
export interface InvalidDateQuery {
dateType: 'invalid'
message: string
}
export interface EmptyDateQuery {
dateType: 'empty'
}
export type DateQuery = ValidDateQuery | InvalidDateQuery | EmptyDateQuery
export function toReadableDate(date: number | undefined): string {
if (date==null) return ''
const pad=(n: number): string => ('0'+n).slice(-2)
const dateObject=new Date(date*1000)
const dateString=
dateObject.getUTCFullYear()+
'-'+
pad(dateObject.getUTCMonth()+1)+
'-'+
pad(dateObject.getUTCDate())+
' '+
pad(dateObject.getUTCHours())+
':'+
pad(dateObject.getUTCMinutes())+
':'+
pad(dateObject.getUTCSeconds())
return dateString
}
export function toUrlDate(date: number): string {
const pad=(n: number): string => ('0'+n).slice(-2)
const dateObject=new Date(date*1000)
const dateString=
dateObject.getUTCFullYear()+
pad(dateObject.getUTCMonth()+1)+
pad(dateObject.getUTCDate())+
'T'+
pad(dateObject.getUTCHours())+
pad(dateObject.getUTCMinutes())+
pad(dateObject.getUTCSeconds())+
'Z'
return dateString
}
export function toDateQuery(readableDate: string): DateQuery {
let s=readableDate.trim()
let m=''
let r=''
{
if (s=='') return empty()
const match=s.match(/^((\d\d\d\d)-?)(.*)/)
if (!match) return invalid()
next(match)
}{
if (s=='') return complete()
const match=s.match(/^((\d\d)-?)(.*)/)
if (!match) return invalid()
r+='-'
next(match)
}{
if (s=='') return complete()
const match=s.match(/^((\d\d)[T ]?)(.*)/)
if (!match) return invalid()
r+='-'
next(match)
}{
if (s=='') return complete()
const match=s.match(/^((\d\d):?)(.*)/)
if (!match) return invalid()
r+=' '
next(match)
}{
if (s=='') return complete()
const match=s.match(/^((\d\d):?)(.*)/)
if (!match) return invalid()
r+=':'
next(match)
}{
if (s=='') return complete()
const match=s.match(/^((\d\d)Z?)$/)
if (!match) return invalid()
r+=':'
next(match)
}
return complete()
function next(match: RegExpMatchArray): void {
m+=match[1]
r+=match[2]
s=match[3]
}
function empty(): EmptyDateQuery {
return {
dateType: 'empty'
}
}
function invalid(): InvalidDateQuery {
let message=`invalid date string`
if (m!='') message+=` after ${m}`
return {
dateType: 'invalid',
message
}
}
function complete(): ValidDateQuery {
const completionTemplate='2000-01-01 00:00:00Z'
const completedReadableDate=r+completionTemplate.slice(r.length)
return {
dateType: 'valid',
date: Date.parse(completedReadableDate)/1000
}
}
}
| 21.97479 | 74 | 0.640153 | 112 | 9 | 0 | 6 | 18 | 5 | 5 | 0 | 12 | 4 | 0 | 12.666667 | 950 | 0.015789 | 0.018947 | 0.005263 | 0.004211 | 0 | 0 | 0.315789 | 0.276584 | export interface ValidDateQuery {
dateType
date
}
export interface InvalidDateQuery {
dateType
message
}
export interface EmptyDateQuery {
dateType
}
export type DateQuery = ValidDateQuery | InvalidDateQuery | EmptyDateQuery
export function toReadableDate(date) {
if (date==null) return ''
/* Example usages of 'pad' are shown below:
dateObject.getUTCFullYear() +
'-' +
pad(dateObject.getUTCMonth() + 1) +
'-' +
pad(dateObject.getUTCDate()) +
' ' +
pad(dateObject.getUTCHours()) +
':' +
pad(dateObject.getUTCMinutes()) +
':' +
pad(dateObject.getUTCSeconds());
dateObject.getUTCFullYear() +
pad(dateObject.getUTCMonth() + 1) +
pad(dateObject.getUTCDate()) +
'T' +
pad(dateObject.getUTCHours()) +
pad(dateObject.getUTCMinutes()) +
pad(dateObject.getUTCSeconds()) +
'Z';
*/
/* Example usages of 'pad' are shown below:
dateObject.getUTCFullYear() +
'-' +
pad(dateObject.getUTCMonth() + 1) +
'-' +
pad(dateObject.getUTCDate()) +
' ' +
pad(dateObject.getUTCHours()) +
':' +
pad(dateObject.getUTCMinutes()) +
':' +
pad(dateObject.getUTCSeconds());
dateObject.getUTCFullYear() +
pad(dateObject.getUTCMonth() + 1) +
pad(dateObject.getUTCDate()) +
'T' +
pad(dateObject.getUTCHours()) +
pad(dateObject.getUTCMinutes()) +
pad(dateObject.getUTCSeconds()) +
'Z';
*/
const pad=(n) => ('0'+n).slice(-2)
const dateObject=new Date(date*1000)
const dateString=
dateObject.getUTCFullYear()+
'-'+
pad(dateObject.getUTCMonth()+1)+
'-'+
pad(dateObject.getUTCDate())+
' '+
pad(dateObject.getUTCHours())+
':'+
pad(dateObject.getUTCMinutes())+
':'+
pad(dateObject.getUTCSeconds())
return dateString
}
export function toUrlDate(date) {
/* Example usages of 'pad' are shown below:
dateObject.getUTCFullYear() +
'-' +
pad(dateObject.getUTCMonth() + 1) +
'-' +
pad(dateObject.getUTCDate()) +
' ' +
pad(dateObject.getUTCHours()) +
':' +
pad(dateObject.getUTCMinutes()) +
':' +
pad(dateObject.getUTCSeconds());
dateObject.getUTCFullYear() +
pad(dateObject.getUTCMonth() + 1) +
pad(dateObject.getUTCDate()) +
'T' +
pad(dateObject.getUTCHours()) +
pad(dateObject.getUTCMinutes()) +
pad(dateObject.getUTCSeconds()) +
'Z';
*/
/* Example usages of 'pad' are shown below:
dateObject.getUTCFullYear() +
'-' +
pad(dateObject.getUTCMonth() + 1) +
'-' +
pad(dateObject.getUTCDate()) +
' ' +
pad(dateObject.getUTCHours()) +
':' +
pad(dateObject.getUTCMinutes()) +
':' +
pad(dateObject.getUTCSeconds());
dateObject.getUTCFullYear() +
pad(dateObject.getUTCMonth() + 1) +
pad(dateObject.getUTCDate()) +
'T' +
pad(dateObject.getUTCHours()) +
pad(dateObject.getUTCMinutes()) +
pad(dateObject.getUTCSeconds()) +
'Z';
*/
const pad=(n) => ('0'+n).slice(-2)
const dateObject=new Date(date*1000)
const dateString=
dateObject.getUTCFullYear()+
pad(dateObject.getUTCMonth()+1)+
pad(dateObject.getUTCDate())+
'T'+
pad(dateObject.getUTCHours())+
pad(dateObject.getUTCMinutes())+
pad(dateObject.getUTCSeconds())+
'Z'
return dateString
}
export function toDateQuery(readableDate) {
let s=readableDate.trim()
let m=''
let r=''
{
if (s=='') return empty()
const match=s.match(/^((\d\d\d\d)-?)(.*)/)
if (!match) return invalid()
next(match)
}{
if (s=='') return complete()
const match=s.match(/^((\d\d)-?)(.*)/)
if (!match) return invalid()
r+='-'
next(match)
}{
if (s=='') return complete()
const match=s.match(/^((\d\d)[T ]?)(.*)/)
if (!match) return invalid()
r+='-'
next(match)
}{
if (s=='') return complete()
const match=s.match(/^((\d\d):?)(.*)/)
if (!match) return invalid()
r+=' '
next(match)
}{
if (s=='') return complete()
const match=s.match(/^((\d\d):?)(.*)/)
if (!match) return invalid()
r+=':'
next(match)
}{
if (s=='') return complete()
const match=s.match(/^((\d\d)Z?)$/)
if (!match) return invalid()
r+=':'
next(match)
}
return complete()
/* Example usages of 'next' are shown below:
next(match);
*/
function next(match) {
m+=match[1]
r+=match[2]
s=match[3]
}
/* Example usages of 'empty' are shown below:
empty();
*/
function empty() {
return {
dateType: 'empty'
}
}
/* Example usages of 'invalid' are shown below:
invalid();
*/
function invalid() {
let message=`invalid date string`
if (m!='') message+=` after ${m}`
return {
dateType: 'invalid',
message
}
}
/* Example usages of 'complete' are shown below:
complete();
*/
function complete() {
const completionTemplate='2000-01-01 00:00:00Z'
const completedReadableDate=r+completionTemplate.slice(r.length)
return {
dateType: 'valid',
date: Date.parse(completedReadableDate)/1000
}
}
}
|
73989c7524dd1d6034870357058ec12a0bd62470 | 2,090 | ts | TypeScript | typescript/bowling/bowling.ts | ndrewnee/exercism-solutions | a203d9e3167fa6e40ecb5671e06e7eae02f5f2fb | [
"MIT"
] | null | null | null | typescript/bowling/bowling.ts | ndrewnee/exercism-solutions | a203d9e3167fa6e40ecb5671e06e7eae02f5f2fb | [
"MIT"
] | 10 | 2022-03-29T18:08:35.000Z | 2022-03-29T18:08:38.000Z | typescript/bowling/bowling.ts | ndrewnee/exercism-solutions | a203d9e3167fa6e40ecb5671e06e7eae02f5f2fb | [
"MIT"
] | null | null | null | export default class Bowling {
constructor(private rolls: number[] = []) {}
score(): number {
let total = 0
let frame = 1
let isFirstBall = true
let hasExtraRolls = false
for (let i = 0; i < this.rolls.length && frame <= 10; i++) {
const current = this.rolls[i]
const next1 = this.rolls[i + 1]
const next2 = this.rolls[i + 2]
const twoBallsSum = current + next1
const isStrike = isFirstBall && current === 10
const isSpare = isFirstBall && twoBallsSum === 10
if (current < 0 || current > 10) {
throw new Error('Pins must have a value from 0 to 10')
}
if (isStrike) {
if (next1 === undefined || next2 === undefined) {
throw new Error('Score cannot be taken until the end of the game')
}
// Bonus can't be greater than 10 without strike in the first extra roll.
if (next1 + next2 > 10 && next1 !== 10) {
throw new Error('Pin count exceeds pins on the lane')
}
total += current + next1 + next2
hasExtraRolls = frame === 10 // The last frame strike has extra rolls.
frame++
continue
}
if (isFirstBall && twoBallsSum > 10) {
throw new Error('Pin count exceeds pins on the lane')
}
if (isSpare) {
if (next2 === undefined) {
throw new Error('Score cannot be taken until the end of the game')
}
total += current + next1 + next2
hasExtraRolls = frame === 10 // The last frame spare has extra rolls.
frame++
i++ // Skip second ball.
continue
}
frame = isFirstBall ? frame : frame + 1 // Increase frame only after second ball.
total += current
isFirstBall = !isFirstBall
}
if (frame < 10) {
throw new Error('Score cannot be taken until the end of the game')
}
// Can't have more than 20 rolls without extra rolls.
if (!hasExtraRolls && this.rolls.length > 20) {
throw new Error('Should not be able to roll after game is over')
}
return total
}
}
| 29.43662 | 87 | 0.572727 | 55 | 2 | 0 | 1 | 11 | 0 | 0 | 0 | 2 | 1 | 0 | 25 | 568 | 0.005282 | 0.019366 | 0 | 0.001761 | 0 | 0 | 0.142857 | 0.248401 | export default class Bowling {
constructor(private rolls = []) {}
score() {
let total = 0
let frame = 1
let isFirstBall = true
let hasExtraRolls = false
for (let i = 0; i < this.rolls.length && frame <= 10; i++) {
const current = this.rolls[i]
const next1 = this.rolls[i + 1]
const next2 = this.rolls[i + 2]
const twoBallsSum = current + next1
const isStrike = isFirstBall && current === 10
const isSpare = isFirstBall && twoBallsSum === 10
if (current < 0 || current > 10) {
throw new Error('Pins must have a value from 0 to 10')
}
if (isStrike) {
if (next1 === undefined || next2 === undefined) {
throw new Error('Score cannot be taken until the end of the game')
}
// Bonus can't be greater than 10 without strike in the first extra roll.
if (next1 + next2 > 10 && next1 !== 10) {
throw new Error('Pin count exceeds pins on the lane')
}
total += current + next1 + next2
hasExtraRolls = frame === 10 // The last frame strike has extra rolls.
frame++
continue
}
if (isFirstBall && twoBallsSum > 10) {
throw new Error('Pin count exceeds pins on the lane')
}
if (isSpare) {
if (next2 === undefined) {
throw new Error('Score cannot be taken until the end of the game')
}
total += current + next1 + next2
hasExtraRolls = frame === 10 // The last frame spare has extra rolls.
frame++
i++ // Skip second ball.
continue
}
frame = isFirstBall ? frame : frame + 1 // Increase frame only after second ball.
total += current
isFirstBall = !isFirstBall
}
if (frame < 10) {
throw new Error('Score cannot be taken until the end of the game')
}
// Can't have more than 20 rolls without extra rolls.
if (!hasExtraRolls && this.rolls.length > 20) {
throw new Error('Should not be able to roll after game is over')
}
return total
}
}
|
73ead2d9a1a65a4316d158456d15a7231b6f972f | 3,203 | ts | TypeScript | src/utils/index.ts | poly-state/poly-state | 635c404faee5cd4a970c585d23a7905b64c03fb8 | [
"MIT"
] | 10 | 2022-01-14T20:29:07.000Z | 2022-03-31T05:18:53.000Z | src/utils/index.ts | poly-state/poly-state | 635c404faee5cd4a970c585d23a7905b64c03fb8 | [
"MIT"
] | 12 | 2022-02-21T04:00:15.000Z | 2022-03-13T18:14:05.000Z | src/utils/index.ts | poly-state/poly-state | 635c404faee5cd4a970c585d23a7905b64c03fb8 | [
"MIT"
] | 2 | 2022-02-21T05:30:51.000Z | 2022-03-02T09:44:07.000Z | /* eslint-disable @typescript-eslint/no-explicit-any */
export const capitalize = (str: string) => `${str.charAt(0).toUpperCase()}${str.substring(1)}`;
export const deleteFromArray = <T>(array: T[], item: T): T[] => {
const index = array.indexOf(item);
if (index > -1) {
array.splice(index, 1);
}
return array;
};
function isObject(obj: any): obj is Record<any, any> {
return obj != null && obj.constructor.name === 'Object';
}
function isDateObject(obj: any): obj is Date {
return obj != null && obj.constructor.name === 'Date';
}
export function isEqualArray(a: any[], b: any[]) {
if (a.length !== b.length) {
return false;
}
for (let i = 0; i < a.length; i++) {
if (Array.isArray(a[i]) && Array.isArray(b[i])) {
const isEqual = isEqualArray(a[i], b[i]);
if (!isEqual) {
return false;
}
continue;
}
if (isObject(a[i]) && isObject(b[i])) {
const isEqual = isEqualObject(a[i], b[i]);
if (!isEqual) {
return false;
}
continue;
}
if (isDateObject(a[i]) && isDateObject(b[i])) {
const isEqual = isEqualDate(a[i], b[i]);
if (!isEqual) {
return false;
}
continue;
}
if (a[i] !== b[i]) {
return false;
}
}
return true;
}
function isEqualDate(a: Date, b: Date) {
return a.getTime() === b.getTime();
}
function isEqualObject(a: Record<any, any>, b: Record<any, any>) {
const aKeys = Object.keys(a);
const bKeys = Object.keys(b);
if (aKeys.length !== bKeys.length) {
return false;
}
for (const key of aKeys) {
if (Array.isArray(a[key]) && Array.isArray(b[key])) {
const isEqual = isEqualArray(a[key], b[key]);
if (!isEqual) {
return false;
}
continue;
}
if (isObject(a[key]) && isObject(b[key])) {
const isEqual = isEqualObject(a[key], b[key]);
if (!isEqual) {
return false;
}
continue;
}
if (isDateObject(a[key]) && isDateObject(b[key])) {
const isEqual = isEqualDate(a[key], b[key]);
if (!isEqual) {
return false;
}
continue;
}
if (a[key] !== b[key]) {
return false;
}
}
return true;
}
export const isEqual = (a: unknown, b: unknown): boolean => {
if (a instanceof Date && b instanceof Date) return a.getTime() === b.getTime();
if (Array.isArray(a) && Array.isArray(b)) {
return isEqualArray(a, b);
}
if (isObject(a) && isObject(b)) {
return isEqualObject(a, b);
}
if (a === b) return true;
return false;
};
export const getStoreIdentifier = (name: string) => {
if (name !== '') return name;
//generate a random name
const randomName =
Math.random().toString(36).substring(2, 15) + Math.random().toString(36).substring(2, 15);
return `STORE_${randomName}`;
};
export const deepClone = <T>(a: T): T => {
if (Array.isArray(a)) {
return a.map(deepClone) as unknown as T;
}
if (isObject(a)) {
const b: Record<any, any> = {};
for (const key in a) {
b[key] = deepClone(a[key]);
}
return b as unknown as T;
}
return a as unknown as T;
};
export const isFunction = (obj: any): obj is CallableFunction => {
return typeof obj === 'function';
};
| 21.353333 | 96 | 0.571027 | 116 | 11 | 0 | 16 | 18 | 0 | 6 | 13 | 8 | 0 | 9 | 8.727273 | 1,118 | 0.02415 | 0.0161 | 0 | 0 | 0.00805 | 0.288889 | 0.177778 | 0.274662 | /* eslint-disable @typescript-eslint/no-explicit-any */
export const capitalize = (str) => `${str.charAt(0).toUpperCase()}${str.substring(1)}`;
export const deleteFromArray = <T>(array, item) => {
const index = array.indexOf(item);
if (index > -1) {
array.splice(index, 1);
}
return array;
};
/* Example usages of 'isObject' are shown below:
isObject(a[i]) && isObject(b[i]);
isObject(a[key]) && isObject(b[key]);
isObject(a) && isObject(b);
isObject(a);
*/
function isObject(obj): obj is Record<any, any> {
return obj != null && obj.constructor.name === 'Object';
}
/* Example usages of 'isDateObject' are shown below:
isDateObject(a[i]) && isDateObject(b[i]);
isDateObject(a[key]) && isDateObject(b[key]);
*/
function isDateObject(obj): obj is Date {
return obj != null && obj.constructor.name === 'Date';
}
export /* Example usages of 'isEqualArray' are shown below:
isEqualArray(a[i], b[i]);
isEqualArray(a[key], b[key]);
isEqualArray(a, b);
*/
function isEqualArray(a, b) {
if (a.length !== b.length) {
return false;
}
for (let i = 0; i < a.length; i++) {
if (Array.isArray(a[i]) && Array.isArray(b[i])) {
const isEqual = isEqualArray(a[i], b[i]);
if (!isEqual) {
return false;
}
continue;
}
if (isObject(a[i]) && isObject(b[i])) {
const isEqual = isEqualObject(a[i], b[i]);
if (!isEqual) {
return false;
}
continue;
}
if (isDateObject(a[i]) && isDateObject(b[i])) {
const isEqual = isEqualDate(a[i], b[i]);
if (!isEqual) {
return false;
}
continue;
}
if (a[i] !== b[i]) {
return false;
}
}
return true;
}
/* Example usages of 'isEqualDate' are shown below:
isEqualDate(a[i], b[i]);
isEqualDate(a[key], b[key]);
*/
function isEqualDate(a, b) {
return a.getTime() === b.getTime();
}
/* Example usages of 'isEqualObject' are shown below:
isEqualObject(a[i], b[i]);
isEqualObject(a[key], b[key]);
isEqualObject(a, b);
*/
function isEqualObject(a, b) {
const aKeys = Object.keys(a);
const bKeys = Object.keys(b);
if (aKeys.length !== bKeys.length) {
return false;
}
for (const key of aKeys) {
if (Array.isArray(a[key]) && Array.isArray(b[key])) {
const isEqual = isEqualArray(a[key], b[key]);
if (!isEqual) {
return false;
}
continue;
}
if (isObject(a[key]) && isObject(b[key])) {
const isEqual = isEqualObject(a[key], b[key]);
if (!isEqual) {
return false;
}
continue;
}
if (isDateObject(a[key]) && isDateObject(b[key])) {
const isEqual = isEqualDate(a[key], b[key]);
if (!isEqual) {
return false;
}
continue;
}
if (a[key] !== b[key]) {
return false;
}
}
return true;
}
export /* Example usages of 'isEqual' are shown below:
var isEqual = isEqualArray(a[i], b[i]);
!isEqual;
var isEqual = isEqualObject(a[i], b[i]);
var isEqual = isEqualDate(a[i], b[i]);
var isEqual = isEqualArray(a[key], b[key]);
var isEqual = isEqualObject(a[key], b[key]);
var isEqual = isEqualDate(a[key], b[key]);
*/
const isEqual = (a, b) => {
if (a instanceof Date && b instanceof Date) return a.getTime() === b.getTime();
if (Array.isArray(a) && Array.isArray(b)) {
return isEqualArray(a, b);
}
if (isObject(a) && isObject(b)) {
return isEqualObject(a, b);
}
if (a === b) return true;
return false;
};
export const getStoreIdentifier = (name) => {
if (name !== '') return name;
//generate a random name
const randomName =
Math.random().toString(36).substring(2, 15) + Math.random().toString(36).substring(2, 15);
return `STORE_${randomName}`;
};
export /* Example usages of 'deepClone' are shown below:
a.map(deepClone);
b[key] = deepClone(a[key]);
*/
const deepClone = <T>(a) => {
if (Array.isArray(a)) {
return a.map(deepClone) as unknown as T;
}
if (isObject(a)) {
const b = {};
for (const key in a) {
b[key] = deepClone(a[key]);
}
return b as unknown as T;
}
return a as unknown as T;
};
export const isFunction = (obj): obj is CallableFunction => {
return typeof obj === 'function';
};
|
d8207be83f61bb1adfd772ea392fa6b08c1105e0 | 1,227 | ts | TypeScript | styles/constants.ts | VinciProtocol/vinci-ui | a8269c7cebfbe147618be490f4b90088108134cf | [
"MIT"
] | 1 | 2022-03-30T10:05:25.000Z | 2022-03-30T10:05:25.000Z | styles/constants.ts | VinciProtocol/vinci-ui | a8269c7cebfbe147618be490f4b90088108134cf | [
"MIT"
] | null | null | null | styles/constants.ts | VinciProtocol/vinci-ui | a8269c7cebfbe147618be490f4b90088108134cf | [
"MIT"
] | null | null | null | export const RESPONSIVE_DESIGN = {
display: {
XS: (display = 'block') => {
return {
display: {
xs: display,
sm: 'none',
md: 'none',
lg: 'none',
xl: 'none',
},
}
},
NEXS: (display = 'block') => {
return {
display: {
xs: 'none',
sm: display,
md: display,
lg: display,
xl: display,
},
}
},
LESM: (display = 'block') => {
return {
display: {
xs: display,
sm: display,
md: 'none',
lg: 'none',
xl: 'none',
},
}
},
GTSM: (display = 'block') => {
return {
display: {
xs: 'none',
sm: 'none',
md: display,
lg: display,
xl: display,
},
}
},
},
width: {
set: <T extends string>(xs: T, sm: T, md: T, lg: T, xl: T) => ({
width: {
xs,
sm,
md,
lg,
xl,
},
}),
LESM: (lesm: string, gemd: string) => ({
width: {
xs: lesm,
sm: lesm,
md: gemd,
lg: gemd,
xl: gemd,
},
}),
},
}
| 17.782609 | 68 | 0.334148 | 68 | 6 | 0 | 11 | 1 | 0 | 0 | 0 | 3 | 0 | 0 | 9 | 346 | 0.049133 | 0.00289 | 0 | 0 | 0 | 0 | 0.166667 | 0.294263 | export const RESPONSIVE_DESIGN = {
display: {
XS: (display = 'block') => {
return {
display: {
xs: display,
sm: 'none',
md: 'none',
lg: 'none',
xl: 'none',
},
}
},
NEXS: (display = 'block') => {
return {
display: {
xs: 'none',
sm: display,
md: display,
lg: display,
xl: display,
},
}
},
LESM: (display = 'block') => {
return {
display: {
xs: display,
sm: display,
md: 'none',
lg: 'none',
xl: 'none',
},
}
},
GTSM: (display = 'block') => {
return {
display: {
xs: 'none',
sm: 'none',
md: display,
lg: display,
xl: display,
},
}
},
},
width: {
set: <T extends string>(xs, sm, md, lg, xl) => ({
width: {
xs,
sm,
md,
lg,
xl,
},
}),
LESM: (lesm, gemd) => ({
width: {
xs: lesm,
sm: lesm,
md: gemd,
lg: gemd,
xl: gemd,
},
}),
},
}
|
2c31ac9149f16e030306749f32588668642a2f12 | 2,057 | ts | TypeScript | app/firebase/parseJob.ts | ctrlup-io/for-developers | 26106b46f61fb91f3df14323d962712b7e4fb8d8 | [
"MIT"
] | null | null | null | app/firebase/parseJob.ts | ctrlup-io/for-developers | 26106b46f61fb91f3df14323d962712b7e4fb8d8 | [
"MIT"
] | 21 | 2022-03-03T16:58:02.000Z | 2022-03-28T10:41:56.000Z | app/firebase/parseJob.ts | ctrlup-io/for-developers | 26106b46f61fb91f3df14323d962712b7e4fb8d8 | [
"MIT"
] | null | null | null | export default function parseJob({ skills, seniorityLevels }) {
return ({
id,
title,
description,
seniorities: seniorityIds,
mainSkills: mainSkillIds,
completeSkills: completeSkillIds,
location,
remote,
startingDate,
}: Job) => {
const seniorities = findAll(seniorityLevels, seniorityIds) as Seniority[];
const mainSkills = findAll(skills, mainSkillIds) as Skill[];
const completeSkills = findAll(skills, completeSkillIds) as Skill[];
return {
id,
title,
description,
location,
remote,
startingDate,
experience: getExperienceRange(seniorities),
salary: getSalaryRange(seniorities),
mainSkills: getSkills(mainSkills),
completeSkills: getSkills(completeSkills),
};
};
}
function find(items: { id: string }[], id: string) {
return items.find((item) => item.id === id);
}
function findAll(items: { id: string }[], ids: string[] = []) {
return ids.map((id) => find(items, id));
}
function getSkills(skills: Skill[]) {
return skills.map((skill) => skill.name);
}
function getExperienceRange(seniorities: Seniority[]) {
return seniorities
.reduce(
(acc, seniority) => [
Math.min(seniority.experience.min, acc[0]),
Math.max(seniority.experience.max || seniority.experience.min, acc[1]),
],
[Infinity, 0]
)
.join(" - ");
}
function getSalaryRange(seniorities: Seniority[]) {
return seniorities
.reduce(
(acc, seniority) => [
Math.round(Math.min(seniority.salary.base, acc[0])),
Math.round(Math.max(seniority.salary.base, acc[1])),
],
[Infinity, 0]
)
.join(" - ");
}
type Skill = { id: string; name: string };
type Seniority = {
id: string;
experience: { max: number; min: number };
salary: { base: number };
};
export type Job = {
id: string;
title: string;
description: string;
seniorities: string[];
mainSkills: string[];
completeSkills: string[];
location: string;
remote: boolean;
startingDate: number;
};
| 23.918605 | 79 | 0.629558 | 77 | 12 | 0 | 16 | 3 | 14 | 5 | 0 | 19 | 3 | 3 | 6.166667 | 599 | 0.046745 | 0.005008 | 0.023372 | 0.005008 | 0.005008 | 0 | 0.422222 | 0.303861 | export default function parseJob({ skills, seniorityLevels }) {
return ({
id,
title,
description,
seniorities: seniorityIds,
mainSkills: mainSkillIds,
completeSkills: completeSkillIds,
location,
remote,
startingDate,
}) => {
const seniorities = findAll(seniorityLevels, seniorityIds) as Seniority[];
const mainSkills = findAll(skills, mainSkillIds) as Skill[];
const completeSkills = findAll(skills, completeSkillIds) as Skill[];
return {
id,
title,
description,
location,
remote,
startingDate,
experience: getExperienceRange(seniorities),
salary: getSalaryRange(seniorities),
mainSkills: getSkills(mainSkills),
completeSkills: getSkills(completeSkills),
};
};
}
/* Example usages of 'find' are shown below:
items.find((item) => item.id === id);
find(items, id);
*/
function find(items, id) {
return items.find((item) => item.id === id);
}
/* Example usages of 'findAll' are shown below:
findAll(seniorityLevels, seniorityIds);
findAll(skills, mainSkillIds);
findAll(skills, completeSkillIds);
*/
function findAll(items, ids = []) {
return ids.map((id) => find(items, id));
}
/* Example usages of 'getSkills' are shown below:
getSkills(mainSkills);
getSkills(completeSkills);
*/
function getSkills(skills) {
return skills.map((skill) => skill.name);
}
/* Example usages of 'getExperienceRange' are shown below:
getExperienceRange(seniorities);
*/
function getExperienceRange(seniorities) {
return seniorities
.reduce(
(acc, seniority) => [
Math.min(seniority.experience.min, acc[0]),
Math.max(seniority.experience.max || seniority.experience.min, acc[1]),
],
[Infinity, 0]
)
.join(" - ");
}
/* Example usages of 'getSalaryRange' are shown below:
getSalaryRange(seniorities);
*/
function getSalaryRange(seniorities) {
return seniorities
.reduce(
(acc, seniority) => [
Math.round(Math.min(seniority.salary.base, acc[0])),
Math.round(Math.max(seniority.salary.base, acc[1])),
],
[Infinity, 0]
)
.join(" - ");
}
type Skill = { id; name };
type Seniority = {
id;
experience;
salary;
};
export type Job = {
id;
title;
description;
seniorities;
mainSkills;
completeSkills;
location;
remote;
startingDate;
};
|
2cb59d73168b34abd1b1fdfe682092c10381edc8 | 2,228 | ts | TypeScript | packages/core/src/classes/query-string.class.ts | stanwmusic/builder | 339015e0bf7e1eafca4ad7a5e94483f5b283a7e0 | [
"MIT"
] | 1 | 2022-02-04T16:46:58.000Z | 2022-02-04T16:46:58.000Z | packages/core/src/classes/query-string.class.ts | stanwmusic/builder | 339015e0bf7e1eafca4ad7a5e94483f5b283a7e0 | [
"MIT"
] | null | null | null | packages/core/src/classes/query-string.class.ts | stanwmusic/builder | 339015e0bf7e1eafca4ad7a5e94483f5b283a7e0 | [
"MIT"
] | null | null | null | export type StringMap = Record<string, string>;
const PROPERTY_NAME_DENY_LIST = Object.freeze(['__proto__', 'prototype']);
// TODO: unit tests
export class QueryString {
static parseDeep(queryString: string) {
const obj = this.parse(queryString);
return this.deepen(obj);
}
static stringifyDeep(obj: any) {
const map = this.flatten(obj);
return this.stringify(map);
}
static parse(queryString: string): StringMap {
const query: StringMap = {};
const pairs = (queryString[0] === '?' ? queryString.substr(1) : queryString).split('&');
for (let i = 0; i < pairs.length; i++) {
const pair = pairs[i].split('=');
// TODO: node support?
try {
query[decodeURIComponent(pair[0])] = decodeURIComponent(pair[1] || '');
} catch (error) {
// Ignore malformed URI components
}
}
return query;
}
static stringify(map: StringMap) {
let str = '';
for (const key in map) {
if (map.hasOwnProperty(key)) {
const value = map[key];
if (str) {
str += '&';
}
str += encodeURIComponent(key) + '=' + encodeURIComponent(value);
}
}
return str;
}
static deepen(map: StringMap) {
// FIXME; Should be type Tree = Record<string, string | Tree>
// requires a typescript upgrade.
const output: any = Object.create(null);
for (const k in map) {
let t = output;
const parts = k.split('.');
const key = parts.pop()!;
for (const part of parts) {
assertAllowedPropertyName(part);
t = t[part] = t[part] || Object.create(null);
}
t[key] = map[k];
}
return output;
}
static flatten(obj: any, _current?: any, _res: any = {}): StringMap {
for (const key in obj) {
const value = obj[key];
const newKey = _current ? _current + '.' + key : key;
if (value && typeof value === 'object') {
this.flatten(value, newKey, _res);
} else {
_res[newKey] = value;
}
}
return _res;
}
}
function assertAllowedPropertyName(name: string): asserts name {
if (PROPERTY_NAME_DENY_LIST.indexOf(name) >= 0)
throw new Error(`Property name "${name}" is not allowed`);
}
| 27.170732 | 92 | 0.581688 | 67 | 7 | 0 | 9 | 15 | 0 | 5 | 5 | 5 | 2 | 1 | 7 | 606 | 0.026403 | 0.024752 | 0 | 0.0033 | 0.00165 | 0.16129 | 0.16129 | 0.316289 | export type StringMap = Record<string, string>;
const PROPERTY_NAME_DENY_LIST = Object.freeze(['__proto__', 'prototype']);
// TODO: unit tests
export class QueryString {
static parseDeep(queryString) {
const obj = this.parse(queryString);
return this.deepen(obj);
}
static stringifyDeep(obj) {
const map = this.flatten(obj);
return this.stringify(map);
}
static parse(queryString) {
const query = {};
const pairs = (queryString[0] === '?' ? queryString.substr(1) : queryString).split('&');
for (let i = 0; i < pairs.length; i++) {
const pair = pairs[i].split('=');
// TODO: node support?
try {
query[decodeURIComponent(pair[0])] = decodeURIComponent(pair[1] || '');
} catch (error) {
// Ignore malformed URI components
}
}
return query;
}
static stringify(map) {
let str = '';
for (const key in map) {
if (map.hasOwnProperty(key)) {
const value = map[key];
if (str) {
str += '&';
}
str += encodeURIComponent(key) + '=' + encodeURIComponent(value);
}
}
return str;
}
static deepen(map) {
// FIXME; Should be type Tree = Record<string, string | Tree>
// requires a typescript upgrade.
const output = Object.create(null);
for (const k in map) {
let t = output;
const parts = k.split('.');
const key = parts.pop()!;
for (const part of parts) {
assertAllowedPropertyName(part);
t = t[part] = t[part] || Object.create(null);
}
t[key] = map[k];
}
return output;
}
static flatten(obj, _current?, _res = {}) {
for (const key in obj) {
const value = obj[key];
const newKey = _current ? _current + '.' + key : key;
if (value && typeof value === 'object') {
this.flatten(value, newKey, _res);
} else {
_res[newKey] = value;
}
}
return _res;
}
}
/* Example usages of 'assertAllowedPropertyName' are shown below:
assertAllowedPropertyName(part);
*/
function assertAllowedPropertyName(name): asserts name {
if (PROPERTY_NAME_DENY_LIST.indexOf(name) >= 0)
throw new Error(`Property name "${name}" is not allowed`);
}
|
9409d8e1617cff432cb32227ae7eb2b8436b8fa7 | 2,638 | ts | TypeScript | solutions/day12.ts | GiyoMoon/aoc2021 | 83d7e9018ed3b628353bc9a0a37b70a1462ecd74 | [
"Unlicense"
] | null | null | null | solutions/day12.ts | GiyoMoon/aoc2021 | 83d7e9018ed3b628353bc9a0a37b70a1462ecd74 | [
"Unlicense"
] | 1 | 2022-02-03T11:04:17.000Z | 2022-02-03T11:04:17.000Z | solutions/day12.ts | GiyoMoon/aoc2021 | 83d7e9018ed3b628353bc9a0a37b70a1462ecd74 | [
"Unlicense"
] | null | null | null | export default class Day12 {
private _connections: string[][];
private _foundPaths: number[][][] = [];
public solve(input: string): { part1: any, part2: any; } {
this._connections = input.split('\n').map(line => line.split('-'));
const starts: number[][] = [];
this._connections.forEach((c, i) => {
if (c[0] === 'start') {
starts.push([i, 1]);
} else if (c[1] === 'start') {
starts.push([i, 0]);
}
});
starts.forEach(s => {
this._findPath([s], false);
});
const waysOutPart1 = this._foundPaths.length;
this._foundPaths = [];
starts.forEach(s => {
this._findPath([s], true);
});
const waysOutPart2 = this._foundPaths.length;
return { part1: waysOutPart1, part2: waysOutPart2 };
}
private _findPath(path: number[][], extraSmallCave: boolean) {
const lastPathIndex = path.length - 1;
this._connections.forEach((c, i) => {
if (
c[0] === this._connections[path[lastPathIndex][0]][path[lastPathIndex][1]] &&
c[1] !== 'end' &&
c[1] !== 'start' &&
(!path.some(p => c[1] === this._connections[p[0]][p[1]] && this._connections[p[0]][p[1]].match(/^[a-z]+$/)) ||
(path.filter(p => c[1] === this._connections[p[0]][p[1]] && this._connections[p[0]][p[1]].match(/^[a-z]+$/)).length === 1 && extraSmallCave))
) {
this._findPath([...path, [i, 1]], extraSmallCave && path.filter(p => c[1] === this._connections[p[0]][p[1]] && this._connections[p[0]][p[1]].match(/^[a-z]+$/)).length === 0);
} else if (
c[1] === this._connections[path[lastPathIndex][0]][path[lastPathIndex][1]] &&
c[0] !== 'end' &&
c[0] !== 'start' &&
(!path.some(p => c[0] === this._connections[p[0]][p[1]] && this._connections[p[0]][p[1]].match(/^[a-z]+$/)) ||
(path.filter(p => c[0] === this._connections[p[0]][p[1]] && this._connections[p[0]][p[1]].match(/^[a-z]+$/)).length === 1 && extraSmallCave))
) {
this._findPath([...path, [i, 0]], extraSmallCave && path.filter(p => c[0] === this._connections[p[0]][p[1]] && this._connections[p[0]][p[1]].match(/^[a-z]+$/)).length === 0);
}
});
let lastPath;
this._connections.forEach((c, i) => {
if (c[0] === 'end' && c[1] === this._connections[path[lastPathIndex][0]][path[lastPathIndex][1]]) {
lastPath = [i, 0];
} else if (c[1] === 'end' && c[0] === this._connections[path[lastPathIndex][0]][path[lastPathIndex][1]]) {
lastPath = [i, 1];
}
});
if (lastPath) {
path.push(lastPath);
this._foundPaths.push(path);
}
}
}
| 37.15493 | 182 | 0.525777 | 59 | 14 | 0 | 18 | 5 | 2 | 1 | 2 | 6 | 1 | 0 | 6.214286 | 890 | 0.035955 | 0.005618 | 0.002247 | 0.001124 | 0 | 0.051282 | 0.153846 | 0.273586 | export default class Day12 {
private _connections;
private _foundPaths = [];
public solve(input) {
this._connections = input.split('\n').map(line => line.split('-'));
const starts = [];
this._connections.forEach((c, i) => {
if (c[0] === 'start') {
starts.push([i, 1]);
} else if (c[1] === 'start') {
starts.push([i, 0]);
}
});
starts.forEach(s => {
this._findPath([s], false);
});
const waysOutPart1 = this._foundPaths.length;
this._foundPaths = [];
starts.forEach(s => {
this._findPath([s], true);
});
const waysOutPart2 = this._foundPaths.length;
return { part1: waysOutPart1, part2: waysOutPart2 };
}
private _findPath(path, extraSmallCave) {
const lastPathIndex = path.length - 1;
this._connections.forEach((c, i) => {
if (
c[0] === this._connections[path[lastPathIndex][0]][path[lastPathIndex][1]] &&
c[1] !== 'end' &&
c[1] !== 'start' &&
(!path.some(p => c[1] === this._connections[p[0]][p[1]] && this._connections[p[0]][p[1]].match(/^[a-z]+$/)) ||
(path.filter(p => c[1] === this._connections[p[0]][p[1]] && this._connections[p[0]][p[1]].match(/^[a-z]+$/)).length === 1 && extraSmallCave))
) {
this._findPath([...path, [i, 1]], extraSmallCave && path.filter(p => c[1] === this._connections[p[0]][p[1]] && this._connections[p[0]][p[1]].match(/^[a-z]+$/)).length === 0);
} else if (
c[1] === this._connections[path[lastPathIndex][0]][path[lastPathIndex][1]] &&
c[0] !== 'end' &&
c[0] !== 'start' &&
(!path.some(p => c[0] === this._connections[p[0]][p[1]] && this._connections[p[0]][p[1]].match(/^[a-z]+$/)) ||
(path.filter(p => c[0] === this._connections[p[0]][p[1]] && this._connections[p[0]][p[1]].match(/^[a-z]+$/)).length === 1 && extraSmallCave))
) {
this._findPath([...path, [i, 0]], extraSmallCave && path.filter(p => c[0] === this._connections[p[0]][p[1]] && this._connections[p[0]][p[1]].match(/^[a-z]+$/)).length === 0);
}
});
let lastPath;
this._connections.forEach((c, i) => {
if (c[0] === 'end' && c[1] === this._connections[path[lastPathIndex][0]][path[lastPathIndex][1]]) {
lastPath = [i, 0];
} else if (c[1] === 'end' && c[0] === this._connections[path[lastPathIndex][0]][path[lastPathIndex][1]]) {
lastPath = [i, 1];
}
});
if (lastPath) {
path.push(lastPath);
this._foundPaths.push(path);
}
}
}
|
9411bc35f0916e880babde2f1f971f7c4f02165d | 2,488 | ts | TypeScript | problemset/trapping-rain-water/index.ts | OUDUIDUI/leet-code | 50e61ce16d1c419ccefc075ae9ead721cdd1cdbb | [
"MIT"
] | 6 | 2022-01-17T03:19:56.000Z | 2022-01-17T05:45:39.000Z | problemset/trapping-rain-water/index.ts | OUDUIDUI/leet-code | 50e61ce16d1c419ccefc075ae9ead721cdd1cdbb | [
"MIT"
] | null | null | null | problemset/trapping-rain-water/index.ts | OUDUIDUI/leet-code | 50e61ce16d1c419ccefc075ae9ead721cdd1cdbb | [
"MIT"
] | null | null | null | /**
* 动态规划
* @desc 时间复杂度 O(N) 空间复杂度 O(N)
* @param height {number[]}
* @return {number}
*/
export function trap(height: number[]): number {
const len = height.length
if (!len) return 0
// 记录从左到右扫描的最大值数组
const leftMax: number[] = new Array(len).fill(0)
for (let i = 0; i < len; i++)
leftMax[i] = i === 0 ? height[i] : Math.max(leftMax[i - 1], height[i])
// 记录从右到左扫描的最大值数组
const rightMax = new Array(len).fill(0)
for (let i = len - 1; i >= 0; i--) {
rightMax[i]
= i === len - 1 ? height[i] : Math.max(rightMax[i + 1], height[i])
}
let ans = 0
// leftMax和rightMax重叠的区域减掉height[i]就是对应区域的接水量
for (let i = 0; i < len; i++)
ans += Math.min(leftMax[i], rightMax[i]) - height[i]
return ans
}
/**
* 单调栈
* @desc 时间复杂度 O(N) 空间复杂度 O(N)
* @param height {number[]}
* @return {number}
*/
export function trap2(height: number[]): number {
let ans = 0
const stack: number[] = []
for (let i = 0; i < height.length; i++) {
while (
stack.length
&& /* 栈有值 */ height[i]
> height[stack[stack.length - 1]] /* 当前高度比上一个高度高的话 */
) {
// 获取栈顶,并弹出
const top = stack.pop() as number
// 确保栈还有值
if (!stack.length) break
// 获取左边坐标
const left = stack[stack.length - 1] as number
// 计算出宽高
const w = i - left - 1
const h = Math.min(height[left], height[i]) - height[top]
ans += w * h
}
// 入栈
stack.push(i)
}
return ans
}
/**
* 双指针
* @desc 时间复杂度 O(N) 空间复杂度 O(1)
* @param height {number[]}
* @return {number}
*/
export function trap3(height: number[]): number {
let ans = 0
let left = 0
let right: number = height.length - 1
let leftMaxHeight = 0
let rightMaxHeight = 0
while (left < right) {
// 更新左右最大高度
leftMaxHeight = Math.max(leftMaxHeight, height[left])
rightMaxHeight = Math.max(rightMaxHeight, height[right])
if (height[left] < height[right]) {
// 当height[left] < height[right] 在动态规划中必有leftMax[left] < rightMax[left]
// 因此在动态规划中,此时的高度为 Math.min(leftMax[left], rightMax[left]) - height[left]
// 即 leftMaxHeight - height[left]
ans += leftMaxHeight - height[left]
left++
}
else {
// 同理,当height[left] >= height[right] 在动态规划中必有leftMax[right] >= rightMax[right]
// 因此在动态规划中,此时的高度为 Math.min(leftMax[right], rightMax[right]) - height[right]
// 即 rightMaxHeight - height[right]
ans += rightMaxHeight - height[right]
right--
}
}
return ans
}
| 23.923077 | 84 | 0.57918 | 56 | 3 | 0 | 3 | 19 | 0 | 0 | 0 | 11 | 0 | 2 | 16.666667 | 942 | 0.006369 | 0.02017 | 0 | 0 | 0.002123 | 0 | 0.44 | 0.249992 | /**
* 动态规划
* @desc 时间复杂度 O(N) 空间复杂度 O(N)
* @param height {number[]}
* @return {number}
*/
export function trap(height) {
const len = height.length
if (!len) return 0
// 记录从左到右扫描的最大值数组
const leftMax = new Array(len).fill(0)
for (let i = 0; i < len; i++)
leftMax[i] = i === 0 ? height[i] : Math.max(leftMax[i - 1], height[i])
// 记录从右到左扫描的最大值数组
const rightMax = new Array(len).fill(0)
for (let i = len - 1; i >= 0; i--) {
rightMax[i]
= i === len - 1 ? height[i] : Math.max(rightMax[i + 1], height[i])
}
let ans = 0
// leftMax和rightMax重叠的区域减掉height[i]就是对应区域的接水量
for (let i = 0; i < len; i++)
ans += Math.min(leftMax[i], rightMax[i]) - height[i]
return ans
}
/**
* 单调栈
* @desc 时间复杂度 O(N) 空间复杂度 O(N)
* @param height {number[]}
* @return {number}
*/
export function trap2(height) {
let ans = 0
const stack = []
for (let i = 0; i < height.length; i++) {
while (
stack.length
&& /* 栈有值 */ height[i]
> height[stack[stack.length - 1]] /* 当前高度比上一个高度高的话 */
) {
// 获取栈顶,并弹出
const top = stack.pop() as number
// 确保栈还有值
if (!stack.length) break
// 获取左边坐标
const left = stack[stack.length - 1] as number
// 计算出宽高
const w = i - left - 1
const h = Math.min(height[left], height[i]) - height[top]
ans += w * h
}
// 入栈
stack.push(i)
}
return ans
}
/**
* 双指针
* @desc 时间复杂度 O(N) 空间复杂度 O(1)
* @param height {number[]}
* @return {number}
*/
export function trap3(height) {
let ans = 0
let left = 0
let right = height.length - 1
let leftMaxHeight = 0
let rightMaxHeight = 0
while (left < right) {
// 更新左右最大高度
leftMaxHeight = Math.max(leftMaxHeight, height[left])
rightMaxHeight = Math.max(rightMaxHeight, height[right])
if (height[left] < height[right]) {
// 当height[left] < height[right] 在动态规划中必有leftMax[left] < rightMax[left]
// 因此在动态规划中,此时的高度为 Math.min(leftMax[left], rightMax[left]) - height[left]
// 即 leftMaxHeight - height[left]
ans += leftMaxHeight - height[left]
left++
}
else {
// 同理,当height[left] >= height[right] 在动态规划中必有leftMax[right] >= rightMax[right]
// 因此在动态规划中,此时的高度为 Math.min(leftMax[right], rightMax[right]) - height[right]
// 即 rightMaxHeight - height[right]
ans += rightMaxHeight - height[right]
right--
}
}
return ans
}
|
94219cd52f22c4e35141410a3dc16f62080e11da | 2,428 | ts | TypeScript | src/utils/linkedList.ts | Josh-McFarlin/remix-image | 088ec7aa78ed1b79ac4cd4891d5795df01f39864 | [
"MIT"
] | 57 | 2022-01-20T19:59:03.000Z | 2022-03-31T15:35:38.000Z | src/utils/linkedList.ts | Josh-McFarlin/remix-image | 088ec7aa78ed1b79ac4cd4891d5795df01f39864 | [
"MIT"
] | 3 | 2022-02-23T05:47:27.000Z | 2022-03-02T16:52:35.000Z | src/utils/linkedList.ts | Josh-McFarlin/remix-image | 088ec7aa78ed1b79ac4cd4891d5795df01f39864 | [
"MIT"
] | 4 | 2022-01-20T20:25:37.000Z | 2022-03-19T19:54:51.000Z | export class ListNode<T> {
value: T;
weight: number;
prev: ListNode<T> | null = null;
next: ListNode<T> | null = null;
constructor(
value: T,
weight: number,
prev: ListNode<T> | null = null,
next: ListNode<T> | null = null
) {
this.value = value;
this.weight = weight;
this.prev = prev;
this.next = next;
}
}
export class DoublyLinkedList<T> {
head: ListNode<T> | null = null;
tail: ListNode<T> | null = null;
size = 0;
peekHead(): T | undefined {
return this.head?.value;
}
peekTail(): T | undefined {
return this.tail?.value;
}
addHead(value: T, weight = 1): ListNode<T> {
const node = new ListNode(value, weight);
if (!this.head) {
this.head = node;
this.tail = node;
this.size = node.weight;
return node;
}
node.next = this.head;
this.head.prev = node;
this.head = node;
this.size += node.weight;
return node;
}
addTail(value: T, weight = 1): ListNode<T> {
const node = new ListNode(value, weight);
if (!this.tail) {
this.head = node;
this.tail = node;
this.size = node.weight;
return node;
}
node.prev = this.tail;
this.tail.next = node;
this.tail = node;
this.size += node.weight;
return node;
}
popHead(): T | null {
if (!this.head) {
return null;
}
const tmp = this.head.value;
this.size -= this.head.weight;
this.head = this.head.next;
if (this.head) {
this.head.prev = null;
}
return tmp;
}
popTail(): T | null {
if (!this.tail) {
return null;
}
const tmp = this.tail.value;
this.size -= this.tail.weight;
this.tail = this.tail.prev;
this.tail!.next = null;
return tmp;
}
removeNode(node: ListNode<T>): void {
if (!this.head) {
return;
}
this.size -= node.weight;
if (node.prev) {
node.prev.next = node.next;
if (node.next) {
node.next.prev = node.prev;
}
} else {
this.head = this.head.next;
if (this.tail === node) {
this.tail = this.head;
}
}
}
clear(): void {
this.head = null;
this.tail = null;
this.size = 0;
}
toString(): string {
const values = [];
let tmp = this.head;
while (tmp != null) {
values.push(tmp.value);
tmp = tmp.next;
}
return JSON.stringify(values);
}
}
| 17.467626 | 46 | 0.540774 | 109 | 10 | 0 | 9 | 6 | 7 | 0 | 0 | 5 | 2 | 0 | 7.3 | 752 | 0.025266 | 0.007979 | 0.009309 | 0.00266 | 0 | 0 | 0.15625 | 0.259319 | export class ListNode<T> {
value;
weight;
prev = null;
next = null;
constructor(
value,
weight,
prev = null,
next = null
) {
this.value = value;
this.weight = weight;
this.prev = prev;
this.next = next;
}
}
export class DoublyLinkedList<T> {
head = null;
tail = null;
size = 0;
peekHead() {
return this.head?.value;
}
peekTail() {
return this.tail?.value;
}
addHead(value, weight = 1) {
const node = new ListNode(value, weight);
if (!this.head) {
this.head = node;
this.tail = node;
this.size = node.weight;
return node;
}
node.next = this.head;
this.head.prev = node;
this.head = node;
this.size += node.weight;
return node;
}
addTail(value, weight = 1) {
const node = new ListNode(value, weight);
if (!this.tail) {
this.head = node;
this.tail = node;
this.size = node.weight;
return node;
}
node.prev = this.tail;
this.tail.next = node;
this.tail = node;
this.size += node.weight;
return node;
}
popHead() {
if (!this.head) {
return null;
}
const tmp = this.head.value;
this.size -= this.head.weight;
this.head = this.head.next;
if (this.head) {
this.head.prev = null;
}
return tmp;
}
popTail() {
if (!this.tail) {
return null;
}
const tmp = this.tail.value;
this.size -= this.tail.weight;
this.tail = this.tail.prev;
this.tail!.next = null;
return tmp;
}
removeNode(node) {
if (!this.head) {
return;
}
this.size -= node.weight;
if (node.prev) {
node.prev.next = node.next;
if (node.next) {
node.next.prev = node.prev;
}
} else {
this.head = this.head.next;
if (this.tail === node) {
this.tail = this.head;
}
}
}
clear() {
this.head = null;
this.tail = null;
this.size = 0;
}
toString() {
const values = [];
let tmp = this.head;
while (tmp != null) {
values.push(tmp.value);
tmp = tmp.next;
}
return JSON.stringify(values);
}
}
|
94257ef30c23f4cdedaf7f7b70d7116f9f5c08c6 | 3,645 | ts | TypeScript | src/utils/common.ts | AgainPsychoX/Stellaris-Save-API | 08b482ee15ea04fcecc971e60c1efa15da9779e8 | [
"MIT"
] | 1 | 2022-01-06T02:45:33.000Z | 2022-01-06T02:45:33.000Z | src/utils/common.ts | AgainPsychoX/Stellaris-Save-API | 08b482ee15ea04fcecc971e60c1efa15da9779e8 | [
"MIT"
] | null | null | null | src/utils/common.ts | AgainPsychoX/Stellaris-Save-API | 08b482ee15ea04fcecc971e60c1efa15da9779e8 | [
"MIT"
] | 1 | 2022-01-06T02:45:36.000Z | 2022-01-06T02:45:36.000Z |
export class MyError extends Error {
code: string;
inner?: any;
constructor(code: string, message?: string, inner?: any) {
super(message || code);
this.code = code;
this.inner = inner;
}
}
export const getLineAndColumn = (string: string, offset: number) => {
let line = 1;
let column = 1;
for (let j = 0; j < offset; j++) {
column += 1;
if (string.charCodeAt(j) === 10) {
line += 1;
column = 1;
}
}
return [line, column] as const;
}
export const getLinesRange = (
string: string,
options: {
prefixLineNumbers?: boolean
firstLine?: number,
lastLine?: number,
centerLine?: number,
radius?: number,
highlight?: { line: number, column?: number },
process?: (lineString: string, lineNumber: number) => string;
} = {}) => {
options = Object.assign({ prefixLineNumbers: false, radius: 2 }, options);
if (options.firstLine === undefined) {
if (options.centerLine === undefined) {
if (options.highlight) {
options.centerLine = options.highlight.line;
}
else {
throw new Error('no lines selected');
}
}
if (options.radius === undefined) {
options.radius = 2;
}
options.firstLine = options.centerLine - options.radius;
if (options.lastLine === undefined) {
options.lastLine = options.centerLine + options.radius;
}
}
if (options.firstLine <= 0) {
options.firstLine = 1;
}
let current = 0;
let currentLine = 1;
let selected: string[] = [];
while (true) {
const next = string.indexOf('\n', current);
if (next === -1) {
selected.push(string.substring(current));
break;
}
if (options.firstLine <= currentLine) {
selected.push(string.substring(current, next));
if (currentLine == options.lastLine) {
break;
}
}
currentLine += 1;
current = next + 1;
}
if (options.process) {
selected = selected.map((text, index) => options.process!(text, options.firstLine! + index));
}
let prefixWidth = 0;
if (options.prefixLineNumbers) {
const width = ('' + (options.firstLine + selected.length)).length;
prefixWidth = width + 2;
selected = selected.map((text, index) => `${('' + (options.firstLine! + index)).padStart(width)}: ${text}`);
}
if (options.highlight) {
const index = Math.max(options.highlight.line - options.firstLine, 0);
const insert = options.highlight.column
? '^'.padStart(prefixWidth + options.highlight.column)
: `${' '.repeat(prefixWidth)}${'^'.repeat(38)}`
;
selected.splice(index + 1, 0, insert);
}
return selected;
}
export interface ParserErrorPoint {
offset: number;
comment?: string;
}
export class ParserError extends MyError {
path: string | undefined
content: string;
points: ParserErrorPoint[];
constructor(code: string, message: string, path: string | undefined, content: string, points?: ParserErrorPoint[], inner?: any) {
super(code, message, inner);
this.path = path;
this.content = content;
this.points = points || [];
// Make 'content' string not enumerable to hide it from debug printing,
// as it would be annoying (too long to read, only beginning visible).
Object.defineProperty(this, 'content', { enumerable: false });
}
override toString() {
return [this.message, ...this.points.map(p => {
const [line, column] = getLineAndColumn(this.content, p.offset);
return (
(this.path
? `${this.path}:${line}:${column} ${p.comment || ''}`
: (p.comment
? `${p.comment}\n`
: '\n'
)
) +
getLinesRange(this.content, {
prefixLineNumbers: true,
highlight: { line, column },
process: (line => line.replace(/ /g, '·').replace(/\t/g, '▹')),
}).join('\n')
);
})].join('\n');
}
}
| 26.413043 | 130 | 0.632922 | 125 | 9 | 0 | 19 | 14 | 7 | 2 | 3 | 25 | 3 | 1 | 12.222222 | 1,193 | 0.02347 | 0.011735 | 0.005868 | 0.002515 | 0.000838 | 0.061224 | 0.510204 | 0.266138 |
export class MyError extends Error {
code;
inner?;
constructor(code, message?, inner?) {
super(message || code);
this.code = code;
this.inner = inner;
}
}
export /* Example usages of 'getLineAndColumn' are shown below:
getLineAndColumn(this.content, p.offset);
*/
const getLineAndColumn = (string, offset) => {
let line = 1;
let column = 1;
for (let j = 0; j < offset; j++) {
column += 1;
if (string.charCodeAt(j) === 10) {
line += 1;
column = 1;
}
}
return [line, column] as const;
}
export /* Example usages of 'getLinesRange' are shown below:
(this.path
? `${this.path}:${line}:${column} ${p.comment || ''}`
: (p.comment
? `${p.comment}\n`
: '\n')) +
getLinesRange(this.content, {
prefixLineNumbers: true,
highlight: { line, column },
process: (line => line.replace(/ /g, '·').replace(/\t/g, '▹')),
}).join('\n');
*/
const getLinesRange = (
string,
options = {}) => {
options = Object.assign({ prefixLineNumbers: false, radius: 2 }, options);
if (options.firstLine === undefined) {
if (options.centerLine === undefined) {
if (options.highlight) {
options.centerLine = options.highlight.line;
}
else {
throw new Error('no lines selected');
}
}
if (options.radius === undefined) {
options.radius = 2;
}
options.firstLine = options.centerLine - options.radius;
if (options.lastLine === undefined) {
options.lastLine = options.centerLine + options.radius;
}
}
if (options.firstLine <= 0) {
options.firstLine = 1;
}
let current = 0;
let currentLine = 1;
let selected = [];
while (true) {
const next = string.indexOf('\n', current);
if (next === -1) {
selected.push(string.substring(current));
break;
}
if (options.firstLine <= currentLine) {
selected.push(string.substring(current, next));
if (currentLine == options.lastLine) {
break;
}
}
currentLine += 1;
current = next + 1;
}
if (options.process) {
selected = selected.map((text, index) => options.process!(text, options.firstLine! + index));
}
let prefixWidth = 0;
if (options.prefixLineNumbers) {
const width = ('' + (options.firstLine + selected.length)).length;
prefixWidth = width + 2;
selected = selected.map((text, index) => `${('' + (options.firstLine! + index)).padStart(width)}: ${text}`);
}
if (options.highlight) {
const index = Math.max(options.highlight.line - options.firstLine, 0);
const insert = options.highlight.column
? '^'.padStart(prefixWidth + options.highlight.column)
: `${' '.repeat(prefixWidth)}${'^'.repeat(38)}`
;
selected.splice(index + 1, 0, insert);
}
return selected;
}
export interface ParserErrorPoint {
offset;
comment?;
}
export class ParserError extends MyError {
path
content;
points;
constructor(code, message, path, content, points?, inner?) {
super(code, message, inner);
this.path = path;
this.content = content;
this.points = points || [];
// Make 'content' string not enumerable to hide it from debug printing,
// as it would be annoying (too long to read, only beginning visible).
Object.defineProperty(this, 'content', { enumerable: false });
}
override toString() {
return [this.message, ...this.points.map(p => {
const [line, column] = getLineAndColumn(this.content, p.offset);
return (
(this.path
? `${this.path}:${line}:${column} ${p.comment || ''}`
: (p.comment
? `${p.comment}\n`
: '\n'
)
) +
getLinesRange(this.content, {
prefixLineNumbers: true,
highlight: { line, column },
process: (line => line.replace(/ /g, '·').replace(/\t/g, '▹')),
}).join('\n')
);
})].join('\n');
}
}
|
94637b526e4fb25f8c58cc0dba0eae3fd70140ec | 7,624 | ts | TypeScript | projects/md5/src/lib/md5.helper.ts | Dikman/md5 | b9f3e1f3db8e5e22276fe42400500bee6d7a45d7 | [
"MIT"
] | null | null | null | projects/md5/src/lib/md5.helper.ts | Dikman/md5 | b9f3e1f3db8e5e22276fe42400500bee6d7a45d7 | [
"MIT"
] | 1 | 2022-03-02T06:59:20.000Z | 2022-03-02T06:59:20.000Z | projects/md5/src/lib/md5.helper.ts | Dikman/md5 | b9f3e1f3db8e5e22276fe42400500bee6d7a45d7 | [
"MIT"
] | null | null | null | /**
* Calculates MD5 from a given string
*
* @param str Source string whose checksum will be calculated
*/
export function md5(str: string): string {
function rotateLeft(value: number, shift: number): number {
return (value << shift) | (value >>> (32 - shift));
}
function addUnsigned(lX: number, lY: number): number {
const lX8 = lX & 0x80000000;
const lY8 = lY & 0x80000000;
const lX4 = lX & 0x40000000;
const lY4 = lY & 0x40000000;
const lResult = (lX & 0x3FFFFFFF) + (lY & 0x3FFFFFFF);
if (lX4 & lY4) {
return lResult ^ 0x80000000 ^ lX8 ^ lY8;
}
if (lX4 | lY4) {
if (lResult & 0x40000000) {
return lResult ^ 0xC0000000 ^ lX8 ^ lY8;
} else {
return lResult ^ 0x40000000 ^ lX8 ^ lY8;
}
}
return lResult ^ lX8 ^ lY8;
}
function f(x: number, y: number, z: number): number {
return (x & y) | (~x & z);
}
function g(x: number, y: number, z: number): number {
return (x & z) | (y & ~z);
}
function h(x: number, y: number, z: number): number {
return x ^ y ^ z;
}
function i(x: number, y: number, z: number): number {
return y ^ (x | ~z);
}
function ff(a: number, b: number, c: number, d: number, x: number, s: number, ac: number): number {
return addUnsigned(rotateLeft(addUnsigned(a, addUnsigned(addUnsigned(f(b, c, d), x), ac)), s), b);
}
function gg(a: number, b: number, c: number, d: number, x: number, s: number, ac: number): number {
return addUnsigned(rotateLeft(addUnsigned(a, addUnsigned(addUnsigned(g(b, c, d), x), ac)), s), b);
}
function hh(a: number, b: number, c: number, d: number, x: number, s: number, ac: number): number {
return addUnsigned(rotateLeft(addUnsigned(a, addUnsigned(addUnsigned(h(b, c, d), x), ac)), s), b);
}
function ii(a: number, b: number, c: number, d: number, x: number, s: number, ac: number): number {
return addUnsigned(rotateLeft(addUnsigned(a, addUnsigned(addUnsigned(i(b, c, d), x), ac)), s), b);
}
function strToWordArray(str: string): Array<number> {
const len = str.length;
const words = ((len + 8 - (len + 8) % 64) / 64 + 1) * 16;
const result = Array<number>(words - 1);
let count = 0;
while (count < len) {
const position = (count - (count % 4)) / 4;
const shift = (count % 4) * 8;
result[position] = result[position] | (str.charCodeAt(count++) << shift);
}
const position = (count - (count % 4)) / 4;
const shift = (count % 4) * 8;
result[position] = result[position] | (0x80 << shift);
result[words - 2] = len << 3;
result[words - 1] = len >>> 29;
return result;
}
function numToHex(value: number): string {
let result = '';
for (let idx = 0; idx < 4; idx++) {
const byte = (value >>> (idx * 8)) & 0xFF;
result += byte.toString(16).substr(-2).padStart(2, '0');
}
return result;
}
function utf8Encode(str: string): string {
str = str.replace(/\r\n/g, '\n');
const len = str.length;
let result = '';
for (let idx = 0; idx < len; idx++) {
const code = str.charCodeAt(idx);
if (code < 128) {
result += String.fromCharCode(code);
} else if ((code > 127) && (code < 2048)) {
result += String.fromCharCode((code >> 6) | 192);
result += String.fromCharCode((code & 63) | 128);
} else {
result += String.fromCharCode((code >> 12) | 224);
result += String.fromCharCode(((code >> 6) & 63) | 128);
result += String.fromCharCode((code & 63) | 128);
}
}
return result;
}
const S11 = 7;
const S12 = 12;
const S13 = 17;
const S14 = 22;
const S21 = 5;
const S22 = 9;
const S23 = 14;
const S24 = 20;
const S31 = 4;
const S32 = 11;
const S33 = 16;
const S34 = 23;
const S41 = 6;
const S42 = 10;
const S43 = 15;
const S44 = 21;
const x = strToWordArray(utf8Encode(str));
let a = 0x67452301;
let b = 0xEFCDAB89;
let c = 0x98BADCFE;
let d = 0x10325476;
for (let k = 0; k < x.length; k += 16) {
const AA = a;
const BB = b;
const CC = c;
const DD = d;
a = ff(a, b, c, d, x[k + 0], S11, 0xD76AA478);
d = ff(d, a, b, c, x[k + 1], S12, 0xE8C7B756);
c = ff(c, d, a, b, x[k + 2], S13, 0x242070DB);
b = ff(b, c, d, a, x[k + 3], S14, 0xC1BDCEEE);
a = ff(a, b, c, d, x[k + 4], S11, 0xF57C0FAF);
d = ff(d, a, b, c, x[k + 5], S12, 0x4787C62A);
c = ff(c, d, a, b, x[k + 6], S13, 0xA8304613);
b = ff(b, c, d, a, x[k + 7], S14, 0xFD469501);
a = ff(a, b, c, d, x[k + 8], S11, 0x698098D8);
d = ff(d, a, b, c, x[k + 9], S12, 0x8B44F7AF);
c = ff(c, d, a, b, x[k + 10], S13, 0xFFFF5BB1);
b = ff(b, c, d, a, x[k + 11], S14, 0x895CD7BE);
a = ff(a, b, c, d, x[k + 12], S11, 0x6B901122);
d = ff(d, a, b, c, x[k + 13], S12, 0xFD987193);
c = ff(c, d, a, b, x[k + 14], S13, 0xA679438E);
b = ff(b, c, d, a, x[k + 15], S14, 0x49B40821);
a = gg(a, b, c, d, x[k + 1], S21, 0xF61E2562);
d = gg(d, a, b, c, x[k + 6], S22, 0xC040B340);
c = gg(c, d, a, b, x[k + 11], S23, 0x265E5A51);
b = gg(b, c, d, a, x[k + 0], S24, 0xE9B6C7AA);
a = gg(a, b, c, d, x[k + 5], S21, 0xD62F105D);
d = gg(d, a, b, c, x[k + 10], S22, 0x2441453);
c = gg(c, d, a, b, x[k + 15], S23, 0xD8A1E681);
b = gg(b, c, d, a, x[k + 4], S24, 0xE7D3FBC8);
a = gg(a, b, c, d, x[k + 9], S21, 0x21E1CDE6);
d = gg(d, a, b, c, x[k + 14], S22, 0xC33707D6);
c = gg(c, d, a, b, x[k + 3], S23, 0xF4D50D87);
b = gg(b, c, d, a, x[k + 8], S24, 0x455A14ED);
a = gg(a, b, c, d, x[k + 13], S21, 0xA9E3E905);
d = gg(d, a, b, c, x[k + 2], S22, 0xFCEFA3F8);
c = gg(c, d, a, b, x[k + 7], S23, 0x676F02D9);
b = gg(b, c, d, a, x[k + 12], S24, 0x8D2A4C8A);
a = hh(a, b, c, d, x[k + 5], S31, 0xFFFA3942);
d = hh(d, a, b, c, x[k + 8], S32, 0x8771F681);
c = hh(c, d, a, b, x[k + 11], S33, 0x6D9D6122);
b = hh(b, c, d, a, x[k + 14], S34, 0xFDE5380C);
a = hh(a, b, c, d, x[k + 1], S31, 0xA4BEEA44);
d = hh(d, a, b, c, x[k + 4], S32, 0x4BDECFA9);
c = hh(c, d, a, b, x[k + 7], S33, 0xF6BB4B60);
b = hh(b, c, d, a, x[k + 10], S34, 0xBEBFBC70);
a = hh(a, b, c, d, x[k + 13], S31, 0x289B7EC6);
d = hh(d, a, b, c, x[k + 0], S32, 0xEAA127FA);
c = hh(c, d, a, b, x[k + 3], S33, 0xD4EF3085);
b = hh(b, c, d, a, x[k + 6], S34, 0x4881D05);
a = hh(a, b, c, d, x[k + 9], S31, 0xD9D4D039);
d = hh(d, a, b, c, x[k + 12], S32, 0xE6DB99E5);
c = hh(c, d, a, b, x[k + 15], S33, 0x1FA27CF8);
b = hh(b, c, d, a, x[k + 2], S34, 0xC4AC5665);
a = ii(a, b, c, d, x[k + 0], S41, 0xF4292244);
d = ii(d, a, b, c, x[k + 7], S42, 0x432AFF97);
c = ii(c, d, a, b, x[k + 14], S43, 0xAB9423A7);
b = ii(b, c, d, a, x[k + 5], S44, 0xFC93A039);
a = ii(a, b, c, d, x[k + 12], S41, 0x655B59C3);
d = ii(d, a, b, c, x[k + 3], S42, 0x8F0CCC92);
c = ii(c, d, a, b, x[k + 10], S43, 0xFFEFF47D);
b = ii(b, c, d, a, x[k + 1], S44, 0x85845DD1);
a = ii(a, b, c, d, x[k + 8], S41, 0x6FA87E4F);
d = ii(d, a, b, c, x[k + 15], S42, 0xFE2CE6E0);
c = ii(c, d, a, b, x[k + 6], S43, 0xA3014314);
b = ii(b, c, d, a, x[k + 13], S44, 0x4E0811A1);
a = ii(a, b, c, d, x[k + 4], S41, 0xF7537E82);
d = ii(d, a, b, c, x[k + 11], S42, 0xBD3AF235);
c = ii(c, d, a, b, x[k + 2], S43, 0x2AD7D2BB);
b = ii(b, c, d, a, x[k + 9], S44, 0xEB86D391);
a = addUnsigned(a, AA);
b = addUnsigned(b, BB);
c = addUnsigned(c, CC);
d = addUnsigned(d, DD);
}
return (numToHex(a) + numToHex(b) + numToHex(c) + numToHex(d)).toLowerCase();
}
| 33.585903 | 102 | 0.518625 | 187 | 14 | 0 | 48 | 46 | 0 | 13 | 0 | 63 | 0 | 0 | 17.714286 | 3,863 | 0.01605 | 0.011908 | 0 | 0 | 0 | 0 | 0.583333 | 0.249119 | /**
* Calculates MD5 from a given string
*
* @param str Source string whose checksum will be calculated
*/
export function md5(str) {
/* Example usages of 'rotateLeft' are shown below:
addUnsigned(rotateLeft(addUnsigned(a, addUnsigned(addUnsigned(f(b, c, d), x), ac)), s), b);
addUnsigned(rotateLeft(addUnsigned(a, addUnsigned(addUnsigned(g(b, c, d), x), ac)), s), b);
addUnsigned(rotateLeft(addUnsigned(a, addUnsigned(addUnsigned(h(b, c, d), x), ac)), s), b);
addUnsigned(rotateLeft(addUnsigned(a, addUnsigned(addUnsigned(i(b, c, d), x), ac)), s), b);
*/
function rotateLeft(value, shift) {
return (value << shift) | (value >>> (32 - shift));
}
/* Example usages of 'addUnsigned' are shown below:
addUnsigned(rotateLeft(addUnsigned(a, addUnsigned(addUnsigned(f(b, c, d), x), ac)), s), b);
addUnsigned(rotateLeft(addUnsigned(a, addUnsigned(addUnsigned(g(b, c, d), x), ac)), s), b);
addUnsigned(rotateLeft(addUnsigned(a, addUnsigned(addUnsigned(h(b, c, d), x), ac)), s), b);
addUnsigned(rotateLeft(addUnsigned(a, addUnsigned(addUnsigned(i(b, c, d), x), ac)), s), b);
a = addUnsigned(a, AA);
b = addUnsigned(b, BB);
c = addUnsigned(c, CC);
d = addUnsigned(d, DD);
*/
function addUnsigned(lX, lY) {
const lX8 = lX & 0x80000000;
const lY8 = lY & 0x80000000;
const lX4 = lX & 0x40000000;
const lY4 = lY & 0x40000000;
const lResult = (lX & 0x3FFFFFFF) + (lY & 0x3FFFFFFF);
if (lX4 & lY4) {
return lResult ^ 0x80000000 ^ lX8 ^ lY8;
}
if (lX4 | lY4) {
if (lResult & 0x40000000) {
return lResult ^ 0xC0000000 ^ lX8 ^ lY8;
} else {
return lResult ^ 0x40000000 ^ lX8 ^ lY8;
}
}
return lResult ^ lX8 ^ lY8;
}
/* Example usages of 'f' are shown below:
addUnsigned(rotateLeft(addUnsigned(a, addUnsigned(addUnsigned(f(b, c, d), x), ac)), s), b);
*/
function f(x, y, z) {
return (x & y) | (~x & z);
}
/* Example usages of 'g' are shown below:
addUnsigned(rotateLeft(addUnsigned(a, addUnsigned(addUnsigned(g(b, c, d), x), ac)), s), b);
*/
function g(x, y, z) {
return (x & z) | (y & ~z);
}
/* Example usages of 'h' are shown below:
addUnsigned(rotateLeft(addUnsigned(a, addUnsigned(addUnsigned(h(b, c, d), x), ac)), s), b);
*/
function h(x, y, z) {
return x ^ y ^ z;
}
/* Example usages of 'i' are shown below:
addUnsigned(rotateLeft(addUnsigned(a, addUnsigned(addUnsigned(i(b, c, d), x), ac)), s), b);
*/
function i(x, y, z) {
return y ^ (x | ~z);
}
/* Example usages of 'ff' are shown below:
a = ff(a, b, c, d, x[k + 0], S11, 0xD76AA478);
d = ff(d, a, b, c, x[k + 1], S12, 0xE8C7B756);
c = ff(c, d, a, b, x[k + 2], S13, 0x242070DB);
b = ff(b, c, d, a, x[k + 3], S14, 0xC1BDCEEE);
a = ff(a, b, c, d, x[k + 4], S11, 0xF57C0FAF);
d = ff(d, a, b, c, x[k + 5], S12, 0x4787C62A);
c = ff(c, d, a, b, x[k + 6], S13, 0xA8304613);
b = ff(b, c, d, a, x[k + 7], S14, 0xFD469501);
a = ff(a, b, c, d, x[k + 8], S11, 0x698098D8);
d = ff(d, a, b, c, x[k + 9], S12, 0x8B44F7AF);
c = ff(c, d, a, b, x[k + 10], S13, 0xFFFF5BB1);
b = ff(b, c, d, a, x[k + 11], S14, 0x895CD7BE);
a = ff(a, b, c, d, x[k + 12], S11, 0x6B901122);
d = ff(d, a, b, c, x[k + 13], S12, 0xFD987193);
c = ff(c, d, a, b, x[k + 14], S13, 0xA679438E);
b = ff(b, c, d, a, x[k + 15], S14, 0x49B40821);
*/
function ff(a, b, c, d, x, s, ac) {
return addUnsigned(rotateLeft(addUnsigned(a, addUnsigned(addUnsigned(f(b, c, d), x), ac)), s), b);
}
/* Example usages of 'gg' are shown below:
a = gg(a, b, c, d, x[k + 1], S21, 0xF61E2562);
d = gg(d, a, b, c, x[k + 6], S22, 0xC040B340);
c = gg(c, d, a, b, x[k + 11], S23, 0x265E5A51);
b = gg(b, c, d, a, x[k + 0], S24, 0xE9B6C7AA);
a = gg(a, b, c, d, x[k + 5], S21, 0xD62F105D);
d = gg(d, a, b, c, x[k + 10], S22, 0x2441453);
c = gg(c, d, a, b, x[k + 15], S23, 0xD8A1E681);
b = gg(b, c, d, a, x[k + 4], S24, 0xE7D3FBC8);
a = gg(a, b, c, d, x[k + 9], S21, 0x21E1CDE6);
d = gg(d, a, b, c, x[k + 14], S22, 0xC33707D6);
c = gg(c, d, a, b, x[k + 3], S23, 0xF4D50D87);
b = gg(b, c, d, a, x[k + 8], S24, 0x455A14ED);
a = gg(a, b, c, d, x[k + 13], S21, 0xA9E3E905);
d = gg(d, a, b, c, x[k + 2], S22, 0xFCEFA3F8);
c = gg(c, d, a, b, x[k + 7], S23, 0x676F02D9);
b = gg(b, c, d, a, x[k + 12], S24, 0x8D2A4C8A);
*/
function gg(a, b, c, d, x, s, ac) {
return addUnsigned(rotateLeft(addUnsigned(a, addUnsigned(addUnsigned(g(b, c, d), x), ac)), s), b);
}
/* Example usages of 'hh' are shown below:
a = hh(a, b, c, d, x[k + 5], S31, 0xFFFA3942);
d = hh(d, a, b, c, x[k + 8], S32, 0x8771F681);
c = hh(c, d, a, b, x[k + 11], S33, 0x6D9D6122);
b = hh(b, c, d, a, x[k + 14], S34, 0xFDE5380C);
a = hh(a, b, c, d, x[k + 1], S31, 0xA4BEEA44);
d = hh(d, a, b, c, x[k + 4], S32, 0x4BDECFA9);
c = hh(c, d, a, b, x[k + 7], S33, 0xF6BB4B60);
b = hh(b, c, d, a, x[k + 10], S34, 0xBEBFBC70);
a = hh(a, b, c, d, x[k + 13], S31, 0x289B7EC6);
d = hh(d, a, b, c, x[k + 0], S32, 0xEAA127FA);
c = hh(c, d, a, b, x[k + 3], S33, 0xD4EF3085);
b = hh(b, c, d, a, x[k + 6], S34, 0x4881D05);
a = hh(a, b, c, d, x[k + 9], S31, 0xD9D4D039);
d = hh(d, a, b, c, x[k + 12], S32, 0xE6DB99E5);
c = hh(c, d, a, b, x[k + 15], S33, 0x1FA27CF8);
b = hh(b, c, d, a, x[k + 2], S34, 0xC4AC5665);
*/
function hh(a, b, c, d, x, s, ac) {
return addUnsigned(rotateLeft(addUnsigned(a, addUnsigned(addUnsigned(h(b, c, d), x), ac)), s), b);
}
/* Example usages of 'ii' are shown below:
a = ii(a, b, c, d, x[k + 0], S41, 0xF4292244);
d = ii(d, a, b, c, x[k + 7], S42, 0x432AFF97);
c = ii(c, d, a, b, x[k + 14], S43, 0xAB9423A7);
b = ii(b, c, d, a, x[k + 5], S44, 0xFC93A039);
a = ii(a, b, c, d, x[k + 12], S41, 0x655B59C3);
d = ii(d, a, b, c, x[k + 3], S42, 0x8F0CCC92);
c = ii(c, d, a, b, x[k + 10], S43, 0xFFEFF47D);
b = ii(b, c, d, a, x[k + 1], S44, 0x85845DD1);
a = ii(a, b, c, d, x[k + 8], S41, 0x6FA87E4F);
d = ii(d, a, b, c, x[k + 15], S42, 0xFE2CE6E0);
c = ii(c, d, a, b, x[k + 6], S43, 0xA3014314);
b = ii(b, c, d, a, x[k + 13], S44, 0x4E0811A1);
a = ii(a, b, c, d, x[k + 4], S41, 0xF7537E82);
d = ii(d, a, b, c, x[k + 11], S42, 0xBD3AF235);
c = ii(c, d, a, b, x[k + 2], S43, 0x2AD7D2BB);
b = ii(b, c, d, a, x[k + 9], S44, 0xEB86D391);
*/
function ii(a, b, c, d, x, s, ac) {
return addUnsigned(rotateLeft(addUnsigned(a, addUnsigned(addUnsigned(i(b, c, d), x), ac)), s), b);
}
/* Example usages of 'strToWordArray' are shown below:
strToWordArray(utf8Encode(str));
*/
function strToWordArray(str) {
const len = str.length;
const words = ((len + 8 - (len + 8) % 64) / 64 + 1) * 16;
const result = Array<number>(words - 1);
let count = 0;
while (count < len) {
const position = (count - (count % 4)) / 4;
const shift = (count % 4) * 8;
result[position] = result[position] | (str.charCodeAt(count++) << shift);
}
const position = (count - (count % 4)) / 4;
const shift = (count % 4) * 8;
result[position] = result[position] | (0x80 << shift);
result[words - 2] = len << 3;
result[words - 1] = len >>> 29;
return result;
}
/* Example usages of 'numToHex' are shown below:
numToHex(a) + numToHex(b) + numToHex(c) + numToHex(d);
*/
function numToHex(value) {
let result = '';
for (let idx = 0; idx < 4; idx++) {
const byte = (value >>> (idx * 8)) & 0xFF;
result += byte.toString(16).substr(-2).padStart(2, '0');
}
return result;
}
/* Example usages of 'utf8Encode' are shown below:
strToWordArray(utf8Encode(str));
*/
function utf8Encode(str) {
str = str.replace(/\r\n/g, '\n');
const len = str.length;
let result = '';
for (let idx = 0; idx < len; idx++) {
const code = str.charCodeAt(idx);
if (code < 128) {
result += String.fromCharCode(code);
} else if ((code > 127) && (code < 2048)) {
result += String.fromCharCode((code >> 6) | 192);
result += String.fromCharCode((code & 63) | 128);
} else {
result += String.fromCharCode((code >> 12) | 224);
result += String.fromCharCode(((code >> 6) & 63) | 128);
result += String.fromCharCode((code & 63) | 128);
}
}
return result;
}
const S11 = 7;
const S12 = 12;
const S13 = 17;
const S14 = 22;
const S21 = 5;
const S22 = 9;
const S23 = 14;
const S24 = 20;
const S31 = 4;
const S32 = 11;
const S33 = 16;
const S34 = 23;
const S41 = 6;
const S42 = 10;
const S43 = 15;
const S44 = 21;
const x = strToWordArray(utf8Encode(str));
let a = 0x67452301;
let b = 0xEFCDAB89;
let c = 0x98BADCFE;
let d = 0x10325476;
for (let k = 0; k < x.length; k += 16) {
const AA = a;
const BB = b;
const CC = c;
const DD = d;
a = ff(a, b, c, d, x[k + 0], S11, 0xD76AA478);
d = ff(d, a, b, c, x[k + 1], S12, 0xE8C7B756);
c = ff(c, d, a, b, x[k + 2], S13, 0x242070DB);
b = ff(b, c, d, a, x[k + 3], S14, 0xC1BDCEEE);
a = ff(a, b, c, d, x[k + 4], S11, 0xF57C0FAF);
d = ff(d, a, b, c, x[k + 5], S12, 0x4787C62A);
c = ff(c, d, a, b, x[k + 6], S13, 0xA8304613);
b = ff(b, c, d, a, x[k + 7], S14, 0xFD469501);
a = ff(a, b, c, d, x[k + 8], S11, 0x698098D8);
d = ff(d, a, b, c, x[k + 9], S12, 0x8B44F7AF);
c = ff(c, d, a, b, x[k + 10], S13, 0xFFFF5BB1);
b = ff(b, c, d, a, x[k + 11], S14, 0x895CD7BE);
a = ff(a, b, c, d, x[k + 12], S11, 0x6B901122);
d = ff(d, a, b, c, x[k + 13], S12, 0xFD987193);
c = ff(c, d, a, b, x[k + 14], S13, 0xA679438E);
b = ff(b, c, d, a, x[k + 15], S14, 0x49B40821);
a = gg(a, b, c, d, x[k + 1], S21, 0xF61E2562);
d = gg(d, a, b, c, x[k + 6], S22, 0xC040B340);
c = gg(c, d, a, b, x[k + 11], S23, 0x265E5A51);
b = gg(b, c, d, a, x[k + 0], S24, 0xE9B6C7AA);
a = gg(a, b, c, d, x[k + 5], S21, 0xD62F105D);
d = gg(d, a, b, c, x[k + 10], S22, 0x2441453);
c = gg(c, d, a, b, x[k + 15], S23, 0xD8A1E681);
b = gg(b, c, d, a, x[k + 4], S24, 0xE7D3FBC8);
a = gg(a, b, c, d, x[k + 9], S21, 0x21E1CDE6);
d = gg(d, a, b, c, x[k + 14], S22, 0xC33707D6);
c = gg(c, d, a, b, x[k + 3], S23, 0xF4D50D87);
b = gg(b, c, d, a, x[k + 8], S24, 0x455A14ED);
a = gg(a, b, c, d, x[k + 13], S21, 0xA9E3E905);
d = gg(d, a, b, c, x[k + 2], S22, 0xFCEFA3F8);
c = gg(c, d, a, b, x[k + 7], S23, 0x676F02D9);
b = gg(b, c, d, a, x[k + 12], S24, 0x8D2A4C8A);
a = hh(a, b, c, d, x[k + 5], S31, 0xFFFA3942);
d = hh(d, a, b, c, x[k + 8], S32, 0x8771F681);
c = hh(c, d, a, b, x[k + 11], S33, 0x6D9D6122);
b = hh(b, c, d, a, x[k + 14], S34, 0xFDE5380C);
a = hh(a, b, c, d, x[k + 1], S31, 0xA4BEEA44);
d = hh(d, a, b, c, x[k + 4], S32, 0x4BDECFA9);
c = hh(c, d, a, b, x[k + 7], S33, 0xF6BB4B60);
b = hh(b, c, d, a, x[k + 10], S34, 0xBEBFBC70);
a = hh(a, b, c, d, x[k + 13], S31, 0x289B7EC6);
d = hh(d, a, b, c, x[k + 0], S32, 0xEAA127FA);
c = hh(c, d, a, b, x[k + 3], S33, 0xD4EF3085);
b = hh(b, c, d, a, x[k + 6], S34, 0x4881D05);
a = hh(a, b, c, d, x[k + 9], S31, 0xD9D4D039);
d = hh(d, a, b, c, x[k + 12], S32, 0xE6DB99E5);
c = hh(c, d, a, b, x[k + 15], S33, 0x1FA27CF8);
b = hh(b, c, d, a, x[k + 2], S34, 0xC4AC5665);
a = ii(a, b, c, d, x[k + 0], S41, 0xF4292244);
d = ii(d, a, b, c, x[k + 7], S42, 0x432AFF97);
c = ii(c, d, a, b, x[k + 14], S43, 0xAB9423A7);
b = ii(b, c, d, a, x[k + 5], S44, 0xFC93A039);
a = ii(a, b, c, d, x[k + 12], S41, 0x655B59C3);
d = ii(d, a, b, c, x[k + 3], S42, 0x8F0CCC92);
c = ii(c, d, a, b, x[k + 10], S43, 0xFFEFF47D);
b = ii(b, c, d, a, x[k + 1], S44, 0x85845DD1);
a = ii(a, b, c, d, x[k + 8], S41, 0x6FA87E4F);
d = ii(d, a, b, c, x[k + 15], S42, 0xFE2CE6E0);
c = ii(c, d, a, b, x[k + 6], S43, 0xA3014314);
b = ii(b, c, d, a, x[k + 13], S44, 0x4E0811A1);
a = ii(a, b, c, d, x[k + 4], S41, 0xF7537E82);
d = ii(d, a, b, c, x[k + 11], S42, 0xBD3AF235);
c = ii(c, d, a, b, x[k + 2], S43, 0x2AD7D2BB);
b = ii(b, c, d, a, x[k + 9], S44, 0xEB86D391);
a = addUnsigned(a, AA);
b = addUnsigned(b, BB);
c = addUnsigned(c, CC);
d = addUnsigned(d, DD);
}
return (numToHex(a) + numToHex(b) + numToHex(c) + numToHex(d)).toLowerCase();
}
|
949a24da270d21c3254c7d63051b125d6fdaa38f | 4,835 | ts | TypeScript | libs/amyr-ts-lib/src/lib/libs/tsmt/math/repeat-to-frac.ts | theAlgorithmist/AMYR | db4141d7e545b94a5c98fc5430a065e2ba229e75 | [
"Apache-2.0"
] | 3 | 2022-01-17T21:31:47.000Z | 2022-03-04T20:16:21.000Z | libs/amyr-ts-lib/src/lib/libs/tsmt/math/repeat-to-frac.ts | theAlgorithmist/AMYR | db4141d7e545b94a5c98fc5430a065e2ba229e75 | [
"Apache-2.0"
] | null | null | null | libs/amyr-ts-lib/src/lib/libs/tsmt/math/repeat-to-frac.ts | theAlgorithmist/AMYR | db4141d7e545b94a5c98fc5430a065e2ba229e75 | [
"Apache-2.0"
] | null | null | null | /**
* Copyright 2016 Jim Armstrong (www.algorithmist.net)
*
* 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.
*/
/**
* Repeating decimal to fraction
*
* @author Jim Armstrong (www.algorithmist.net)
*
* @version 1.0
*/
export type SimpleFraction =
{
num: number,
den: number
}
/**
* AMYR Library, Typescript Math Toolkit. Return a number with a simple repeating decimal, i.e. 1.454545 as a fraction
* (optionally in reduced form). Decimals in the repeating sequence may be presumed to be unique, i.e. 0.115115 would
* be considered as 0.1111 as 1 is the first digit to repeat. This likely done to keep problems tractable for students.
*
* Only numerator and denominator are returned.
*
* @param {string} n Number containing a repeating sequence after the decimal
*
* @param {boolean} toReduced True if result is to be converted into reduced form
* @default false
*/
export function repeatToFraction(n: string, toReduced: boolean = false): SimpleFraction | null
{
let result: SimpleFraction | null = null;
// is there a repeating sequence after the decimal?
const decimal: number = n.indexOf('.');
if (decimal == -1) return result;
const beforeDecimal = n.substring(0,decimal);
const afterDecimal = n.substring(decimal+1, n.length);
let repeat: string = getMinimalRepeating(afterDecimal);
let shift = 0;
// do we need to skip forward to test for a repeating sequence some places after the decimal, like 5.0424242 or 2.13234234
if (repeat == "")
{
let tmp: string = afterDecimal;
const len: number = afterDecimal.length;
shift = 1;
while (tmp.length > 1)
{
tmp = afterDecimal.substring(shift, len);
repeat = getMinimalRepeating(tmp);
if (repeat != "") break;
shift++;
}
if (repeat === "") return result;
}
const digits: number = repeat.length + shift; // number of repeat and shift digits
// if d = # repeat digits, s = shift factor, and x is the original number, then form the equation 10^(d+s)x -
// (10^s)x = z, where z is the numerical result of subtracting out the repeat sequence so, numerator = z and
// denominator = 10^(d+s) - 10^s. z needs to be symbolically computed since the repeat sequence may not be
// repeated in sufficient length to get the correct result in floating-point computation.
const s: number = shift == 0 ? 1 : Math.pow(10,shift);
let denominator: number = Math.pow(10,digits) - s;
const n1: string = beforeDecimal + n.substr(decimal+1, digits);
const n2: string = beforeDecimal + n.substr(decimal+1, shift);
let numerator: number = +n1 - +n2;
// result in reduced form?
if (toReduced)
{
const d: number = gcd(numerator, denominator);
numerator = Math.floor(numerator/d);
denominator = Math.floor(denominator/d);
}
result = {num: numerator, den: denominator};
return result;
}
// utility function to extract the minimal (unique-digit) repeating sequence of at least length 1, i.e. '555555' is
// a repeating sequence of '5', '545454' is a repeating sequence of '54, '123123123' is a repeating sequence of '123',
// and '054605460546' is a repeating sequence of '0546'
function getMinimalRepeating(test: string): string
{
const result = "";
const len: number = test.length;
if (len < 1) return result;
let candidate: string; // candidate sequence
let lenC = 1; // length of candidate sequence
while (2*lenC <= len)
{
candidate = test.substr(0,lenC);
if (candidate == test.substr(lenC, lenC))
{
// candidate just got elected
return candidate;
}
else
{
// try again
lenC++;
}
}
return result;
}
/**
* Compute the greatest common divisor of two integers
*
* @param {number} n1 First integer
*
* @param {number} n2 Second integer
*/
function gcd(n1: number, n2: number): number
{
// since this is used internally to the problem at hand, a lot of error-checking is skipped
// Euclid's algorithm - nothing new under the sun
let a = Math.max(n1, n2);
let b = Math.min(n1, n2);
let r = 0;
while( b > 0 )
{
r = a % b;
a = b;
b = r;
}
return Math.floor(a);
}
| 30.408805 | 125 | 0.653154 | 77 | 3 | 0 | 5 | 22 | 2 | 2 | 0 | 22 | 1 | 0 | 21 | 1,387 | 0.005768 | 0.015862 | 0.001442 | 0.000721 | 0 | 0 | 0.6875 | 0.236202 | /**
* Copyright 2016 Jim Armstrong (www.algorithmist.net)
*
* 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.
*/
/**
* Repeating decimal to fraction
*
* @author Jim Armstrong (www.algorithmist.net)
*
* @version 1.0
*/
export type SimpleFraction =
{
num,
den
}
/**
* AMYR Library, Typescript Math Toolkit. Return a number with a simple repeating decimal, i.e. 1.454545 as a fraction
* (optionally in reduced form). Decimals in the repeating sequence may be presumed to be unique, i.e. 0.115115 would
* be considered as 0.1111 as 1 is the first digit to repeat. This likely done to keep problems tractable for students.
*
* Only numerator and denominator are returned.
*
* @param {string} n Number containing a repeating sequence after the decimal
*
* @param {boolean} toReduced True if result is to be converted into reduced form
* @default false
*/
export function repeatToFraction(n, toReduced = false)
{
let result = null;
// is there a repeating sequence after the decimal?
const decimal = n.indexOf('.');
if (decimal == -1) return result;
const beforeDecimal = n.substring(0,decimal);
const afterDecimal = n.substring(decimal+1, n.length);
let repeat = getMinimalRepeating(afterDecimal);
let shift = 0;
// do we need to skip forward to test for a repeating sequence some places after the decimal, like 5.0424242 or 2.13234234
if (repeat == "")
{
let tmp = afterDecimal;
const len = afterDecimal.length;
shift = 1;
while (tmp.length > 1)
{
tmp = afterDecimal.substring(shift, len);
repeat = getMinimalRepeating(tmp);
if (repeat != "") break;
shift++;
}
if (repeat === "") return result;
}
const digits = repeat.length + shift; // number of repeat and shift digits
// if d = # repeat digits, s = shift factor, and x is the original number, then form the equation 10^(d+s)x -
// (10^s)x = z, where z is the numerical result of subtracting out the repeat sequence so, numerator = z and
// denominator = 10^(d+s) - 10^s. z needs to be symbolically computed since the repeat sequence may not be
// repeated in sufficient length to get the correct result in floating-point computation.
const s = shift == 0 ? 1 : Math.pow(10,shift);
let denominator = Math.pow(10,digits) - s;
const n1 = beforeDecimal + n.substr(decimal+1, digits);
const n2 = beforeDecimal + n.substr(decimal+1, shift);
let numerator = +n1 - +n2;
// result in reduced form?
if (toReduced)
{
const d = gcd(numerator, denominator);
numerator = Math.floor(numerator/d);
denominator = Math.floor(denominator/d);
}
result = {num: numerator, den: denominator};
return result;
}
// utility function to extract the minimal (unique-digit) repeating sequence of at least length 1, i.e. '555555' is
// a repeating sequence of '5', '545454' is a repeating sequence of '54, '123123123' is a repeating sequence of '123',
// and '054605460546' is a repeating sequence of '0546'
/* Example usages of 'getMinimalRepeating' are shown below:
getMinimalRepeating(afterDecimal);
repeat = getMinimalRepeating(tmp);
*/
function getMinimalRepeating(test)
{
const result = "";
const len = test.length;
if (len < 1) return result;
let candidate; // candidate sequence
let lenC = 1; // length of candidate sequence
while (2*lenC <= len)
{
candidate = test.substr(0,lenC);
if (candidate == test.substr(lenC, lenC))
{
// candidate just got elected
return candidate;
}
else
{
// try again
lenC++;
}
}
return result;
}
/**
* Compute the greatest common divisor of two integers
*
* @param {number} n1 First integer
*
* @param {number} n2 Second integer
*/
/* Example usages of 'gcd' are shown below:
gcd(numerator, denominator);
*/
function gcd(n1, n2)
{
// since this is used internally to the problem at hand, a lot of error-checking is skipped
// Euclid's algorithm - nothing new under the sun
let a = Math.max(n1, n2);
let b = Math.min(n1, n2);
let r = 0;
while( b > 0 )
{
r = a % b;
a = b;
b = r;
}
return Math.floor(a);
}
|
16390d9456de7a9e1a9f02518a9074772c248f70 | 9,071 | ts | TypeScript | src/filters/core/calculate.ts | MahmoudAboelazm/image-editor-pwa | 768d423e43ccee07789d08914caff6aef2935368 | [
"MIT"
] | null | null | null | src/filters/core/calculate.ts | MahmoudAboelazm/image-editor-pwa | 768d423e43ccee07789d08914caff6aef2935368 | [
"MIT"
] | 3 | 2022-01-22T04:31:47.000Z | 2022-03-30T02:26:53.000Z | src/filters/core/calculate.ts | MahmoudAboelazm/image-editor-pwa | 768d423e43ccee07789d08914caff6aef2935368 | [
"MIT"
] | null | null | null | class Calculate {
// Calculates the distance between two points.
// @param [Number] x1 1st point x-coordinate.
// @param [Number] y1 1st point y-coordinate.
// @param [Number] x2 2nd point x-coordinate.
// @param [Number] y2 2nd point y-coordinate.
// @return [Number] The distance between the two points.
static distance(x1, y1, x2, y2) {
return Math.sqrt(Math.pow(x2 - x1, 2) + Math.pow(y2 - y1, 2));
}
// Generates a pseudorandom number that lies within the max - mix range. The number can be either
// an integer or a float depending on what the user specifies.
// @param [Number] min The lower bound (inclusive).
// @param [Number] max The upper bound (inclusive).
// @param [Boolean] getFloat Return a Float or a rounded Integer?
// @return [Number] The pseudorandom number, either as a float or integer.
randomRange(min, max, getFloat) {
if (getFloat == null) {
getFloat = false;
}
const rand = min + Math.random() * (max - min);
if (getFloat) {
return rand.toFixed(getFloat);
} else {
return Math.round(rand);
}
}
// Calculates the luminance of a single pixel using a special weighted sum.
// @param [Object] rgba RGBA object describing a single pixel.
// @return [Number] The luminance value of the pixel.
luminance(rgba) {
return 0.299 * rgba.r + 0.587 * rgba.g + 0.114 * rgba.b;
}
// Generates a bezier curve given a start and end point, with control points in between.
// Can also optionally bound the y values between a low and high bound.
//
// This is different than most bezier curve functions because it attempts to construct it in such
// a way that we can use it more like a simple input -> output system, or a one-to-one function.
// In other words we can provide an input color value, and immediately receive an output modified
// color value.
//
// Note that, by design, this does not force X values to be in the range [0..255]. This is to
// generalize the function a bit more. If you give it a starting X value that isn't 0, and/or a
// ending X value that isn't 255, you may run into problems with your filter!
//
// @param [Array] 2-item arrays describing the x, y coordinates of the control points. Minimum two.
// @param [Number] lowBound (optional) Minimum possible value for any y-value in the curve.
// @param [Number] highBound (optional) Maximum posisble value for any y-value in the curve.
// @return [Array] Array whose index represents every x-value between start and end, and value
// represents the corresponding y-value.
bezier(start, ctrl1, ctrl2, end, lowBound, highBound) {
//(controlPoints, lowBound, highBound) ->
// 4.0 shim - change declaration to (controlPoints, lowBound, highBound) at 5.0
let controlPoints;
if (lowBound == null) {
lowBound = 0;
}
if (highBound == null) {
highBound = 255;
}
if (start[0] instanceof Array) {
controlPoints = start;
lowBound = ctrl1;
highBound = ctrl2;
} else {
controlPoints = [start, ctrl1, ctrl2, end];
}
if (controlPoints.length < 2) {
throw "Invalid number of arguments to bezier";
}
let bezier = {};
const lerp = (a, b, t) => a * (1 - t) + b * t;
const clamp = (a, min, max) => Math.min(Math.max(a, min), max);
for (let i = 0; i < 1000; i++) {
const t = i / 1000;
let prev = controlPoints;
while (prev.length > 1) {
const next = [];
for (
let j = 0, end1 = prev.length - 2, asc = 0 <= end1;
asc ? j <= end1 : j >= end1;
asc ? j++ : j--
) {
next.push([
lerp(prev[j][0], prev[j + 1][0], t),
lerp(prev[j][1], prev[j + 1][1], t),
]);
}
prev = next;
}
bezier[Math.round(prev[0][0])] = Math.round(
clamp(prev[0][1], lowBound, highBound),
);
}
const endX = controlPoints[controlPoints.length - 1][0];
bezier = Calculate.missingValues(bezier, endX);
// Edge case
if (bezier[endX] == null) {
bezier[endX] = bezier[endX - 1];
}
return bezier;
}
// Generates a hermite curve given a start and end point, with control points in between.
// Can also optionally bound the y values between a low and high bound.
//
// This is different than most hermite curve functions because it attempts to construct it in such
// a way that we can use it more like a simple input -> output system, or a one-to-one function.
// In other words we can provide an input color value, and immediately receive an output modified
// color value.
//
// Note that, by design, this does not force X values to be in the range [0..255]. This is to
// generalize the function a bit more. If you give it a starting X value that isn't 0, and/or a
// ending X value that isn't 255, you may run into problems with your filter!
//
// @param [Array] 2-item arrays describing the x, y coordinates of the control points. Minimum two.
// @param [Number] lowBound (optional) Minimum possible value for any y-value in the curve.
// @param [Number] highBound (optional) Maximum possible value for any y-value in the curve.
// @return [Array] Array whose index represents every x-value between start and end, and value
// represents the corresponding y-value.
static hermite(controlPoints, lowBound, highBound) {
if (controlPoints.length < 2) {
throw "Invalid number of arguments to hermite";
}
let ret = {};
const lerp = (a, b, t) => a * (1 - t) + b * t;
const add = (a, b, c, d) => [
a[0] + b[0] + c[0] + d[0],
a[1] + b[1] + c[1] + d[1],
];
const mul = (a, b) => [a[0] * b[0], a[1] * b[1]];
const sub = (a, b) => [a[0] - b[0], a[1] - b[1]];
const clamp = (a, min, max) => Math.min(Math.max(a, min), max);
let count = 0;
for (
let i = 0, end = controlPoints.length - 2, asc = 0 <= end;
asc ? i <= end : i >= end;
asc ? i++ : i--
) {
const p0 = controlPoints[i];
const p1 = controlPoints[i + 1];
const pointsPerSegment = p1[0] - p0[0];
let pointsPerStep = 1 / pointsPerSegment;
// the last point of the last segment should reach p1
if (i === controlPoints.length - 2) {
pointsPerStep = 1 / (pointsPerSegment - 1);
}
let p = i > 0 ? controlPoints[i - 1] : p0;
const m0 = mul(sub(p1, p), [0.5, 0.5]);
p = i < controlPoints.length - 2 ? controlPoints[i + 2] : p1;
const m1 = mul(sub(p, p0), [0.5, 0.5]);
for (
let j = 0, end1 = pointsPerSegment, asc1 = 0 <= end1;
asc1 ? j <= end1 : j >= end1;
asc1 ? j++ : j--
) {
const t = j * pointsPerStep;
const fac0 = 2.0 * t * t * t - 3.0 * t * t + 1.0;
const fac1 = t * t * t - 2.0 * t * t + t;
const fac2 = -2.0 * t * t * t + 3.0 * t * t;
const fac3 = t * t * t - t * t;
const pos = add(
mul(p0, [fac0, fac0]),
mul(m0, [fac1, fac1]),
mul(p1, [fac2, fac2]),
mul(m1, [fac3, fac3]),
);
ret[Math.round(pos[0])] = Math.round(
clamp(pos[1], lowBound, highBound),
);
count += 1;
}
}
// add missing values
const endX = controlPoints[controlPoints.length - 1][0];
ret = Calculate.missingValues(ret, endX);
return ret;
}
// Calculates possible missing values from a given value array. Note that this returns a copy
// and does not mutate the original. In case no values are missing the original array is
// returned as that is convenient.
//
// @param [Array] 2-item arrays describing the x, y coordinates of the control points.
// @param [Number] end x value of the array (maximum)
// @return [Array] Array whose index represents every x-value between start and end, and value
// represents the corresponding y-value.
static missingValues(values, endX) {
// Do a search for missing values in the bezier array and use linear
// interpolation to approximate their values
var i, j, leftCoord, ret, rightCoord, _i, _j;
if (Object.keys(values).length < endX + 1) {
ret = {};
for (
i = _i = 0;
0 <= endX ? _i <= endX : _i >= endX;
i = 0 <= endX ? ++_i : --_i
) {
if (values[i] != null) {
ret[i] = values[i];
} else {
leftCoord = [i - 1, ret[i - 1]];
for (
j = _j = i;
i <= endX ? _j <= endX : _j >= endX;
j = i <= endX ? ++_j : --_j
) {
if (values[j] != null) {
rightCoord = [j, values[j]];
break;
}
}
if (!rightCoord) {
rightCoord = [0, 0];
}
ret[i] =
leftCoord[1] +
((rightCoord[1] - leftCoord[1]) / (rightCoord[0] - leftCoord[0])) *
(i - leftCoord[0]);
}
}
return ret;
}
return values;
}
}
export default Calculate;
| 34.888462 | 101 | 0.578216 | 161 | 13 | 0 | 39 | 47 | 0 | 6 | 0 | 0 | 1 | 1 | 12 | 2,737 | 0.018999 | 0.017172 | 0 | 0.000365 | 0.000365 | 0 | 0 | 0.272692 | class Calculate {
// Calculates the distance between two points.
// @param [Number] x1 1st point x-coordinate.
// @param [Number] y1 1st point y-coordinate.
// @param [Number] x2 2nd point x-coordinate.
// @param [Number] y2 2nd point y-coordinate.
// @return [Number] The distance between the two points.
static distance(x1, y1, x2, y2) {
return Math.sqrt(Math.pow(x2 - x1, 2) + Math.pow(y2 - y1, 2));
}
// Generates a pseudorandom number that lies within the max - mix range. The number can be either
// an integer or a float depending on what the user specifies.
// @param [Number] min The lower bound (inclusive).
// @param [Number] max The upper bound (inclusive).
// @param [Boolean] getFloat Return a Float or a rounded Integer?
// @return [Number] The pseudorandom number, either as a float or integer.
randomRange(min, max, getFloat) {
if (getFloat == null) {
getFloat = false;
}
const rand = min + Math.random() * (max - min);
if (getFloat) {
return rand.toFixed(getFloat);
} else {
return Math.round(rand);
}
}
// Calculates the luminance of a single pixel using a special weighted sum.
// @param [Object] rgba RGBA object describing a single pixel.
// @return [Number] The luminance value of the pixel.
luminance(rgba) {
return 0.299 * rgba.r + 0.587 * rgba.g + 0.114 * rgba.b;
}
// Generates a bezier curve given a start and end point, with control points in between.
// Can also optionally bound the y values between a low and high bound.
//
// This is different than most bezier curve functions because it attempts to construct it in such
// a way that we can use it more like a simple input -> output system, or a one-to-one function.
// In other words we can provide an input color value, and immediately receive an output modified
// color value.
//
// Note that, by design, this does not force X values to be in the range [0..255]. This is to
// generalize the function a bit more. If you give it a starting X value that isn't 0, and/or a
// ending X value that isn't 255, you may run into problems with your filter!
//
// @param [Array] 2-item arrays describing the x, y coordinates of the control points. Minimum two.
// @param [Number] lowBound (optional) Minimum possible value for any y-value in the curve.
// @param [Number] highBound (optional) Maximum posisble value for any y-value in the curve.
// @return [Array] Array whose index represents every x-value between start and end, and value
// represents the corresponding y-value.
bezier(start, ctrl1, ctrl2, end, lowBound, highBound) {
//(controlPoints, lowBound, highBound) ->
// 4.0 shim - change declaration to (controlPoints, lowBound, highBound) at 5.0
let controlPoints;
if (lowBound == null) {
lowBound = 0;
}
if (highBound == null) {
highBound = 255;
}
if (start[0] instanceof Array) {
controlPoints = start;
lowBound = ctrl1;
highBound = ctrl2;
} else {
controlPoints = [start, ctrl1, ctrl2, end];
}
if (controlPoints.length < 2) {
throw "Invalid number of arguments to bezier";
}
let bezier = {};
/* Example usages of 'lerp' are shown below:
lerp(prev[j][0], prev[j + 1][0], t);
lerp(prev[j][1], prev[j + 1][1], t);
*/
/* Example usages of 'lerp' are shown below:
lerp(prev[j][0], prev[j + 1][0], t);
lerp(prev[j][1], prev[j + 1][1], t);
*/
const lerp = (a, b, t) => a * (1 - t) + b * t;
/* Example usages of 'clamp' are shown below:
bezier[Math.round(prev[0][0])] = Math.round(clamp(prev[0][1], lowBound, highBound));
ret[Math.round(pos[0])] = Math.round(clamp(pos[1], lowBound, highBound));
*/
/* Example usages of 'clamp' are shown below:
bezier[Math.round(prev[0][0])] = Math.round(clamp(prev[0][1], lowBound, highBound));
ret[Math.round(pos[0])] = Math.round(clamp(pos[1], lowBound, highBound));
*/
const clamp = (a, min, max) => Math.min(Math.max(a, min), max);
for (let i = 0; i < 1000; i++) {
const t = i / 1000;
let prev = controlPoints;
while (prev.length > 1) {
const next = [];
for (
let j = 0, end1 = prev.length - 2, asc = 0 <= end1;
asc ? j <= end1 : j >= end1;
asc ? j++ : j--
) {
next.push([
lerp(prev[j][0], prev[j + 1][0], t),
lerp(prev[j][1], prev[j + 1][1], t),
]);
}
prev = next;
}
bezier[Math.round(prev[0][0])] = Math.round(
clamp(prev[0][1], lowBound, highBound),
);
}
const endX = controlPoints[controlPoints.length - 1][0];
bezier = Calculate.missingValues(bezier, endX);
// Edge case
if (bezier[endX] == null) {
bezier[endX] = bezier[endX - 1];
}
return bezier;
}
// Generates a hermite curve given a start and end point, with control points in between.
// Can also optionally bound the y values between a low and high bound.
//
// This is different than most hermite curve functions because it attempts to construct it in such
// a way that we can use it more like a simple input -> output system, or a one-to-one function.
// In other words we can provide an input color value, and immediately receive an output modified
// color value.
//
// Note that, by design, this does not force X values to be in the range [0..255]. This is to
// generalize the function a bit more. If you give it a starting X value that isn't 0, and/or a
// ending X value that isn't 255, you may run into problems with your filter!
//
// @param [Array] 2-item arrays describing the x, y coordinates of the control points. Minimum two.
// @param [Number] lowBound (optional) Minimum possible value for any y-value in the curve.
// @param [Number] highBound (optional) Maximum possible value for any y-value in the curve.
// @return [Array] Array whose index represents every x-value between start and end, and value
// represents the corresponding y-value.
static hermite(controlPoints, lowBound, highBound) {
if (controlPoints.length < 2) {
throw "Invalid number of arguments to hermite";
}
let ret = {};
/* Example usages of 'lerp' are shown below:
lerp(prev[j][0], prev[j + 1][0], t);
lerp(prev[j][1], prev[j + 1][1], t);
*/
/* Example usages of 'lerp' are shown below:
lerp(prev[j][0], prev[j + 1][0], t);
lerp(prev[j][1], prev[j + 1][1], t);
*/
const lerp = (a, b, t) => a * (1 - t) + b * t;
/* Example usages of 'add' are shown below:
add(mul(p0, [fac0, fac0]), mul(m0, [fac1, fac1]), mul(p1, [fac2, fac2]), mul(m1, [fac3, fac3]));
*/
const add = (a, b, c, d) => [
a[0] + b[0] + c[0] + d[0],
a[1] + b[1] + c[1] + d[1],
];
/* Example usages of 'mul' are shown below:
mul(sub(p1, p), [0.5, 0.5]);
mul(sub(p, p0), [0.5, 0.5]);
add(mul(p0, [fac0, fac0]), mul(m0, [fac1, fac1]), mul(p1, [fac2, fac2]), mul(m1, [fac3, fac3]));
*/
const mul = (a, b) => [a[0] * b[0], a[1] * b[1]];
/* Example usages of 'sub' are shown below:
mul(sub(p1, p), [0.5, 0.5]);
mul(sub(p, p0), [0.5, 0.5]);
*/
const sub = (a, b) => [a[0] - b[0], a[1] - b[1]];
/* Example usages of 'clamp' are shown below:
bezier[Math.round(prev[0][0])] = Math.round(clamp(prev[0][1], lowBound, highBound));
ret[Math.round(pos[0])] = Math.round(clamp(pos[1], lowBound, highBound));
*/
/* Example usages of 'clamp' are shown below:
bezier[Math.round(prev[0][0])] = Math.round(clamp(prev[0][1], lowBound, highBound));
ret[Math.round(pos[0])] = Math.round(clamp(pos[1], lowBound, highBound));
*/
const clamp = (a, min, max) => Math.min(Math.max(a, min), max);
let count = 0;
for (
let i = 0, end = controlPoints.length - 2, asc = 0 <= end;
asc ? i <= end : i >= end;
asc ? i++ : i--
) {
const p0 = controlPoints[i];
const p1 = controlPoints[i + 1];
const pointsPerSegment = p1[0] - p0[0];
let pointsPerStep = 1 / pointsPerSegment;
// the last point of the last segment should reach p1
if (i === controlPoints.length - 2) {
pointsPerStep = 1 / (pointsPerSegment - 1);
}
let p = i > 0 ? controlPoints[i - 1] : p0;
const m0 = mul(sub(p1, p), [0.5, 0.5]);
p = i < controlPoints.length - 2 ? controlPoints[i + 2] : p1;
const m1 = mul(sub(p, p0), [0.5, 0.5]);
for (
let j = 0, end1 = pointsPerSegment, asc1 = 0 <= end1;
asc1 ? j <= end1 : j >= end1;
asc1 ? j++ : j--
) {
const t = j * pointsPerStep;
const fac0 = 2.0 * t * t * t - 3.0 * t * t + 1.0;
const fac1 = t * t * t - 2.0 * t * t + t;
const fac2 = -2.0 * t * t * t + 3.0 * t * t;
const fac3 = t * t * t - t * t;
const pos = add(
mul(p0, [fac0, fac0]),
mul(m0, [fac1, fac1]),
mul(p1, [fac2, fac2]),
mul(m1, [fac3, fac3]),
);
ret[Math.round(pos[0])] = Math.round(
clamp(pos[1], lowBound, highBound),
);
count += 1;
}
}
// add missing values
const endX = controlPoints[controlPoints.length - 1][0];
ret = Calculate.missingValues(ret, endX);
return ret;
}
// Calculates possible missing values from a given value array. Note that this returns a copy
// and does not mutate the original. In case no values are missing the original array is
// returned as that is convenient.
//
// @param [Array] 2-item arrays describing the x, y coordinates of the control points.
// @param [Number] end x value of the array (maximum)
// @return [Array] Array whose index represents every x-value between start and end, and value
// represents the corresponding y-value.
static missingValues(values, endX) {
// Do a search for missing values in the bezier array and use linear
// interpolation to approximate their values
var i, j, leftCoord, ret, rightCoord, _i, _j;
if (Object.keys(values).length < endX + 1) {
ret = {};
for (
i = _i = 0;
0 <= endX ? _i <= endX : _i >= endX;
i = 0 <= endX ? ++_i : --_i
) {
if (values[i] != null) {
ret[i] = values[i];
} else {
leftCoord = [i - 1, ret[i - 1]];
for (
j = _j = i;
i <= endX ? _j <= endX : _j >= endX;
j = i <= endX ? ++_j : --_j
) {
if (values[j] != null) {
rightCoord = [j, values[j]];
break;
}
}
if (!rightCoord) {
rightCoord = [0, 0];
}
ret[i] =
leftCoord[1] +
((rightCoord[1] - leftCoord[1]) / (rightCoord[0] - leftCoord[0])) *
(i - leftCoord[0]);
}
}
return ret;
}
return values;
}
}
export default Calculate;
|
1676a766887b46a217110786a281fed07ac92a2a | 2,728 | ts | TypeScript | src/common/file-handlers/parse-utils.ts | Stevebel/DPE-Editor | 7e0533ff6a794dd9de45f1ee80b72a30def494fa | [
"MIT"
] | 1 | 2022-01-29T20:48:27.000Z | 2022-01-29T20:48:27.000Z | src/common/file-handlers/parse-utils.ts | Stevebel/DPE-Editor | 7e0533ff6a794dd9de45f1ee80b72a30def494fa | [
"MIT"
] | 1 | 2022-02-06T21:41:21.000Z | 2022-02-06T21:41:21.000Z | src/common/file-handlers/parse-utils.ts | Stevebel/DPE-Editor | 7e0533ff6a794dd9de45f1ee80b72a30def494fa | [
"MIT"
] | null | null | null | // Finds the index of the closing bracket of the first opening bracket found
// unless the bracket is commented out or in quotes.
export function closingBracketIndex(
str: string,
open: string,
close: string
): number {
let openCount = 0;
let i = 0;
while (i < str.length) {
if (str[i] === `"` || str[i] === `'`) {
// Skip over quoted strings
i = str.indexOf(str[i], i + 1);
if (i === -1) {
throw new Error(`Unterminated string literal`);
}
i += 1;
} else if (str[i] === '/' && str[i + 1] === '/') {
// Skip single line comment
i = str.indexOf('\n', i + 1);
if (i === -1) {
throw new Error(`Unterminated line comment`);
}
} else if (str[i] === '/' && str[i + 1] === '*') {
// Skip multi-line comment
i = str.indexOf('*/', i + 1);
if (i === -1) {
throw new Error(`Unterminated block comment`);
}
i += 2;
}
if (str[i] === open) {
openCount += 1;
} else if (str[i] === close) {
openCount -= 1;
if (openCount === 0) {
return i;
}
}
i += 1;
}
throw new Error(`Unterminated ${open}: ${str}`);
}
// Find index of the first target character that is not inside a string or brackets
export function nextIndexOf(str: string, target: string): number {
let i = 0;
while (i < str.length) {
if (str[i] === target) {
return i;
}
if (str[i] === `"` || str[i] === `'`) {
// Skip over quoted strings
i = str.indexOf(str[i], i + 1);
if (i === -1) {
throw new Error(`Unterminated string literal`);
}
i += 1;
} else if (str[i] === '/' && str[i + 1] === '/') {
// Skip single line comment
i = str.indexOf('\n', i + 1);
if (i === -1) {
throw new Error(`Unterminated line comment`);
}
} else if (str[i] === '/' && str[i + 1] === '*') {
// Skip multi-line comment
i = str.indexOf('*/', i + 1);
if (i === -1) {
throw new Error(`Unterminated block comment`);
}
i += 2;
} else if (str[i] === '[') {
// Skip over square brackets
i += closingBracketIndex(str.substring(i), '[', ']');
} else if (str[i] === '{') {
// Skip over curly brackets
i += closingBracketIndex(str.substring(i), '{', '}');
} else if (str[i] === '(') {
// Skip over parentheses
i += closingBracketIndex(str.substring(i), '(', ')');
} else {
i += 1;
}
}
return -1;
}
export function nextCommaIndex(str: string): number {
return nextIndexOf(str, ',');
}
export function regExpEscape(str: string) {
return str
.replace(/[-[\]{}()*+!<=:?.^$|#,]/g, '\\$&')
.replace(/\s+/g, '\\s+');
}
| 27.836735 | 83 | 0.488636 | 81 | 4 | 0 | 7 | 3 | 0 | 2 | 0 | 10 | 0 | 0 | 17.25 | 836 | 0.013158 | 0.003589 | 0 | 0 | 0 | 0 | 0.714286 | 0.212177 | // Finds the index of the closing bracket of the first opening bracket found
// unless the bracket is commented out or in quotes.
export /* Example usages of 'closingBracketIndex' are shown below:
// Skip over square brackets
i += closingBracketIndex(str.substring(i), '[', ']');
// Skip over curly brackets
i += closingBracketIndex(str.substring(i), '{', '}');
// Skip over parentheses
i += closingBracketIndex(str.substring(i), '(', ')');
*/
function closingBracketIndex(
str,
open,
close
) {
let openCount = 0;
let i = 0;
while (i < str.length) {
if (str[i] === `"` || str[i] === `'`) {
// Skip over quoted strings
i = str.indexOf(str[i], i + 1);
if (i === -1) {
throw new Error(`Unterminated string literal`);
}
i += 1;
} else if (str[i] === '/' && str[i + 1] === '/') {
// Skip single line comment
i = str.indexOf('\n', i + 1);
if (i === -1) {
throw new Error(`Unterminated line comment`);
}
} else if (str[i] === '/' && str[i + 1] === '*') {
// Skip multi-line comment
i = str.indexOf('*/', i + 1);
if (i === -1) {
throw new Error(`Unterminated block comment`);
}
i += 2;
}
if (str[i] === open) {
openCount += 1;
} else if (str[i] === close) {
openCount -= 1;
if (openCount === 0) {
return i;
}
}
i += 1;
}
throw new Error(`Unterminated ${open}: ${str}`);
}
// Find index of the first target character that is not inside a string or brackets
export /* Example usages of 'nextIndexOf' are shown below:
nextIndexOf(str, ',');
*/
function nextIndexOf(str, target) {
let i = 0;
while (i < str.length) {
if (str[i] === target) {
return i;
}
if (str[i] === `"` || str[i] === `'`) {
// Skip over quoted strings
i = str.indexOf(str[i], i + 1);
if (i === -1) {
throw new Error(`Unterminated string literal`);
}
i += 1;
} else if (str[i] === '/' && str[i + 1] === '/') {
// Skip single line comment
i = str.indexOf('\n', i + 1);
if (i === -1) {
throw new Error(`Unterminated line comment`);
}
} else if (str[i] === '/' && str[i + 1] === '*') {
// Skip multi-line comment
i = str.indexOf('*/', i + 1);
if (i === -1) {
throw new Error(`Unterminated block comment`);
}
i += 2;
} else if (str[i] === '[') {
// Skip over square brackets
i += closingBracketIndex(str.substring(i), '[', ']');
} else if (str[i] === '{') {
// Skip over curly brackets
i += closingBracketIndex(str.substring(i), '{', '}');
} else if (str[i] === '(') {
// Skip over parentheses
i += closingBracketIndex(str.substring(i), '(', ')');
} else {
i += 1;
}
}
return -1;
}
export function nextCommaIndex(str) {
return nextIndexOf(str, ',');
}
export function regExpEscape(str) {
return str
.replace(/[-[\]{}()*+!<=:?.^$|#,]/g, '\\$&')
.replace(/\s+/g, '\\s+');
}
|
167c0adeafafaf9109d51b2470a2c981c6182c56 | 4,738 | ts | TypeScript | src/utilities/dateUtilities.ts | yannisraft/chronocraft-datepicker-vue | 80b94876872c9be2f56fb46f197e7c6d2821baaf | [
"MIT"
] | 1 | 2022-03-14T08:11:23.000Z | 2022-03-14T08:11:23.000Z | src/utilities/dateUtilities.ts | yannisraft/chronocraft-datepicker-vue | 80b94876872c9be2f56fb46f197e7c6d2821baaf | [
"MIT"
] | null | null | null | src/utilities/dateUtilities.ts | yannisraft/chronocraft-datepicker-vue | 80b94876872c9be2f56fb46f197e7c6d2821baaf | [
"MIT"
] | null | null | null | export const addDays = (date: Date, days: number): Date => {
var result = new Date(date);
result.setDate(result.getDate() + days);
return result;
};
export const addMonths = (date: Date, months: number): Date => {
var result = new Date(date);
result.setMonth(result.getMonth() + months);
return result;
};
export const getDiff = (d1: Date, d2: Date): number => {
var result = d1.getTime() - d2.getTime();
return result;
};
export const getDiffInDays = (d1: Date, d2: Date): number => {
var result = d1.getTime() - d2.getTime();
return Math.ceil(result / (1000 * 60 * 60 * 24));;
};
export const daysMatch = (d1: Date, d2: Date): boolean => {
return d1.getDate() == d2.getDate() &&
d1.getMonth() == d2.getMonth() &&
d1.getFullYear() == d2.getFullYear()
}
export const isDateBetweenDatesExcluding = (
startDate: Date,
endDate: Date,
checkDate: Date
): boolean => {
var isbetween = false;
if((checkDate < endDate && checkDate > startDate)) {
isbetween = true;
}
return isbetween;
};
export const twoDigitPad = (num: number): string => {
return num < 10 ? ("0" + String(num)) : String(num);
}
export const formatDate = (date: any, patternStr: string): string => {
var monthNames = [
"January", "February", "March", "April", "May", "June", "July",
"August", "September", "October", "November", "December"
];
var dayOfWeekNames = [
"Sunday", "Monday", "Tuesday",
"Wednesday", "Thursday", "Friday", "Saturday"
];
if (!patternStr) {
patternStr = 'M/d/yyyy';
}
var day = date.getDate(),
month = date.getMonth(),
year = date.getFullYear(),
hour = date.getHours(),
minute = date.getMinutes(),
second = date.getSeconds(),
miliseconds = date.getMilliseconds(),
h = hour % 12,
hh = twoDigitPad(h),
HH = twoDigitPad(hour),
mm = twoDigitPad(minute),
ss = twoDigitPad(second),
aaa = hour < 12 ? 'AM' : 'PM',
EEEE = dayOfWeekNames[date.getDay()],
EEE = EEEE.substring(0, 3),
dd = twoDigitPad(day),
M = month + 1,
MM = twoDigitPad(M),
MMMM = monthNames[month],
MMM = MMMM.substring(0, 3),
yyyy = year + "",
yy = yyyy.substring(2, 2);
// checks to see if month name will be used
if (patternStr.indexOf('MMM') <= -1) {
patternStr = patternStr
.replace('MM', MM)
.replace('M', String(M));
}
patternStr = patternStr
.replace('hh', hh).replace('h', String(h))
.replace('HH', HH).replace('H', String(hour))
.replace('mm', mm).replace('m', String(minute))
.replace('ss', ss).replace('s', String(second))
.replace('S', String(miliseconds))
.replace('dd', dd).replace('d', String(day))
.replace('EEEE', EEEE).replace('EEE', EEE)
.replace('yyyy', yyyy)
.replace('yy', yy)
.replace('aaa', aaa);
if (patternStr.indexOf('MMM') > -1) {
patternStr = patternStr
.replace('MMMM', MMMM)
.replace('MMM', MMM);
}
return patternStr;
}
export const enumerateDaysBetweenDates = (
startDate: Date,
endDate: Date
): Date[] => {
var dates: Date[] = [];
var currDate: Date;
let lastDate: Date;
currDate = startDate;
lastDate = endDate;
currDate.setHours(0, 0, 0, 0);
lastDate.setHours(0, 0, 0, 0);
dates.push(currDate);
var diff = getDiff(currDate, lastDate);
var testDate = currDate;
if (diff < 0) {
while (getDiff(testDate, lastDate) < 0) {
testDate = addDays(testDate, 1);
dates.push(testDate);
}
}
//dates.push(lastDate);
return dates;
};
export const enumerateStringDaysBetweenDates = (
startDate: Date,
endDate: Date
): string[] => {
var dates: string[] = [];
var currDate: Date;
let lastDate: Date;
currDate = startDate;
lastDate = endDate;
currDate.setHours(0, 0, 0, 0);
lastDate.setHours(0, 0, 0, 0);
dates.push(formatDate(currDate, 'dd-MMM-yyyy'));
var diff = getDiff(currDate, lastDate);
var testDate = currDate;
if (diff < 0) {
while (getDiff(testDate, lastDate) < 0) {
testDate = addDays(testDate, 1);
dates.push(formatDate(testDate, 'dd-MMM-yyyy'));
}
}
dates.push(formatDate(lastDate, 'dd-MMM-yyyy'));
return dates;
};
export const checkIfWeekendDay = (date: Date): boolean => {
var isWeekend = false;
var dayOfWeek = date.getDay();
isWeekend = (dayOfWeek === 6) || (dayOfWeek === 0);
return isWeekend;
}; | 26.469274 | 71 | 0.562685 | 145 | 11 | 0 | 21 | 52 | 0 | 4 | 1 | 13 | 0 | 0 | 10.272727 | 1,411 | 0.022679 | 0.036853 | 0 | 0 | 0 | 0.011905 | 0.154762 | 0.344184 | export /* Example usages of 'addDays' are shown below:
testDate = addDays(testDate, 1);
*/
const addDays = (date, days) => {
var result = new Date(date);
result.setDate(result.getDate() + days);
return result;
};
export const addMonths = (date, months) => {
var result = new Date(date);
result.setMonth(result.getMonth() + months);
return result;
};
export /* Example usages of 'getDiff' are shown below:
getDiff(currDate, lastDate);
getDiff(testDate, lastDate) < 0;
*/
const getDiff = (d1, d2) => {
var result = d1.getTime() - d2.getTime();
return result;
};
export const getDiffInDays = (d1, d2) => {
var result = d1.getTime() - d2.getTime();
return Math.ceil(result / (1000 * 60 * 60 * 24));;
};
export const daysMatch = (d1, d2) => {
return d1.getDate() == d2.getDate() &&
d1.getMonth() == d2.getMonth() &&
d1.getFullYear() == d2.getFullYear()
}
export const isDateBetweenDatesExcluding = (
startDate,
endDate,
checkDate
) => {
var isbetween = false;
if((checkDate < endDate && checkDate > startDate)) {
isbetween = true;
}
return isbetween;
};
export /* Example usages of 'twoDigitPad' are shown below:
twoDigitPad(h);
twoDigitPad(hour);
twoDigitPad(minute);
twoDigitPad(second);
twoDigitPad(day);
twoDigitPad(M);
*/
const twoDigitPad = (num) => {
return num < 10 ? ("0" + String(num)) : String(num);
}
export /* Example usages of 'formatDate' are shown below:
dates.push(formatDate(currDate, 'dd-MMM-yyyy'));
dates.push(formatDate(testDate, 'dd-MMM-yyyy'));
dates.push(formatDate(lastDate, 'dd-MMM-yyyy'));
*/
const formatDate = (date, patternStr) => {
var monthNames = [
"January", "February", "March", "April", "May", "June", "July",
"August", "September", "October", "November", "December"
];
var dayOfWeekNames = [
"Sunday", "Monday", "Tuesday",
"Wednesday", "Thursday", "Friday", "Saturday"
];
if (!patternStr) {
patternStr = 'M/d/yyyy';
}
var day = date.getDate(),
month = date.getMonth(),
year = date.getFullYear(),
hour = date.getHours(),
minute = date.getMinutes(),
second = date.getSeconds(),
miliseconds = date.getMilliseconds(),
h = hour % 12,
hh = twoDigitPad(h),
HH = twoDigitPad(hour),
mm = twoDigitPad(minute),
ss = twoDigitPad(second),
aaa = hour < 12 ? 'AM' : 'PM',
EEEE = dayOfWeekNames[date.getDay()],
EEE = EEEE.substring(0, 3),
dd = twoDigitPad(day),
M = month + 1,
MM = twoDigitPad(M),
MMMM = monthNames[month],
MMM = MMMM.substring(0, 3),
yyyy = year + "",
yy = yyyy.substring(2, 2);
// checks to see if month name will be used
if (patternStr.indexOf('MMM') <= -1) {
patternStr = patternStr
.replace('MM', MM)
.replace('M', String(M));
}
patternStr = patternStr
.replace('hh', hh).replace('h', String(h))
.replace('HH', HH).replace('H', String(hour))
.replace('mm', mm).replace('m', String(minute))
.replace('ss', ss).replace('s', String(second))
.replace('S', String(miliseconds))
.replace('dd', dd).replace('d', String(day))
.replace('EEEE', EEEE).replace('EEE', EEE)
.replace('yyyy', yyyy)
.replace('yy', yy)
.replace('aaa', aaa);
if (patternStr.indexOf('MMM') > -1) {
patternStr = patternStr
.replace('MMMM', MMMM)
.replace('MMM', MMM);
}
return patternStr;
}
export const enumerateDaysBetweenDates = (
startDate,
endDate
) => {
var dates = [];
var currDate;
let lastDate;
currDate = startDate;
lastDate = endDate;
currDate.setHours(0, 0, 0, 0);
lastDate.setHours(0, 0, 0, 0);
dates.push(currDate);
var diff = getDiff(currDate, lastDate);
var testDate = currDate;
if (diff < 0) {
while (getDiff(testDate, lastDate) < 0) {
testDate = addDays(testDate, 1);
dates.push(testDate);
}
}
//dates.push(lastDate);
return dates;
};
export const enumerateStringDaysBetweenDates = (
startDate,
endDate
) => {
var dates = [];
var currDate;
let lastDate;
currDate = startDate;
lastDate = endDate;
currDate.setHours(0, 0, 0, 0);
lastDate.setHours(0, 0, 0, 0);
dates.push(formatDate(currDate, 'dd-MMM-yyyy'));
var diff = getDiff(currDate, lastDate);
var testDate = currDate;
if (diff < 0) {
while (getDiff(testDate, lastDate) < 0) {
testDate = addDays(testDate, 1);
dates.push(formatDate(testDate, 'dd-MMM-yyyy'));
}
}
dates.push(formatDate(lastDate, 'dd-MMM-yyyy'));
return dates;
};
export const checkIfWeekendDay = (date) => {
var isWeekend = false;
var dayOfWeek = date.getDay();
isWeekend = (dayOfWeek === 6) || (dayOfWeek === 0);
return isWeekend;
}; |
0f41ac9b06678bb3cb4bd71f1290cca1c0a84859 | 4,672 | ts | TypeScript | src/checkGraduate/checkGrad.ts | oshamashama/ITFGraduationChecker | 34e62f5c970b12ae164796b69dab056dd99d0294 | [
"MIT"
] | 5 | 2022-02-01T10:25:26.000Z | 2022-02-09T09:15:26.000Z | src/checkGraduate/checkGrad.ts | oshamashama/ITFGraduationChecker | 34e62f5c970b12ae164796b69dab056dd99d0294 | [
"MIT"
] | 3 | 2022-02-01T16:42:21.000Z | 2022-02-12T12:55:00.000Z | src/checkGraduate/checkGrad.ts | oshamashama/ITFGraduationChecker | 34e62f5c970b12ae164796b69dab056dd99d0294 | [
"MIT"
] | 3 | 2022-02-01T11:05:56.000Z | 2022-02-09T09:08:33.000Z | const max = "max_certificated_credit_num";
const now = "now_certificated_credit_num";
//const min = 'min_certificated_credit_num';
const feature = "feature_certificated_credit_num";
const count_course = "count_course";
export function checkGraduate(grade, req, callback) {
for (let rishu = 0; rishu < 2; rishu++)
for (let hishu = 0; hishu < 2; hishu++)
for (const k1 in req) {
req[k1] = genNow(req[k1], rishu);
for (const k2 in req[k1]["leaf"]) {
req[k1]["leaf"][k2] = genNow(req[k1]["leaf"][k2], rishu);
for (const k3 in req[k1]["leaf"][k2]["leaf"]) {
req[k1]["leaf"][k2]["leaf"][k3] = genNow(
req[k1]["leaf"][k2]["leaf"][k3],
rishu
);
for (const k4 in req[k1]["leaf"][k2]["leaf"][k3]["leaf"]) {
if (
(k4 === "必修" && hishu === 0) ||
(k4 === "選択" && hishu === 1)
) {
req[k1]["leaf"][k2]["leaf"][k3]["leaf"][k4] = genNow(
req[k1]["leaf"][k2]["leaf"][k3]["leaf"][k4],
rishu
);
for (const k5 in req[k1]["leaf"][k2]["leaf"][k3]["leaf"][k4][
"leaf"
]) {
req[k1]["leaf"][k2]["leaf"][k3]["leaf"][k4]["leaf"][k5] =
genNow(
req[k1]["leaf"][k2]["leaf"][k3]["leaf"][k4]["leaf"][k5],
rishu
);
req[k1]["leaf"][k2]["leaf"][k3]["leaf"][k4]["leaf"][k5] =
checkGet(
grade,
req[k1]["leaf"][k2]["leaf"][k3]["leaf"][k4]["leaf"][k5],
rishu === 1
);
req[k1]["leaf"][k2]["leaf"][k3]["leaf"][k4][now] += Math.min(
rishu *
req[k1]["leaf"][k2]["leaf"][k3]["leaf"][k4]["leaf"][k5][
now
],
rishu *
req[k1]["leaf"][k2]["leaf"][k3]["leaf"][k4]["leaf"][k5][
max
]
);
req[k1]["leaf"][k2]["leaf"][k3]["leaf"][k4][feature] +=
hishu *
rishu *
req[k1]["leaf"][k2]["leaf"][k3]["leaf"][k4]["leaf"][k5][
feature
];
}
req[k1]["leaf"][k2]["leaf"][k3][now] += Math.min(
rishu * req[k1]["leaf"][k2]["leaf"][k3]["leaf"][k4][now],
rishu * req[k1]["leaf"][k2]["leaf"][k3]["leaf"][k4][max]
);
req[k1]["leaf"][k2]["leaf"][k3][feature] +=
hishu *
rishu *
req[k1]["leaf"][k2]["leaf"][k3]["leaf"][k4][feature];
}
}
req[k1]["leaf"][k2][now] += Math.min(
hishu * rishu * req[k1]["leaf"][k2]["leaf"][k3][now],
hishu * rishu * req[k1]["leaf"][k2]["leaf"][k3][max]
);
req[k1]["leaf"][k2][feature] +=
hishu * rishu * req[k1]["leaf"][k2]["leaf"][k3][feature];
}
req[k1][now] += Math.min(
hishu * rishu * req[k1]["leaf"][k2][now],
hishu * rishu * req[k1]["leaf"][k2][max]
);
req[k1][feature] += hishu * rishu * req[k1]["leaf"][k2][feature];
}
}
return req;
}
function genNow(req, rishu) {
if (req[now] === undefined) {
req[now] = 0;
req[feature] = 0;
req[count_course] = [];
}
return req;
}
function checkGet(grade, req, rishu) {
const reg_name = req["leaf"]["regexp_name"];
const reg_number = req["leaf"]["regexp_number"];
for (const key in grade) {
let flag = false;
if (reg_name !== "") {
const reg = new RegExp(reg_name);
if (grade[key]["course_name"].match(reg)) {
flag = true;
}
}
if (reg_number !== "") {
const reg = new RegExp(reg_number);
if (grade[key]["course_number"].match(reg)) {
flag = true;
}
}
if (flag) {
if (
grade[key]["used"] === false &&
grade[key]["used_rishu"] === false &&
req[now] < req[max]
) {
if (grade[key]["can_use"] === true) {
grade[key]["used"] = true;
req[now] += grade[key]["credit"];
req[count_course].push(grade[key]["course_name"]);
} else if (grade[key]["grade"] === "履修中" && rishu) {
grade[key]["used_rishu"] = true;
req[feature] += grade[key]["credit"];
}
}
}
}
return req;
}
| 35.664122 | 79 | 0.406464 | 126 | 3 | 0 | 8 | 11 | 0 | 2 | 0 | 0 | 0 | 0 | 38.666667 | 1,420 | 0.007746 | 0.007746 | 0 | 0 | 0 | 0 | 0 | 0.214115 | const max = "max_certificated_credit_num";
const now = "now_certificated_credit_num";
//const min = 'min_certificated_credit_num';
const feature = "feature_certificated_credit_num";
const count_course = "count_course";
export function checkGraduate(grade, req, callback) {
for (let rishu = 0; rishu < 2; rishu++)
for (let hishu = 0; hishu < 2; hishu++)
for (const k1 in req) {
req[k1] = genNow(req[k1], rishu);
for (const k2 in req[k1]["leaf"]) {
req[k1]["leaf"][k2] = genNow(req[k1]["leaf"][k2], rishu);
for (const k3 in req[k1]["leaf"][k2]["leaf"]) {
req[k1]["leaf"][k2]["leaf"][k3] = genNow(
req[k1]["leaf"][k2]["leaf"][k3],
rishu
);
for (const k4 in req[k1]["leaf"][k2]["leaf"][k3]["leaf"]) {
if (
(k4 === "必修" && hishu === 0) ||
(k4 === "選択" && hishu === 1)
) {
req[k1]["leaf"][k2]["leaf"][k3]["leaf"][k4] = genNow(
req[k1]["leaf"][k2]["leaf"][k3]["leaf"][k4],
rishu
);
for (const k5 in req[k1]["leaf"][k2]["leaf"][k3]["leaf"][k4][
"leaf"
]) {
req[k1]["leaf"][k2]["leaf"][k3]["leaf"][k4]["leaf"][k5] =
genNow(
req[k1]["leaf"][k2]["leaf"][k3]["leaf"][k4]["leaf"][k5],
rishu
);
req[k1]["leaf"][k2]["leaf"][k3]["leaf"][k4]["leaf"][k5] =
checkGet(
grade,
req[k1]["leaf"][k2]["leaf"][k3]["leaf"][k4]["leaf"][k5],
rishu === 1
);
req[k1]["leaf"][k2]["leaf"][k3]["leaf"][k4][now] += Math.min(
rishu *
req[k1]["leaf"][k2]["leaf"][k3]["leaf"][k4]["leaf"][k5][
now
],
rishu *
req[k1]["leaf"][k2]["leaf"][k3]["leaf"][k4]["leaf"][k5][
max
]
);
req[k1]["leaf"][k2]["leaf"][k3]["leaf"][k4][feature] +=
hishu *
rishu *
req[k1]["leaf"][k2]["leaf"][k3]["leaf"][k4]["leaf"][k5][
feature
];
}
req[k1]["leaf"][k2]["leaf"][k3][now] += Math.min(
rishu * req[k1]["leaf"][k2]["leaf"][k3]["leaf"][k4][now],
rishu * req[k1]["leaf"][k2]["leaf"][k3]["leaf"][k4][max]
);
req[k1]["leaf"][k2]["leaf"][k3][feature] +=
hishu *
rishu *
req[k1]["leaf"][k2]["leaf"][k3]["leaf"][k4][feature];
}
}
req[k1]["leaf"][k2][now] += Math.min(
hishu * rishu * req[k1]["leaf"][k2]["leaf"][k3][now],
hishu * rishu * req[k1]["leaf"][k2]["leaf"][k3][max]
);
req[k1]["leaf"][k2][feature] +=
hishu * rishu * req[k1]["leaf"][k2]["leaf"][k3][feature];
}
req[k1][now] += Math.min(
hishu * rishu * req[k1]["leaf"][k2][now],
hishu * rishu * req[k1]["leaf"][k2][max]
);
req[k1][feature] += hishu * rishu * req[k1]["leaf"][k2][feature];
}
}
return req;
}
/* Example usages of 'genNow' are shown below:
req[k1] = genNow(req[k1], rishu);
req[k1]["leaf"][k2] = genNow(req[k1]["leaf"][k2], rishu);
req[k1]["leaf"][k2]["leaf"][k3] = genNow(req[k1]["leaf"][k2]["leaf"][k3], rishu);
req[k1]["leaf"][k2]["leaf"][k3]["leaf"][k4] = genNow(req[k1]["leaf"][k2]["leaf"][k3]["leaf"][k4], rishu);
req[k1]["leaf"][k2]["leaf"][k3]["leaf"][k4]["leaf"][k5] =
genNow(req[k1]["leaf"][k2]["leaf"][k3]["leaf"][k4]["leaf"][k5], rishu);
*/
function genNow(req, rishu) {
if (req[now] === undefined) {
req[now] = 0;
req[feature] = 0;
req[count_course] = [];
}
return req;
}
/* Example usages of 'checkGet' are shown below:
req[k1]["leaf"][k2]["leaf"][k3]["leaf"][k4]["leaf"][k5] =
checkGet(grade, req[k1]["leaf"][k2]["leaf"][k3]["leaf"][k4]["leaf"][k5], rishu === 1);
*/
function checkGet(grade, req, rishu) {
const reg_name = req["leaf"]["regexp_name"];
const reg_number = req["leaf"]["regexp_number"];
for (const key in grade) {
let flag = false;
if (reg_name !== "") {
const reg = new RegExp(reg_name);
if (grade[key]["course_name"].match(reg)) {
flag = true;
}
}
if (reg_number !== "") {
const reg = new RegExp(reg_number);
if (grade[key]["course_number"].match(reg)) {
flag = true;
}
}
if (flag) {
if (
grade[key]["used"] === false &&
grade[key]["used_rishu"] === false &&
req[now] < req[max]
) {
if (grade[key]["can_use"] === true) {
grade[key]["used"] = true;
req[now] += grade[key]["credit"];
req[count_course].push(grade[key]["course_name"]);
} else if (grade[key]["grade"] === "履修中" && rishu) {
grade[key]["used_rishu"] = true;
req[feature] += grade[key]["credit"];
}
}
}
}
return req;
}
|
0f9d7f1cb3beb38aa2abd1a7f09d7ce602290158 | 1,291 | ts | TypeScript | src/shorten-uuid.ts | Cweili/shorten-uuid | a98298ac1d6f3d7c25b450ec436974bd1917391b | [
"MIT"
] | null | null | null | src/shorten-uuid.ts | Cweili/shorten-uuid | a98298ac1d6f3d7c25b450ec436974bd1917391b | [
"MIT"
] | 4 | 2022-02-07T21:23:50.000Z | 2022-03-28T21:23:13.000Z | src/shorten-uuid.ts | Cweili/shorten-uuid | a98298ac1d6f3d7c25b450ec436974bd1917391b | [
"MIT"
] | null | null | null | export default function uuidShorten(
characters: string = '-0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ_abcdefghijklmnopqrstuvwxyz',
) {
function encodeIntTo64(int: number) {
const c: string[] = [];
while (int > 0) {
c.unshift(characters[int & 0x3f]);
int >>>= 6;
}
return c.join('');
}
function decode64ToInt(base64String: string) {
const len = base64String.length;
let int = 0;
for (let i = 0; i < len; i++) {
int <<= 6;
int += characters.indexOf(base64String[i]);
}
return int;
}
return {
encode(uuid: string) {
const stripDashed = uuid.replace(/-/g, '');
const arr: string[] = [];
for (let i = 0; i < 8; i++) {
arr.push(
encodeIntTo64(
parseInt(stripDashed.substr(i * 4, 4), 16),
).padStart(3, characters[0]),
);
}
return arr.join('');
},
decode(shortString: string) {
const arr: string[] = [];
for (let i = 0; i < 8; i++) {
if (i > 1 && i < 6) {
arr.push('-');
}
arr.push(
decode64ToInt(
shortString.substr(i * 3, 3),
).toString(16).padStart(4, '0'),
);
}
return arr.join('');
},
encodeIntTo64,
decode64ToInt,
};
}
| 23.053571 | 90 | 0.50426 | 51 | 5 | 0 | 5 | 9 | 0 | 2 | 0 | 8 | 0 | 0 | 16.4 | 402 | 0.024876 | 0.022388 | 0 | 0 | 0 | 0 | 0.421053 | 0.301418 | export default function uuidShorten(
characters = '-0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ_abcdefghijklmnopqrstuvwxyz',
) {
/* Example usages of 'encodeIntTo64' are shown below:
arr.push(encodeIntTo64(parseInt(stripDashed.substr(i * 4, 4), 16)).padStart(3, characters[0]));
;
*/
function encodeIntTo64(int) {
const c = [];
while (int > 0) {
c.unshift(characters[int & 0x3f]);
int >>>= 6;
}
return c.join('');
}
/* Example usages of 'decode64ToInt' are shown below:
arr.push(decode64ToInt(shortString.substr(i * 3, 3)).toString(16).padStart(4, '0'));
;
*/
function decode64ToInt(base64String) {
const len = base64String.length;
let int = 0;
for (let i = 0; i < len; i++) {
int <<= 6;
int += characters.indexOf(base64String[i]);
}
return int;
}
return {
encode(uuid) {
const stripDashed = uuid.replace(/-/g, '');
const arr = [];
for (let i = 0; i < 8; i++) {
arr.push(
encodeIntTo64(
parseInt(stripDashed.substr(i * 4, 4), 16),
).padStart(3, characters[0]),
);
}
return arr.join('');
},
decode(shortString) {
const arr = [];
for (let i = 0; i < 8; i++) {
if (i > 1 && i < 6) {
arr.push('-');
}
arr.push(
decode64ToInt(
shortString.substr(i * 3, 3),
).toString(16).padStart(4, '0'),
);
}
return arr.join('');
},
encodeIntTo64,
decode64ToInt,
};
}
|
0ff1bf2fb61d373c6e912ff68629025aaef98f8b | 2,672 | ts | TypeScript | functions/remark-functions-channels/lib/dbQueries.ts | triszt4n/remark | 6b2f422b2af25b32cdc3b4941269ae48329b3fd6 | [
"MIT"
] | null | null | null | functions/remark-functions-channels/lib/dbQueries.ts | triszt4n/remark | 6b2f422b2af25b32cdc3b4941269ae48329b3fd6 | [
"MIT"
] | 15 | 2022-02-16T16:53:35.000Z | 2022-03-28T08:46:24.000Z | functions/remark-functions-channels/lib/dbQueries.ts | triszt4n/remark | 6b2f422b2af25b32cdc3b4941269ae48329b3fd6 | [
"MIT"
] | null | null | null | export const createQueryForPostCountOfChannel = (id: string) => ({
query: 'SELECT COUNT(p.id) AS postsCount FROM Posts p WHERE p.parentChannelId = @id',
parameters: [
{
name: '@id',
value: id
}
]
})
export const createQueryForJoinCountOfChannel = (id: string) => ({
query: 'SELECT COUNT(cj.id) AS joinCount FROM ChannelJoins cj WHERE cj.channelId = @id',
parameters: [
{
name: '@id',
value: id
}
]
})
export const createQueryExistsJoinOfUserIdAndChannelId = (userId: string, channelId: string) => ({
query: 'SELECT * FROM ChannelJoins cj WHERE cj.userId = @userId AND cj.channelId = @channelId',
parameters: [
{
name: '@userId',
value: userId
},
{
name: '@channelId',
value: channelId
}
]
})
export const createQueryChannelJoinsOfUserId = (userId: string) => ({
query: 'SELECT * FROM ChannelJoins cj WHERE cj.userId = @userId',
parameters: [
{
name: '@userId',
value: userId
}
]
})
export const createModInfoQueryByUriName = (uriName: string) => ({
query: 'SELECT c.ownerId, c.moderatorIds FROM Channels c WHERE UPPER(c.uriName) = UPPER(@uriName)',
parameters: [
{
name: '@uriName',
value: uriName
}
]
})
export const createQueryByUriName = (uriName: string) => ({
query: 'SELECT c.id FROM Channels c WHERE UPPER(c.uriName) = UPPER(@uriName)',
parameters: [
{
name: '@uriName',
value: uriName
}
]
})
export const createQueryByModeratorIds = (moderatorIds: string[]) => ({
query: 'SELECT * FROM Users u WHERE ARRAY_CONTAINS(@moderatorIds, u.id)',
parameters: [
{
name: '@moderatorIds',
value: moderatorIds
}
]
})
// select for ChannelPartial
export const createQueryByChannelIds = (channelIds: string[]) => ({
query: 'SELECT c.id, c.uriName, c.title FROM Channels c WHERE ARRAY_CONTAINS(@channelIds, c.id)',
parameters: [
{
name: '@channelIds',
value: channelIds
}
]
})
export const createQueryPostsOfChannel = (channelId: string) => ({
query: 'SELECT * FROM Posts p WHERE p.parentChannelId = @channelId',
parameters: [
{
name: '@channelId',
value: channelId
}
]
})
export const createQueryChannelJoinsOfChannel = (channelId: string) => ({
query: 'SELECT * FROM ChannelJoins cj WHERE cj.channelId = @channelId',
parameters: [
{
name: '@channelId',
value: channelId
}
]
})
export const createQueryUserByUsername = (username: string) => ({
query: 'SELECT * FROM Users u WHERE u.username = @username',
parameters: [
{
name: '@username',
value: username
}
]
})
| 23.234783 | 101 | 0.623503 | 103 | 11 | 0 | 12 | 11 | 0 | 0 | 0 | 12 | 0 | 0 | 9.363636 | 757 | 0.030383 | 0.014531 | 0 | 0 | 0 | 0 | 0.352941 | 0.288176 | export const createQueryForPostCountOfChannel = (id) => ({
query: 'SELECT COUNT(p.id) AS postsCount FROM Posts p WHERE p.parentChannelId = @id',
parameters: [
{
name: '@id',
value: id
}
]
})
export const createQueryForJoinCountOfChannel = (id) => ({
query: 'SELECT COUNT(cj.id) AS joinCount FROM ChannelJoins cj WHERE cj.channelId = @id',
parameters: [
{
name: '@id',
value: id
}
]
})
export const createQueryExistsJoinOfUserIdAndChannelId = (userId, channelId) => ({
query: 'SELECT * FROM ChannelJoins cj WHERE cj.userId = @userId AND cj.channelId = @channelId',
parameters: [
{
name: '@userId',
value: userId
},
{
name: '@channelId',
value: channelId
}
]
})
export const createQueryChannelJoinsOfUserId = (userId) => ({
query: 'SELECT * FROM ChannelJoins cj WHERE cj.userId = @userId',
parameters: [
{
name: '@userId',
value: userId
}
]
})
export const createModInfoQueryByUriName = (uriName) => ({
query: 'SELECT c.ownerId, c.moderatorIds FROM Channels c WHERE UPPER(c.uriName) = UPPER(@uriName)',
parameters: [
{
name: '@uriName',
value: uriName
}
]
})
export const createQueryByUriName = (uriName) => ({
query: 'SELECT c.id FROM Channels c WHERE UPPER(c.uriName) = UPPER(@uriName)',
parameters: [
{
name: '@uriName',
value: uriName
}
]
})
export const createQueryByModeratorIds = (moderatorIds) => ({
query: 'SELECT * FROM Users u WHERE ARRAY_CONTAINS(@moderatorIds, u.id)',
parameters: [
{
name: '@moderatorIds',
value: moderatorIds
}
]
})
// select for ChannelPartial
export const createQueryByChannelIds = (channelIds) => ({
query: 'SELECT c.id, c.uriName, c.title FROM Channels c WHERE ARRAY_CONTAINS(@channelIds, c.id)',
parameters: [
{
name: '@channelIds',
value: channelIds
}
]
})
export const createQueryPostsOfChannel = (channelId) => ({
query: 'SELECT * FROM Posts p WHERE p.parentChannelId = @channelId',
parameters: [
{
name: '@channelId',
value: channelId
}
]
})
export const createQueryChannelJoinsOfChannel = (channelId) => ({
query: 'SELECT * FROM ChannelJoins cj WHERE cj.channelId = @channelId',
parameters: [
{
name: '@channelId',
value: channelId
}
]
})
export const createQueryUserByUsername = (username) => ({
query: 'SELECT * FROM Users u WHERE u.username = @username',
parameters: [
{
name: '@username',
value: username
}
]
})
|
3c537a8009ff7cec25f5cbbe0f35eab19fd1530d | 12,837 | ts | TypeScript | juvy.ts | brianjenkins94/juvy | 06a124dfdbbc25aca620d5bb1119746ccf30aea2 | [
"MIT"
] | 1 | 2022-03-05T23:43:13.000Z | 2022-03-05T23:43:13.000Z | juvy.ts | brianjenkins94/juvy | 06a124dfdbbc25aca620d5bb1119746ccf30aea2 | [
"MIT"
] | null | null | null | juvy.ts | brianjenkins94/juvy | 06a124dfdbbc25aca620d5bb1119746ccf30aea2 | [
"MIT"
] | null | null | null | // @ts-nocheck
/* eslint-disable complexity */
function cloneDeep(object) {
if (typeof object !== "object" || object === null) {
return object;
}
const clone = Array.isArray(object) ? [] : {};
for (const [key, value] of Object.entries(object)) {
if (Array.isArray(value)) {
clone[key] = [];
for (const element of value) {
if (typeof element === "object" && element !== null) {
clone[key].push(cloneDeep(element));
} else {
clone[key].push(element);
}
}
} else if (typeof value === "object" && value !== null) {
clone[key] = cloneDeep(value);
} else {
clone[key] = value;
}
}
return clone;
}
function getOrCreateKeyOfObjectByPath(object, path) {
return path.reduce(function(object, key) {
if (object[key] === undefined) {
object[key] = {};
}
return object[key];
}, object);
}
function getKeyOfObjectByPath(object, path) {
return path.reduce(function(object, key) {
if (!Object.prototype.hasOwnProperty.call(object, key)) {
throw new TypeError("Cannot read properties of undefined (reading '" + key + "')");
}
return object[key];
}, object);
}
class Juvy {
private static readonly BUILT_INS = {
"Array": Array,
"Boolean": Boolean,
"Number": Number,
"Object": Object,
"RegExp": RegExp,
"String": String
};
private readonly _schema = {
"_juvyProperties": {}
};
private readonly _env = {};
private readonly _argv = {};
private readonly _instance = {};
private readonly options = {};
private readonly types = {
"*": function() { },
"int": function(x) {
console.assert(Number.isInteger(x), "must be an integer");
},
"integer": function(x) {
console.assert(Number.isInteger(x), "must be an integer");
},
"nat": function(x) {
console.assert(Number.isInteger(x) && x >= 0, "must be a positive integer");
},
"port": function(x) {
console.assert(Number.isInteger(x) && x >= 0 && x <= 65535, "ports must be within range 0 - 65535");
}
};
public constructor(def, options = { "strict": true }) {
this.options["strict"] = options["strict"] ?? true;
for (const [key, value] of Object.entries(def)) {
const { types } = this;
// ???
(function normalizeSchema(key, value, props, fullName, env, argv) {
if (key === "_juvyProperties") {
throw new Error("'" + fullName + "': `_juvyProperties` is reserved word of juvy.");
}
// If the current schema node is not a config property (has no "default"), recursively normalize it.
if (typeof value === "object" && value !== null && !Array.isArray(value) && Object.keys(value).length > 0 && !("default" in value)) {
props[key] = {
"_juvyProperties": {}
};
Object.keys(value).forEach(function(k) {
normalizeSchema(k, value[k], props[key]._juvyProperties, fullName + "." + k, env, argv);
});
return;
} else if (typeof value !== "object" || Array.isArray(value) || value === null || Object.keys(value).length === 0) {
// Normalize shorthand "value" config properties
value = { "default": value };
}
const o = cloneDeep(value);
props[key] = o;
// Associate this property with an environmental variable
if (o.env) {
if (!env[o.env]) {
env[o.env] = [];
}
env[o.env].push(fullName);
}
// Associate this property with a command-line argument
if (o.arg) {
argv[o.arg] = fullName;
}
// store original format function
const format = o.format;
let newFormat;
if (Object.keys(Juvy.BUILT_INS).includes(format) || Object.values(Juvy.BUILT_INS).includes(format)) {
// If the format property is a built-in JavaScript constructor,
// assert that the value is of that type
const Format = typeof format === "string" ? Juvy.BUILT_INS[format] : format;
newFormat = function(x) {
console.assert(Object.prototype.toString.call(x) === Object.prototype.toString.call(new Format()), "must be of type " + Format.name);
};
o.format = Format.name.toLowerCase();
} else if (typeof format === "string") {
// Store declared type
if (!types[format]) {
throw new Error("'" + fullName + "' uses an unknown format type: " + format);
}
// Use a predefined type
newFormat = types[format];
} else if (Array.isArray(format)) {
// Assert that the value is a valid option
newFormat = (function contains(options, x) {
console.assert(options.indexOf(x) !== -1, "must be one of the possible values: " + JSON.stringify(options));
}).bind(null, format);
} else if (typeof format === "function") {
newFormat = format;
} else if (format && typeof format !== "function") {
throw new Error("'" + fullName + "': `format` must be a function or a known format type.");
}
if (!newFormat && !format) {
// Default format is the typeof the default value
const type = Object.prototype.toString.call(o.default);
newFormat = function(x) {
console.assert(Object.prototype.toString.call(x) === type, " should be of type " + type.replace(/\[.* \]/gu, ""));
};
}
o._format = function(x) {
// Accept null if allowed before calling any format function
if (this.nullable && x === null) {
return;
}
try {
newFormat(x, this);
} catch (e) {
// Attach the value and the property's fullName to the error
e.fullName = fullName;
e.value = x;
throw e;
}
};
})(key, value, this._schema._juvyProperties, key, this._env, this._argv);
}
// ???
(function addDefaultValues(schema, c, instance) {
for (const [key, value] of Object.entries(schema._juvyProperties)) {
if (value["_juvyProperties"]) {
const kids = c[key] || {};
addDefaultValues(value, kids, instance);
c[key] = kids;
} else {
c[key] = Juvy.coerce(key, cloneDeep(value["default"]), schema);
}
}
})(this._schema, this._instance, this);
Juvy.importEnvironment(this);
Juvy.importArguments(this);
}
// ???
private static coerce(path, value, schema) {
const ar = path.split(".");
let o = schema;
while (ar.length > 0) {
const k = ar.shift();
if (o?._juvyProperties?.[k]) {
o = o._juvyProperties[k];
} else {
o = null;
break;
}
}
let format;
if (o === null || o === undefined) { // added || === undefined
format = null;
} else if (typeof o.format === "string") {
format = o.format;
} else if (o.default !== null && o.default !== undefined) { // added && !== undefined
format = typeof o.default;
} else {
format = null;
}
if (typeof value === "string") {
switch (format) {
case "int":
case "integer":
case "nat":
case "port":
value = parseInt(value);
break;
case "number":
value = parseFloat(value);
break;
case "boolean":
value = String(value).toLowerCase() !== "false";
break;
case "array":
value = value.split(",");
break;
case "object":
value = JSON.parse(value);
break;
case "regexp":
value = new RegExp(value, "u");
break;
default:
//console.warn("No match for format: `" + format + "`");
}
}
return value;
}
private static importEnvironment(o) {
const env = process.env;
for (const [key, value] of Object.entries(o._env)) {
if (env[key] !== undefined) {
for (const k of value) {
o.set(k, env[key]);
}
}
}
}
private static importArguments(o) {
const argv = (function parseArgs(args) {
const argv = {};
args = args.join(" ").match(/-(.*?)(?= +-|$)/gu) || [];
for (let x = 0; x < args.length; x++) {
const arg = args[x];
if (arg[1] !== "-") {
for (const shorthand of arg.substring(1).split("")) {
argv[shorthand] = true;
}
continue;
} else if (arg.length === 2) {
break;
}
const value = arg.split(/ +|=/u);
const key = value.shift().replace(/^-+/u, "");
argv[key] = value.join(" ") ?? (args[x + 1] === undefined || args[x + 1].startsWith("-") || args[x + 1]);
}
return argv;
})(process.argv);
for (const [key, value] of Object.entries(o._argv)) {
if (argv[key] !== undefined) {
o.set(value, String(argv[key]));
}
}
}
public getProperties() {
return cloneDeep(this._instance);
}
public getSchema() {
return JSON.parse(JSON.stringify(this._schema));
}
public get(path) {
return cloneDeep(getKeyOfObjectByPath(this._instance, path.split(".")));
}
public default(path) {
path = (path.split(".").join("._juvyProperties.") + ".default").split(".");
return cloneDeep(getKeyOfObjectByPath(this._schema._juvyProperties, path));
}
public reset(name) {
this.set(name, this.default(name));
}
public has(path) {
return Object.keys(this.getProperties()).includes(path);
}
public set(name, value) {
value = Juvy.coerce(name, value, this._schema);
const parent = name.split(".");
const child = parent.pop();
if (parent !== "__proto__" && parent !== "constructor" && parent !== "prototype") {
getOrCreateKeyOfObjectByPath(this._instance, parent)[child] = value;
}
return this;
}
public load(conf) {
this.overlay(conf, this._instance, this._schema);
// Environment and arguments always overrides config files
Juvy.importEnvironment(this);
Juvy.importArguments(this);
return this;
}
// ???
public overlay(from, to, schema) {
for (const key of Object.keys(from)) {
// Leaf
if (Array.isArray(from[key]) || !(typeof from[key] === "object" && from[key] !== null) || !schema || schema.format === "object") {
to[key] = Juvy.coerce(key, from[key], schema);
} else {
if (!(typeof to[key] === "object" && to[key] !== null)) {
to[key] = {};
}
this.overlay(from[key], to[key], schema._juvyProperties[key]);
}
}
}
// ???
public validate(options = this.options) {
function flatten(obj, useProperties) {
let key;
const entries = [];
for (const stack = Object.keys(obj); stack.length > 0;) {
key = stack.shift();
let value = getKeyOfObjectByPath(obj, key.split("."));
if (typeof value === "object" && !Array.isArray(value) && value !== null && value !== undefined) { // added && !== undefined
if (useProperties) {
if ("_juvyProperties" in value) {
value = value._juvyProperties;
key += "._juvyProperties";
} else {
entries.push([key, value]);
continue;
}
}
const subkeys = Object.keys(value);
// Don't filter out empty objects
if (subkeys.length > 0) {
for (const subkey of subkeys) {
stack.push(key + "." + subkey);
}
continue;
}
}
entries.push([key, value]);
}
const flattened = {};
for (let [key, value] of entries) {
if (useProperties) {
key = key.replace(/\._juvyProperties/gu, "u");
}
flattened[key] = value;
}
return flattened;
}
const flatInstance = flatten(this._instance);
const flatSchema = flatten(this._schema._juvyProperties, true);
for (const name of Object.keys(flatSchema)) {
const schemaItem = flatSchema[name];
let instanceItem = flatInstance[name];
if (!(name in flatInstance)) {
try {
if (typeof schemaItem.default === "object" && !Array.isArray(schemaItem.default)) {
// Missing item may be an object with undeclared children, so try to
// pull it unflattened from the config instance for type validation
instanceItem = getKeyOfObjectByPath(this._instance, name.split("."));
} else {
throw new Error("missing");
}
} catch (e) {
const err = new Error("configuration param '" + name + "' missing from config, did you override its parent?");
//errors.missing.push(err)
return;
}
}
delete flatInstance[name];
// Ignore nested keys of schema `object` properties
if (schemaItem.format === "object" || typeof schemaItem.default === "object") {
const keys = Object.keys(flatInstance).filter(function(key) {
return key.lastIndexOf(name + ".", 0) === 0;
});
for (const key of keys) {
delete flatInstance[key];
}
}
if (typeof schemaItem.default !== undefined && instanceItem !== schemaItem.default) {
try {
schemaItem._format(instanceItem);
} catch (err) {
//errors.invalid_type.push(err)
}
}
}
if (options["strict"]) {
for (const name of Object.keys(flatInstance)) {
const err = new Error("configuration param '" + name + "' not declared in the schema");
//errors.undeclared.push(err)
}
}
return this;
}
}
for (const method of [
"addFormat",
"addFormats",
"addParser",
"getArgs",
"getEnv",
"getSchemaString",
"loadFile",
"toString"
]) {
Juvy[method] = function() {
throw new Error("Removed");
};
}
export function juvy(schema) {
return new Juvy(schema);
}
| 25.319527 | 139 | 0.596713 | 382 | 36 | 0 | 51 | 34 | 7 | 15 | 0 | 0 | 1 | 18 | 12.555556 | 4,061 | 0.021423 | 0.008372 | 0.001724 | 0.000246 | 0.004432 | 0 | 0 | 0.251108 | // @ts-nocheck
/* eslint-disable complexity */
/* Example usages of 'cloneDeep' are shown below:
clone[key].push(cloneDeep(element));
clone[key] = cloneDeep(value);
cloneDeep(value);
c[key] = Juvy.coerce(key, cloneDeep(value["default"]), schema);
cloneDeep(this._instance);
cloneDeep(getKeyOfObjectByPath(this._instance, path.split(".")));
cloneDeep(getKeyOfObjectByPath(this._schema._juvyProperties, path));
*/
function cloneDeep(object) {
if (typeof object !== "object" || object === null) {
return object;
}
const clone = Array.isArray(object) ? [] : {};
for (const [key, value] of Object.entries(object)) {
if (Array.isArray(value)) {
clone[key] = [];
for (const element of value) {
if (typeof element === "object" && element !== null) {
clone[key].push(cloneDeep(element));
} else {
clone[key].push(element);
}
}
} else if (typeof value === "object" && value !== null) {
clone[key] = cloneDeep(value);
} else {
clone[key] = value;
}
}
return clone;
}
/* Example usages of 'getOrCreateKeyOfObjectByPath' are shown below:
getOrCreateKeyOfObjectByPath(this._instance, parent)[child] = value;
*/
function getOrCreateKeyOfObjectByPath(object, path) {
return path.reduce(function(object, key) {
if (object[key] === undefined) {
object[key] = {};
}
return object[key];
}, object);
}
/* Example usages of 'getKeyOfObjectByPath' are shown below:
cloneDeep(getKeyOfObjectByPath(this._instance, path.split(".")));
cloneDeep(getKeyOfObjectByPath(this._schema._juvyProperties, path));
getKeyOfObjectByPath(obj, key.split("."));
// Missing item may be an object with undeclared children, so try to
// pull it unflattened from the config instance for type validation
instanceItem = getKeyOfObjectByPath(this._instance, name.split("."));
*/
function getKeyOfObjectByPath(object, path) {
return path.reduce(function(object, key) {
if (!Object.prototype.hasOwnProperty.call(object, key)) {
throw new TypeError("Cannot read properties of undefined (reading '" + key + "')");
}
return object[key];
}, object);
}
class Juvy {
private static readonly BUILT_INS = {
"Array": Array,
"Boolean": Boolean,
"Number": Number,
"Object": Object,
"RegExp": RegExp,
"String": String
};
private readonly _schema = {
"_juvyProperties": {}
};
private readonly _env = {};
private readonly _argv = {};
private readonly _instance = {};
private readonly options = {};
private readonly types = {
"*": function() { },
"int": function(x) {
console.assert(Number.isInteger(x), "must be an integer");
},
"integer": function(x) {
console.assert(Number.isInteger(x), "must be an integer");
},
"nat": function(x) {
console.assert(Number.isInteger(x) && x >= 0, "must be a positive integer");
},
"port": function(x) {
console.assert(Number.isInteger(x) && x >= 0 && x <= 65535, "ports must be within range 0 - 65535");
}
};
public constructor(def, options = { "strict": true }) {
this.options["strict"] = options["strict"] ?? true;
for (const [key, value] of Object.entries(def)) {
const { types } = this;
// ???
(function normalizeSchema(key, value, props, fullName, env, argv) {
if (key === "_juvyProperties") {
throw new Error("'" + fullName + "': `_juvyProperties` is reserved word of juvy.");
}
// If the current schema node is not a config property (has no "default"), recursively normalize it.
if (typeof value === "object" && value !== null && !Array.isArray(value) && Object.keys(value).length > 0 && !("default" in value)) {
props[key] = {
"_juvyProperties": {}
};
Object.keys(value).forEach(function(k) {
normalizeSchema(k, value[k], props[key]._juvyProperties, fullName + "." + k, env, argv);
});
return;
} else if (typeof value !== "object" || Array.isArray(value) || value === null || Object.keys(value).length === 0) {
// Normalize shorthand "value" config properties
value = { "default": value };
}
const o = cloneDeep(value);
props[key] = o;
// Associate this property with an environmental variable
if (o.env) {
if (!env[o.env]) {
env[o.env] = [];
}
env[o.env].push(fullName);
}
// Associate this property with a command-line argument
if (o.arg) {
argv[o.arg] = fullName;
}
// store original format function
const format = o.format;
let newFormat;
if (Object.keys(Juvy.BUILT_INS).includes(format) || Object.values(Juvy.BUILT_INS).includes(format)) {
// If the format property is a built-in JavaScript constructor,
// assert that the value is of that type
const Format = typeof format === "string" ? Juvy.BUILT_INS[format] : format;
newFormat = function(x) {
console.assert(Object.prototype.toString.call(x) === Object.prototype.toString.call(new Format()), "must be of type " + Format.name);
};
o.format = Format.name.toLowerCase();
} else if (typeof format === "string") {
// Store declared type
if (!types[format]) {
throw new Error("'" + fullName + "' uses an unknown format type: " + format);
}
// Use a predefined type
newFormat = types[format];
} else if (Array.isArray(format)) {
// Assert that the value is a valid option
newFormat = (function contains(options, x) {
console.assert(options.indexOf(x) !== -1, "must be one of the possible values: " + JSON.stringify(options));
}).bind(null, format);
} else if (typeof format === "function") {
newFormat = format;
} else if (format && typeof format !== "function") {
throw new Error("'" + fullName + "': `format` must be a function or a known format type.");
}
if (!newFormat && !format) {
// Default format is the typeof the default value
const type = Object.prototype.toString.call(o.default);
newFormat = function(x) {
console.assert(Object.prototype.toString.call(x) === type, " should be of type " + type.replace(/\[.* \]/gu, ""));
};
}
o._format = function(x) {
// Accept null if allowed before calling any format function
if (this.nullable && x === null) {
return;
}
try {
newFormat(x, this);
} catch (e) {
// Attach the value and the property's fullName to the error
e.fullName = fullName;
e.value = x;
throw e;
}
};
})(key, value, this._schema._juvyProperties, key, this._env, this._argv);
}
// ???
(function addDefaultValues(schema, c, instance) {
for (const [key, value] of Object.entries(schema._juvyProperties)) {
if (value["_juvyProperties"]) {
const kids = c[key] || {};
addDefaultValues(value, kids, instance);
c[key] = kids;
} else {
c[key] = Juvy.coerce(key, cloneDeep(value["default"]), schema);
}
}
})(this._schema, this._instance, this);
Juvy.importEnvironment(this);
Juvy.importArguments(this);
}
// ???
private static coerce(path, value, schema) {
const ar = path.split(".");
let o = schema;
while (ar.length > 0) {
const k = ar.shift();
if (o?._juvyProperties?.[k]) {
o = o._juvyProperties[k];
} else {
o = null;
break;
}
}
let format;
if (o === null || o === undefined) { // added || === undefined
format = null;
} else if (typeof o.format === "string") {
format = o.format;
} else if (o.default !== null && o.default !== undefined) { // added && !== undefined
format = typeof o.default;
} else {
format = null;
}
if (typeof value === "string") {
switch (format) {
case "int":
case "integer":
case "nat":
case "port":
value = parseInt(value);
break;
case "number":
value = parseFloat(value);
break;
case "boolean":
value = String(value).toLowerCase() !== "false";
break;
case "array":
value = value.split(",");
break;
case "object":
value = JSON.parse(value);
break;
case "regexp":
value = new RegExp(value, "u");
break;
default:
//console.warn("No match for format: `" + format + "`");
}
}
return value;
}
private static importEnvironment(o) {
const env = process.env;
for (const [key, value] of Object.entries(o._env)) {
if (env[key] !== undefined) {
for (const k of value) {
o.set(k, env[key]);
}
}
}
}
private static importArguments(o) {
const argv = (function parseArgs(args) {
const argv = {};
args = args.join(" ").match(/-(.*?)(?= +-|$)/gu) || [];
for (let x = 0; x < args.length; x++) {
const arg = args[x];
if (arg[1] !== "-") {
for (const shorthand of arg.substring(1).split("")) {
argv[shorthand] = true;
}
continue;
} else if (arg.length === 2) {
break;
}
const value = arg.split(/ +|=/u);
const key = value.shift().replace(/^-+/u, "");
argv[key] = value.join(" ") ?? (args[x + 1] === undefined || args[x + 1].startsWith("-") || args[x + 1]);
}
return argv;
})(process.argv);
for (const [key, value] of Object.entries(o._argv)) {
if (argv[key] !== undefined) {
o.set(value, String(argv[key]));
}
}
}
public getProperties() {
return cloneDeep(this._instance);
}
public getSchema() {
return JSON.parse(JSON.stringify(this._schema));
}
public get(path) {
return cloneDeep(getKeyOfObjectByPath(this._instance, path.split(".")));
}
public default(path) {
path = (path.split(".").join("._juvyProperties.") + ".default").split(".");
return cloneDeep(getKeyOfObjectByPath(this._schema._juvyProperties, path));
}
public reset(name) {
this.set(name, this.default(name));
}
public has(path) {
return Object.keys(this.getProperties()).includes(path);
}
public set(name, value) {
value = Juvy.coerce(name, value, this._schema);
const parent = name.split(".");
const child = parent.pop();
if (parent !== "__proto__" && parent !== "constructor" && parent !== "prototype") {
getOrCreateKeyOfObjectByPath(this._instance, parent)[child] = value;
}
return this;
}
public load(conf) {
this.overlay(conf, this._instance, this._schema);
// Environment and arguments always overrides config files
Juvy.importEnvironment(this);
Juvy.importArguments(this);
return this;
}
// ???
public overlay(from, to, schema) {
for (const key of Object.keys(from)) {
// Leaf
if (Array.isArray(from[key]) || !(typeof from[key] === "object" && from[key] !== null) || !schema || schema.format === "object") {
to[key] = Juvy.coerce(key, from[key], schema);
} else {
if (!(typeof to[key] === "object" && to[key] !== null)) {
to[key] = {};
}
this.overlay(from[key], to[key], schema._juvyProperties[key]);
}
}
}
// ???
public validate(options = this.options) {
/* Example usages of 'flatten' are shown below:
flatten(this._instance);
flatten(this._schema._juvyProperties, true);
*/
function flatten(obj, useProperties) {
let key;
const entries = [];
for (const stack = Object.keys(obj); stack.length > 0;) {
key = stack.shift();
let value = getKeyOfObjectByPath(obj, key.split("."));
if (typeof value === "object" && !Array.isArray(value) && value !== null && value !== undefined) { // added && !== undefined
if (useProperties) {
if ("_juvyProperties" in value) {
value = value._juvyProperties;
key += "._juvyProperties";
} else {
entries.push([key, value]);
continue;
}
}
const subkeys = Object.keys(value);
// Don't filter out empty objects
if (subkeys.length > 0) {
for (const subkey of subkeys) {
stack.push(key + "." + subkey);
}
continue;
}
}
entries.push([key, value]);
}
const flattened = {};
for (let [key, value] of entries) {
if (useProperties) {
key = key.replace(/\._juvyProperties/gu, "u");
}
flattened[key] = value;
}
return flattened;
}
const flatInstance = flatten(this._instance);
const flatSchema = flatten(this._schema._juvyProperties, true);
for (const name of Object.keys(flatSchema)) {
const schemaItem = flatSchema[name];
let instanceItem = flatInstance[name];
if (!(name in flatInstance)) {
try {
if (typeof schemaItem.default === "object" && !Array.isArray(schemaItem.default)) {
// Missing item may be an object with undeclared children, so try to
// pull it unflattened from the config instance for type validation
instanceItem = getKeyOfObjectByPath(this._instance, name.split("."));
} else {
throw new Error("missing");
}
} catch (e) {
const err = new Error("configuration param '" + name + "' missing from config, did you override its parent?");
//errors.missing.push(err)
return;
}
}
delete flatInstance[name];
// Ignore nested keys of schema `object` properties
if (schemaItem.format === "object" || typeof schemaItem.default === "object") {
const keys = Object.keys(flatInstance).filter(function(key) {
return key.lastIndexOf(name + ".", 0) === 0;
});
for (const key of keys) {
delete flatInstance[key];
}
}
if (typeof schemaItem.default !== undefined && instanceItem !== schemaItem.default) {
try {
schemaItem._format(instanceItem);
} catch (err) {
//errors.invalid_type.push(err)
}
}
}
if (options["strict"]) {
for (const name of Object.keys(flatInstance)) {
const err = new Error("configuration param '" + name + "' not declared in the schema");
//errors.undeclared.push(err)
}
}
return this;
}
}
for (const method of [
"addFormat",
"addFormats",
"addParser",
"getArgs",
"getEnv",
"getSchemaString",
"loadFile",
"toString"
]) {
Juvy[method] = function() {
throw new Error("Removed");
};
}
export function juvy(schema) {
return new Juvy(schema);
}
|
3cafd9278b1350545b7bd9823d04145c9bc2422d | 2,867 | ts | TypeScript | src/run-jobs.ts | suchipi/parallel-park | 725ff3c766cf03be55b2b8d9efad54d9f5f8d860 | [
"MIT"
] | 9 | 2022-02-23T04:39:36.000Z | 2022-03-01T12:14:15.000Z | src/run-jobs.ts | suchipi/parallel-park | 725ff3c766cf03be55b2b8d9efad54d9f5f8d860 | [
"MIT"
] | null | null | null | src/run-jobs.ts | suchipi/parallel-park | 725ff3c766cf03be55b2b8d9efad54d9f5f8d860 | [
"MIT"
] | null | null | null | function isThenable<T>(value: unknown): value is Promise<T> {
return (
typeof value === "object" &&
value != null &&
// @ts-ignore accessing .then
typeof value.then === "function"
);
}
const NOTHING = Symbol("NOTHING");
export async function runJobs<T, U>(
inputs: Iterable<T | Promise<T>> | AsyncIterable<T | Promise<T>>,
mapper: (input: T, index: number, length: number) => Promise<U>,
{
/**
* How many jobs are allowed to run at once.
*/
concurrency = 8,
}: {
/**
* How many jobs are allowed to run at once.
*/
concurrency?: number;
} = {}
): Promise<Array<U>> {
if (concurrency < 1) {
throw new Error(
"Concurrency can't be less than one; that doesn't make any sense."
);
}
const inputsArray: Array<T> = [];
const inputIteratorFactory =
inputs[Symbol.asyncIterator || NOTHING] || inputs[Symbol.iterator];
const inputIterator = inputIteratorFactory.call(inputs);
const maybeLength = Array.isArray(inputs) ? inputs.length : null;
let iteratorDone = false;
async function readInput(): Promise<boolean> {
let nextResult = inputIterator.next();
if (isThenable(nextResult)) {
nextResult = await nextResult;
}
if (nextResult.done) {
iteratorDone = true;
return false;
} else {
let value = nextResult.value;
if (isThenable<T>(value)) {
value = await value;
}
inputsArray.push(value);
return true;
}
}
let unstartedIndex = 0;
const results = new Array(maybeLength || 0);
const runningPromises = new Set();
let error: Error | null = null;
async function takeInput() {
const read = await readInput();
if (!read) return;
const inputIndex = unstartedIndex;
unstartedIndex++;
const input = inputsArray[inputIndex];
const promise = mapper(input, inputIndex, maybeLength || Infinity);
if (!isThenable(promise)) {
throw new Error(
"Mapper function passed into runJobs didn't return a Promise. The mapper function should always return a Promise. The easiest way to ensure this is the case is to make your mapper function an async function."
);
}
const promiseWithMore = promise.then(
(result) => {
results[inputIndex] = result;
runningPromises.delete(promiseWithMore);
},
(err) => {
runningPromises.delete(promiseWithMore);
error = err;
}
);
runningPromises.add(promiseWithMore);
}
async function proceed() {
while (!iteratorDone && runningPromises.size < concurrency) {
await takeInput();
}
}
await proceed();
while (runningPromises.size > 0 && !error) {
await Promise.race(runningPromises.values());
if (error) {
throw error;
}
await proceed();
}
if (error) {
throw error;
}
return results;
}
| 24.930435 | 216 | 0.622253 | 91 | 7 | 0 | 6 | 17 | 0 | 4 | 0 | 5 | 0 | 2 | 17.428571 | 736 | 0.017663 | 0.023098 | 0 | 0 | 0.002717 | 0 | 0.166667 | 0.287286 | /* Example usages of 'isThenable' are shown below:
isThenable(nextResult);
isThenable<T>(value);
!isThenable(promise);
*/
function isThenable<T>(value): value is Promise<T> {
return (
typeof value === "object" &&
value != null &&
// @ts-ignore accessing .then
typeof value.then === "function"
);
}
const NOTHING = Symbol("NOTHING");
export async function runJobs<T, U>(
inputs,
mapper,
{
/**
* How many jobs are allowed to run at once.
*/
concurrency = 8,
} = {}
) {
if (concurrency < 1) {
throw new Error(
"Concurrency can't be less than one; that doesn't make any sense."
);
}
const inputsArray = [];
const inputIteratorFactory =
inputs[Symbol.asyncIterator || NOTHING] || inputs[Symbol.iterator];
const inputIterator = inputIteratorFactory.call(inputs);
const maybeLength = Array.isArray(inputs) ? inputs.length : null;
let iteratorDone = false;
/* Example usages of 'readInput' are shown below:
readInput();
*/
async function readInput() {
let nextResult = inputIterator.next();
if (isThenable(nextResult)) {
nextResult = await nextResult;
}
if (nextResult.done) {
iteratorDone = true;
return false;
} else {
let value = nextResult.value;
if (isThenable<T>(value)) {
value = await value;
}
inputsArray.push(value);
return true;
}
}
let unstartedIndex = 0;
const results = new Array(maybeLength || 0);
const runningPromises = new Set();
let error = null;
/* Example usages of 'takeInput' are shown below:
takeInput();
*/
async function takeInput() {
const read = await readInput();
if (!read) return;
const inputIndex = unstartedIndex;
unstartedIndex++;
const input = inputsArray[inputIndex];
const promise = mapper(input, inputIndex, maybeLength || Infinity);
if (!isThenable(promise)) {
throw new Error(
"Mapper function passed into runJobs didn't return a Promise. The mapper function should always return a Promise. The easiest way to ensure this is the case is to make your mapper function an async function."
);
}
const promiseWithMore = promise.then(
(result) => {
results[inputIndex] = result;
runningPromises.delete(promiseWithMore);
},
(err) => {
runningPromises.delete(promiseWithMore);
error = err;
}
);
runningPromises.add(promiseWithMore);
}
/* Example usages of 'proceed' are shown below:
proceed();
*/
async function proceed() {
while (!iteratorDone && runningPromises.size < concurrency) {
await takeInput();
}
}
await proceed();
while (runningPromises.size > 0 && !error) {
await Promise.race(runningPromises.values());
if (error) {
throw error;
}
await proceed();
}
if (error) {
throw error;
}
return results;
}
|
1a89024240a2c230d91949028e12a7e08a0ee704 | 2,709 | ts | TypeScript | go/src/infra/appengine/statsui/frontend/src/utils/dateUtils.ts | xswz8015/infra | f956b78ce4c39cc76acdda47601b86794ae0c1ba | [
"BSD-3-Clause"
] | null | null | null | go/src/infra/appengine/statsui/frontend/src/utils/dateUtils.ts | xswz8015/infra | f956b78ce4c39cc76acdda47601b86794ae0c1ba | [
"BSD-3-Clause"
] | 7 | 2022-02-15T01:11:37.000Z | 2022-03-02T12:46:13.000Z | go/src/infra/appengine/statsui/frontend/src/utils/dateUtils.ts | NDevTK/chromium-infra | d38e088e158d81f7f2065a38aa1ea1894f735ec4 | [
"BSD-3-Clause"
] | null | null | null | // Copyright 2021 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
// Enum specifying different time periods.
export enum Period {
Undefined = '',
Day = 'day',
Week = 'week',
Month = 'month',
}
const dayMs = 1000 * 60 * 60 * 24;
// toTzDate returns a date object for a YYYY-MM-DD string.
// Because Javascript interprets YYYY-MM-DD as UTC, simply using the date object
// may give the wrong date once UTC is converted to local TZ.
export function toTzDate(date: string): Date {
const utcDate = new Date(date);
return new Date(
utcDate.getUTCFullYear(),
utcDate.getUTCMonth(),
utcDate.getUTCDate()
);
}
// calculateValidDates generates an array of date strings given a starting date,
// a period, and how many periods before and after. If the date given does not
// fall on a period boundary, it will use the earliest period boundary before
// the given date as the start point.
export function calculateValidDates(
date: Date | string,
period: Period,
periodsBefore = 0,
periodsAfter = 0,
includeDate = true
): string[] {
const now = new Date().getTime();
let periodDate = new Date(date);
if (date instanceof Date) {
// Change date to UTC so there aren't TZ issues on the date math
periodDate = new Date(date.getFullYear(), date.getMonth(), date.getDate());
}
switch (period) {
case Period.Week: {
let daysAway = periodDate.getUTCDay() - 1; // First day is Monday
if (daysAway < 0) {
daysAway = 6;
}
periodDate.setTime(periodDate.getTime() - daysAway * dayMs);
break;
}
case Period.Month: {
periodDate.setUTCDate(1);
break;
}
}
const dates: string[] = [];
for (let i = periodsBefore; i > 0; i--) {
const date = addPeriodsToDate(periodDate, period, -i);
if (date.getTime() < now) {
dates.push(date.toISOString().slice(0, 10));
}
}
if (includeDate) {
dates.push(periodDate.toISOString().slice(0, 10));
}
for (let i = 1; i <= periodsAfter; i++) {
const date = addPeriodsToDate(periodDate, period, i);
if (date.getTime() < now) {
dates.push(date.toISOString().slice(0, 10));
}
}
return dates;
}
function addPeriodsToDate(date: Date, period: Period, num: number): Date {
const ret = new Date();
switch (period) {
case Period.Day:
ret.setTime(date.getTime() + num * dayMs);
break;
case Period.Week:
ret.setTime(date.getTime() + num * dayMs * 7);
break;
case Period.Month:
ret.setTime(date.getTime());
ret.setUTCMonth(date.getUTCMonth() + num);
break;
}
return ret;
}
| 27.927835 | 80 | 0.645995 | 75 | 3 | 0 | 9 | 11 | 0 | 1 | 0 | 5 | 0 | 1 | 18.666667 | 784 | 0.015306 | 0.014031 | 0 | 0 | 0.001276 | 0 | 0.217391 | 0.251527 | // Copyright 2021 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
// Enum specifying different time periods.
export enum Period {
Undefined = '',
Day = 'day',
Week = 'week',
Month = 'month',
}
const dayMs = 1000 * 60 * 60 * 24;
// toTzDate returns a date object for a YYYY-MM-DD string.
// Because Javascript interprets YYYY-MM-DD as UTC, simply using the date object
// may give the wrong date once UTC is converted to local TZ.
export function toTzDate(date) {
const utcDate = new Date(date);
return new Date(
utcDate.getUTCFullYear(),
utcDate.getUTCMonth(),
utcDate.getUTCDate()
);
}
// calculateValidDates generates an array of date strings given a starting date,
// a period, and how many periods before and after. If the date given does not
// fall on a period boundary, it will use the earliest period boundary before
// the given date as the start point.
export function calculateValidDates(
date,
period,
periodsBefore = 0,
periodsAfter = 0,
includeDate = true
) {
const now = new Date().getTime();
let periodDate = new Date(date);
if (date instanceof Date) {
// Change date to UTC so there aren't TZ issues on the date math
periodDate = new Date(date.getFullYear(), date.getMonth(), date.getDate());
}
switch (period) {
case Period.Week: {
let daysAway = periodDate.getUTCDay() - 1; // First day is Monday
if (daysAway < 0) {
daysAway = 6;
}
periodDate.setTime(periodDate.getTime() - daysAway * dayMs);
break;
}
case Period.Month: {
periodDate.setUTCDate(1);
break;
}
}
const dates = [];
for (let i = periodsBefore; i > 0; i--) {
const date = addPeriodsToDate(periodDate, period, -i);
if (date.getTime() < now) {
dates.push(date.toISOString().slice(0, 10));
}
}
if (includeDate) {
dates.push(periodDate.toISOString().slice(0, 10));
}
for (let i = 1; i <= periodsAfter; i++) {
const date = addPeriodsToDate(periodDate, period, i);
if (date.getTime() < now) {
dates.push(date.toISOString().slice(0, 10));
}
}
return dates;
}
/* Example usages of 'addPeriodsToDate' are shown below:
addPeriodsToDate(periodDate, period, -i);
addPeriodsToDate(periodDate, period, i);
*/
function addPeriodsToDate(date, period, num) {
const ret = new Date();
switch (period) {
case Period.Day:
ret.setTime(date.getTime() + num * dayMs);
break;
case Period.Week:
ret.setTime(date.getTime() + num * dayMs * 7);
break;
case Period.Month:
ret.setTime(date.getTime());
ret.setUTCMonth(date.getUTCMonth() + num);
break;
}
return ret;
}
|
1abc4a7114b2750e03c4f2ea19f3c1c24f35a118 | 2,630 | ts | TypeScript | day-22.ts | dubzzz/advent-of-pbt-2021 | 7b324588cc582bea60155cc922778f39d503a818 | [
"MIT"
] | 2 | 2022-03-14T00:03:38.000Z | 2022-03-14T11:51:27.000Z | day-22.ts | dubzzz/advent-of-pbt-2021 | 7b324588cc582bea60155cc922778f39d503a818 | [
"MIT"
] | null | null | null | day-22.ts | dubzzz/advent-of-pbt-2021 | 7b324588cc582bea60155cc922778f39d503a818 | [
"MIT"
] | null | null | null | /**
* Santa' elves often want to know in advance what will be the plan
* of Santa for the upcoming Christmas. As a consequence, they try
* to spy on Santa by looking on top of a wall separating them from
* him when Santa starts receiving letters.
*
* They usually try to mount on each others shoulders to have the exact
* same height as the whole. But even if they tried many years in a raw
* they have only succeeding with 1, 2 or 3 eleves.
*
* Could you help them in their mission?
* In other words: could you return one, two or three elves (by index)
* such as:
* height(elves[i]) = height(wall)
* OR
* height(elves[i]) + height(elves[j]) = height(wall)
* OR
* height(elves[i]) + height(elves[j]) + height(elves[k]) = height(wall)
*
* @param elvesHeight - Strictly positive integers representing
* the heights of our elves
* @param wallHeight - The height of the wall
*
* @returns
* The one, two or three selected elves if there is a solution,
* undefined otherwise.
*/
export function spyOnSanta(
elvesHeight: number[],
wallHeight: number
): number[] | undefined {
return (
spyOnSanta1(elvesHeight, wallHeight) ??
spyOnSanta2(elvesHeight, wallHeight) ??
spyOnSanta3(elvesHeight, wallHeight)
);
}
function spyOnSanta1(
elvesHeight: number[],
wallHeight: number
): number[] | undefined {
for (let index = 0; index !== elvesHeight.length; ++index) {
if (elvesHeight[index] === wallHeight) {
return [index];
}
}
return undefined;
}
function spyOnSanta2(
elvesHeight: number[],
wallHeight: number,
startOffset: number = 0
): number[] | undefined {
const knownHeightAndIndex = new Map<number, number>();
for (let index = startOffset; index !== elvesHeight.length; ++index) {
const current = elvesHeight[index];
const complementaryElfIndex = knownHeightAndIndex.get(wallHeight - current);
if (complementaryElfIndex !== undefined) {
return [complementaryElfIndex, index];
}
knownHeightAndIndex.set(current, index);
}
return undefined;
}
function spyOnSanta3(
elvesHeight: number[],
wallHeight: number
): number[] | undefined {
for (let index = 0; index !== elvesHeight.length; ++index) {
const current = elvesHeight[index];
const decreasedWallHeight = wallHeight - current;
if (decreasedWallHeight >= 2) {
// at least two elves, so wall need to be at least 2 units above
const possibility = spyOnSanta2(elvesHeight, decreasedWallHeight, index);
if (possibility !== undefined) {
return [index, ...possibility];
}
}
}
return undefined;
}
| 30.941176 | 80 | 0.678327 | 53 | 4 | 0 | 9 | 9 | 0 | 3 | 0 | 15 | 0 | 0 | 8 | 748 | 0.01738 | 0.012032 | 0 | 0 | 0 | 0 | 0.681818 | 0.249908 | /**
* Santa' elves often want to know in advance what will be the plan
* of Santa for the upcoming Christmas. As a consequence, they try
* to spy on Santa by looking on top of a wall separating them from
* him when Santa starts receiving letters.
*
* They usually try to mount on each others shoulders to have the exact
* same height as the whole. But even if they tried many years in a raw
* they have only succeeding with 1, 2 or 3 eleves.
*
* Could you help them in their mission?
* In other words: could you return one, two or three elves (by index)
* such as:
* height(elves[i]) = height(wall)
* OR
* height(elves[i]) + height(elves[j]) = height(wall)
* OR
* height(elves[i]) + height(elves[j]) + height(elves[k]) = height(wall)
*
* @param elvesHeight - Strictly positive integers representing
* the heights of our elves
* @param wallHeight - The height of the wall
*
* @returns
* The one, two or three selected elves if there is a solution,
* undefined otherwise.
*/
export function spyOnSanta(
elvesHeight,
wallHeight
) {
return (
spyOnSanta1(elvesHeight, wallHeight) ??
spyOnSanta2(elvesHeight, wallHeight) ??
spyOnSanta3(elvesHeight, wallHeight)
);
}
/* Example usages of 'spyOnSanta1' are shown below:
spyOnSanta1(elvesHeight, wallHeight) ??
spyOnSanta2(elvesHeight, wallHeight) ??
spyOnSanta3(elvesHeight, wallHeight);
*/
function spyOnSanta1(
elvesHeight,
wallHeight
) {
for (let index = 0; index !== elvesHeight.length; ++index) {
if (elvesHeight[index] === wallHeight) {
return [index];
}
}
return undefined;
}
/* Example usages of 'spyOnSanta2' are shown below:
spyOnSanta1(elvesHeight, wallHeight) ??
spyOnSanta2(elvesHeight, wallHeight) ??
spyOnSanta3(elvesHeight, wallHeight);
spyOnSanta2(elvesHeight, decreasedWallHeight, index);
*/
function spyOnSanta2(
elvesHeight,
wallHeight,
startOffset = 0
) {
const knownHeightAndIndex = new Map<number, number>();
for (let index = startOffset; index !== elvesHeight.length; ++index) {
const current = elvesHeight[index];
const complementaryElfIndex = knownHeightAndIndex.get(wallHeight - current);
if (complementaryElfIndex !== undefined) {
return [complementaryElfIndex, index];
}
knownHeightAndIndex.set(current, index);
}
return undefined;
}
/* Example usages of 'spyOnSanta3' are shown below:
spyOnSanta1(elvesHeight, wallHeight) ??
spyOnSanta2(elvesHeight, wallHeight) ??
spyOnSanta3(elvesHeight, wallHeight);
*/
function spyOnSanta3(
elvesHeight,
wallHeight
) {
for (let index = 0; index !== elvesHeight.length; ++index) {
const current = elvesHeight[index];
const decreasedWallHeight = wallHeight - current;
if (decreasedWallHeight >= 2) {
// at least two elves, so wall need to be at least 2 units above
const possibility = spyOnSanta2(elvesHeight, decreasedWallHeight, index);
if (possibility !== undefined) {
return [index, ...possibility];
}
}
}
return undefined;
}
|
1af1c1b0df837d195e0953f43f2ce143d93feef4 | 2,476 | ts | TypeScript | src/util/matrices.ts | aleksei-berezkin/code-art | b807425370e55486d177e660bb5671c892d9b3be | [
"MIT"
] | null | null | null | src/util/matrices.ts | aleksei-berezkin/code-art | b807425370e55486d177e660bb5671c892d9b3be | [
"MIT"
] | 1 | 2022-02-21T16:58:13.000Z | 2022-03-01T16:05:30.000Z | src/util/matrices.ts | aleksei-berezkin/code-art | b807425370e55486d177e660bb5671c892d9b3be | [
"MIT"
] | null | null | null | /**
* All matrices are in "math" notation where row is row, column is column, or, in other words,
* matrix' slice is a row. When passed as uniforms matrices get transposed.
*/
export type Mat4 = [
number, number, number, number,
number, number, number, number,
number, number, number, number,
number, number, number, number,
];
const size = 4;
export function mul(...A: Mat4[]): Mat4 {
return A.reduce(mul2);
}
function mul2(A: Mat4, B: Mat4): Mat4 {
const C = [];
for (let r = 0; r < size; r++) {
for (let c = 0; c < size; c++) {
let s = 0;
for (let i = 0; i < size; i++) {
s += A[ix(r, i)] * B[ix(i, c)];
}
C.push(s);
}
}
return asMat4(C);
}
/**
* Unlike math, vector here is 'horizontal'
*/
export type Vec4 = [
number, number, number, number
];
export function mulVec(A: Mat4, v: Vec4): Vec4 {
return [
A[ix(0, 0)] * v[0] + A[ix(0, 1)] * v[1] + A[ix(0, 2)] * v[2] + A[ix(0, 3)] * v[3],
A[ix(1, 0)] * v[0] + A[ix(1, 1)] * v[1] + A[ix(1, 2)] * v[2] + A[ix(1, 3)] * v[3],
A[ix(2, 0)] * v[0] + A[ix(2, 1)] * v[1] + A[ix(2, 2)] * v[2] + A[ix(2, 3)] * v[3],
A[ix(3, 0)] * v[0] + A[ix(3, 1)] * v[1] + A[ix(3, 2)] * v[2] + A[ix(3, 3)] * v[3],
] as Vec4;
}
function ix(r: number, c: number) {
return r * size + c;
}
const sizeSq = size ** 2;
export function asMat4(A: number[]): Mat4 {
if (A.length === sizeSq) {
return A as Mat4;
}
throw new Error(`Bad size=${A.length}`)
}
export function getRotateZMat(angleRad: number) {
return asMat4([
Math.cos(angleRad), Math.sin(angleRad), 0, 0,
-Math.sin(angleRad), Math.cos(angleRad), 0, 0,
0, 0, 1, 0,
0, 0, 0, 1,
]);
}
export function getRotateXMat(angleRad: number) {
return asMat4([
1, 0, 0, 0,
0, Math.cos(angleRad), Math.sin(angleRad), 0,
0, -Math.sin(angleRad), Math.cos(angleRad), 0,
0, 0, 0, 1,
]);
}
export function getRotateYMat(angleRad: number) {
return asMat4([
Math.cos(angleRad), 0, Math.sin(angleRad), 0,
0, 1, 0, 0,
-Math.sin(angleRad), 0, Math.cos(angleRad), 0,
0, 0, 0, 1,
]);
}
// noinspection JSUnusedGlobalSymbols
export function getTranslateMat(x: number, y: number, z: number) {
return asMat4([
1, 0, 0, x,
0, 1, 0, y,
0, 0, 1, z,
0, 0, 0, 1,
]);
}
| 25.265306 | 94 | 0.50525 | 76 | 9 | 0 | 14 | 7 | 0 | 2 | 0 | 29 | 2 | 2 | 5.222222 | 998 | 0.023046 | 0.007014 | 0 | 0.002004 | 0.002004 | 0 | 0.966667 | 0.249072 | /**
* All matrices are in "math" notation where row is row, column is column, or, in other words,
* matrix' slice is a row. When passed as uniforms matrices get transposed.
*/
export type Mat4 = [
number, number, number, number,
number, number, number, number,
number, number, number, number,
number, number, number, number,
];
const size = 4;
export function mul(...A) {
return A.reduce(mul2);
}
/* Example usages of 'mul2' are shown below:
A.reduce(mul2);
*/
function mul2(A, B) {
const C = [];
for (let r = 0; r < size; r++) {
for (let c = 0; c < size; c++) {
let s = 0;
for (let i = 0; i < size; i++) {
s += A[ix(r, i)] * B[ix(i, c)];
}
C.push(s);
}
}
return asMat4(C);
}
/**
* Unlike math, vector here is 'horizontal'
*/
export type Vec4 = [
number, number, number, number
];
export function mulVec(A, v) {
return [
A[ix(0, 0)] * v[0] + A[ix(0, 1)] * v[1] + A[ix(0, 2)] * v[2] + A[ix(0, 3)] * v[3],
A[ix(1, 0)] * v[0] + A[ix(1, 1)] * v[1] + A[ix(1, 2)] * v[2] + A[ix(1, 3)] * v[3],
A[ix(2, 0)] * v[0] + A[ix(2, 1)] * v[1] + A[ix(2, 2)] * v[2] + A[ix(2, 3)] * v[3],
A[ix(3, 0)] * v[0] + A[ix(3, 1)] * v[1] + A[ix(3, 2)] * v[2] + A[ix(3, 3)] * v[3],
] as Vec4;
}
/* Example usages of 'ix' are shown below:
s += A[ix(r, i)] * B[ix(i, c)];
A[ix(0, 0)] * v[0] + A[ix(0, 1)] * v[1] + A[ix(0, 2)] * v[2] + A[ix(0, 3)] * v[3];
A[ix(1, 0)] * v[0] + A[ix(1, 1)] * v[1] + A[ix(1, 2)] * v[2] + A[ix(1, 3)] * v[3];
A[ix(2, 0)] * v[0] + A[ix(2, 1)] * v[1] + A[ix(2, 2)] * v[2] + A[ix(2, 3)] * v[3];
A[ix(3, 0)] * v[0] + A[ix(3, 1)] * v[1] + A[ix(3, 2)] * v[2] + A[ix(3, 3)] * v[3];
*/
function ix(r, c) {
return r * size + c;
}
const sizeSq = size ** 2;
export /* Example usages of 'asMat4' are shown below:
asMat4(C);
asMat4([
Math.cos(angleRad), Math.sin(angleRad), 0, 0,
-Math.sin(angleRad), Math.cos(angleRad), 0, 0,
0, 0, 1, 0,
0, 0, 0, 1,
]);
asMat4([
1, 0, 0, 0,
0, Math.cos(angleRad), Math.sin(angleRad), 0,
0, -Math.sin(angleRad), Math.cos(angleRad), 0,
0, 0, 0, 1,
]);
asMat4([
Math.cos(angleRad), 0, Math.sin(angleRad), 0,
0, 1, 0, 0,
-Math.sin(angleRad), 0, Math.cos(angleRad), 0,
0, 0, 0, 1,
]);
asMat4([
1, 0, 0, x,
0, 1, 0, y,
0, 0, 1, z,
0, 0, 0, 1,
]);
*/
function asMat4(A) {
if (A.length === sizeSq) {
return A as Mat4;
}
throw new Error(`Bad size=${A.length}`)
}
export function getRotateZMat(angleRad) {
return asMat4([
Math.cos(angleRad), Math.sin(angleRad), 0, 0,
-Math.sin(angleRad), Math.cos(angleRad), 0, 0,
0, 0, 1, 0,
0, 0, 0, 1,
]);
}
export function getRotateXMat(angleRad) {
return asMat4([
1, 0, 0, 0,
0, Math.cos(angleRad), Math.sin(angleRad), 0,
0, -Math.sin(angleRad), Math.cos(angleRad), 0,
0, 0, 0, 1,
]);
}
export function getRotateYMat(angleRad) {
return asMat4([
Math.cos(angleRad), 0, Math.sin(angleRad), 0,
0, 1, 0, 0,
-Math.sin(angleRad), 0, Math.cos(angleRad), 0,
0, 0, 0, 1,
]);
}
// noinspection JSUnusedGlobalSymbols
export function getTranslateMat(x, y, z) {
return asMat4([
1, 0, 0, x,
0, 1, 0, y,
0, 0, 1, z,
0, 0, 0, 1,
]);
}
|
ce1ff711fe03d40cc826cfcdbab9b916493eda56 | 1,396 | ts | TypeScript | frontend/src/pages/traceroute/traceroute.reducer.ts | krystal/krystal-network-tools | 05e2a6c5b8807672e9483d847f64ba6d4dd508be | [
"MIT"
] | 1 | 2022-03-10T09:02:06.000Z | 2022-03-10T09:02:06.000Z | frontend/src/pages/traceroute/traceroute.reducer.ts | krystal/krystal-network-tools | 05e2a6c5b8807672e9483d847f64ba6d4dd508be | [
"MIT"
] | 13 | 2022-02-23T12:18:46.000Z | 2022-03-11T16:20:28.000Z | frontend/src/pages/traceroute/traceroute.reducer.ts | krystal/krystal-network-tools | 05e2a6c5b8807672e9483d847f64ba6d4dd508be | [
"MIT"
] | null | null | null | export type TracerouteResponse = {
destination_ip: string;
traceroute: {
pings: number[];
rdns: string;
ip_address: string;
}[];
};
type TracerouteState =
| { status: "initial" }
| {
status: "started";
host: string;
location: string;
responses: TracerouteResponse[];
}
| {
status: "stopped";
host: string;
location: string;
responses: TracerouteResponse[];
}
| { status: "error"; error: Error; host?: string };
type TracerouteAction =
| { type: "start"; host: string; location: string }
| { type: "stop" }
| { type: "response"; response: TracerouteResponse }
| { type: "error"; error: Error };
const tracerouteReducer = (
state: TracerouteState,
action: TracerouteAction
): TracerouteState => {
switch (action.type) {
case "start":
return {
status: "started",
host: action.host,
location: action.location,
responses: [],
};
case "stop":
return state.status === "started"
? { ...state, status: "stopped" }
: state;
case "response":
return state.status === "started"
? { ...state, responses: [...state.responses, action.response] }
: state;
case "error":
return { ...state, status: "error", error: action.error };
default:
return state;
}
};
export default tracerouteReducer;
| 23.266667 | 72 | 0.576648 | 55 | 1 | 0 | 2 | 1 | 2 | 0 | 0 | 11 | 3 | 0 | 21 | 376 | 0.007979 | 0.00266 | 0.005319 | 0.007979 | 0 | 0 | 1.833333 | 0.207966 | export type TracerouteResponse = {
destination_ip;
traceroute;
};
type TracerouteState =
| { status }
| {
status;
host;
location;
responses;
}
| {
status;
host;
location;
responses;
}
| { status; error; host? };
type TracerouteAction =
| { type; host; location }
| { type }
| { type; response }
| { type; error };
/* Example usages of 'tracerouteReducer' are shown below:
;
*/
const tracerouteReducer = (
state,
action
) => {
switch (action.type) {
case "start":
return {
status: "started",
host: action.host,
location: action.location,
responses: [],
};
case "stop":
return state.status === "started"
? { ...state, status: "stopped" }
: state;
case "response":
return state.status === "started"
? { ...state, responses: [...state.responses, action.response] }
: state;
case "error":
return { ...state, status: "error", error: action.error };
default:
return state;
}
};
export default tracerouteReducer;
|
ce4e53dbbd62c1e9be1fd810230501c5a1e4131f | 2,255 | ts | TypeScript | problemset/additive-number/index.ts | OUDUIDUI/leet-code | 50e61ce16d1c419ccefc075ae9ead721cdd1cdbb | [
"MIT"
] | 6 | 2022-01-17T03:19:56.000Z | 2022-01-17T05:45:39.000Z | problemset/additive-number/index.ts | OUDUIDUI/leet-code | 50e61ce16d1c419ccefc075ae9ead721cdd1cdbb | [
"MIT"
] | null | null | null | problemset/additive-number/index.ts | OUDUIDUI/leet-code | 50e61ce16d1c419ccefc075ae9ead721cdd1cdbb | [
"MIT"
] | null | null | null | /**
* 模拟
* @desc 时间复杂度 O(N³) 空间复杂度 O(N)
* @param num
* @returns
*/
export function isAdditiveNumber(num: string): boolean {
const len = num.length
// 遍历定位第二个数值的起点位置
for (let secondStart = 1; secondStart < len - 1; secondStart++) {
// 如果开头为0的话,secondStart只能为1,否则跳出循环
if (num[0] === '0' && secondStart !== 1) break
// 遍历定位第二个数值的结束位置
for (let secondEnd = secondStart; secondEnd < len - 1; secondEnd++) {
// 如果开头为0的话,secondStart只能为1,否则跳出循环
if (num[secondStart] === '0' && secondStart !== secondEnd)
break
// 开始验证
if (valid(secondStart, secondEnd, num)) return true
}
}
return false
/**
* 验证
* @param secondStart
* @param secondEnd
* @param num
* @returns
*/
function valid(secondStart: number, secondEnd: number, num: string): boolean {
const len = num.length
// 初始第一个数值的定位
let firstStart = 0
let firstEnd = secondStart - 1
while (secondEnd <= len - 1) {
// 生成第三个数值
const third = stringAdd(num, firstStart, firstEnd, secondStart, secondEnd)
// 更新第三个数值的定位
const thirdStart = secondEnd + 1
const thirdEnd = secondEnd + third.length
// 如果第三个数值超过界限或不在num中指定位置,则跳出循环
if (thirdEnd >= len || num.slice(thirdStart, thirdEnd + 1) !== third)
break
// 如果已经到结尾,则证明验证成功
if (thirdEnd === len - 1)
return true
// 往后顺延
firstStart = secondStart
firstEnd = secondEnd
secondStart = thirdStart
secondEnd = thirdEnd
}
return false
}
/**
* 生成 first + second 的值
* @param s
* @param firstStart
* @param firstEnd
* @param secondStart
* @param secondEnd
* @returns
*/
function stringAdd(
s: string,
firstStart: number,
firstEnd: number,
secondStart: number,
secondEnd: number,
): string {
const third: number[] = []
let carry = 0
let cur = 0
while (firstEnd >= firstStart || secondEnd >= secondStart || carry !== 0) {
cur = carry
if (firstEnd >= firstStart)
cur += Number(s[firstEnd--])
if (secondEnd >= secondStart)
cur += Number(s[secondEnd--])
carry = (cur / 10) >> 0
cur %= 10
third.unshift(cur)
}
return third.join('')
}
}
| 23.489583 | 80 | 0.585809 | 53 | 3 | 0 | 9 | 12 | 0 | 2 | 0 | 13 | 0 | 0 | 27.333333 | 705 | 0.017021 | 0.017021 | 0 | 0 | 0 | 0 | 0.541667 | 0.265389 | /**
* 模拟
* @desc 时间复杂度 O(N³) 空间复杂度 O(N)
* @param num
* @returns
*/
export function isAdditiveNumber(num) {
const len = num.length
// 遍历定位第二个数值的起点位置
for (let secondStart = 1; secondStart < len - 1; secondStart++) {
// 如果开头为0的话,secondStart只能为1,否则跳出循环
if (num[0] === '0' && secondStart !== 1) break
// 遍历定位第二个数值的结束位置
for (let secondEnd = secondStart; secondEnd < len - 1; secondEnd++) {
// 如果开头为0的话,secondStart只能为1,否则跳出循环
if (num[secondStart] === '0' && secondStart !== secondEnd)
break
// 开始验证
if (valid(secondStart, secondEnd, num)) return true
}
}
return false
/**
* 验证
* @param secondStart
* @param secondEnd
* @param num
* @returns
*/
/* Example usages of 'valid' are shown below:
valid(secondStart, secondEnd, num);
*/
function valid(secondStart, secondEnd, num) {
const len = num.length
// 初始第一个数值的定位
let firstStart = 0
let firstEnd = secondStart - 1
while (secondEnd <= len - 1) {
// 生成第三个数值
const third = stringAdd(num, firstStart, firstEnd, secondStart, secondEnd)
// 更新第三个数值的定位
const thirdStart = secondEnd + 1
const thirdEnd = secondEnd + third.length
// 如果第三个数值超过界限或不在num中指定位置,则跳出循环
if (thirdEnd >= len || num.slice(thirdStart, thirdEnd + 1) !== third)
break
// 如果已经到结尾,则证明验证成功
if (thirdEnd === len - 1)
return true
// 往后顺延
firstStart = secondStart
firstEnd = secondEnd
secondStart = thirdStart
secondEnd = thirdEnd
}
return false
}
/**
* 生成 first + second 的值
* @param s
* @param firstStart
* @param firstEnd
* @param secondStart
* @param secondEnd
* @returns
*/
/* Example usages of 'stringAdd' are shown below:
stringAdd(num, firstStart, firstEnd, secondStart, secondEnd);
*/
function stringAdd(
s,
firstStart,
firstEnd,
secondStart,
secondEnd,
) {
const third = []
let carry = 0
let cur = 0
while (firstEnd >= firstStart || secondEnd >= secondStart || carry !== 0) {
cur = carry
if (firstEnd >= firstStart)
cur += Number(s[firstEnd--])
if (secondEnd >= secondStart)
cur += Number(s[secondEnd--])
carry = (cur / 10) >> 0
cur %= 10
third.unshift(cur)
}
return third.join('')
}
}
|
cebbd13578bce90cb88a3dd8d6fce10efb9f4075 | 2,354 | ts | TypeScript | src/Hooks/Chat/ChatMessages.ts | callmenikk/JetChat | 6f5ba02f6d112ed11e48f08c1a30a1a40a42cf6d | [
"CC0-1.0"
] | 7 | 2022-02-22T06:58:56.000Z | 2022-03-14T11:40:10.000Z | src/Hooks/Chat/ChatMessages.ts | callmenikk/JetChat | 6f5ba02f6d112ed11e48f08c1a30a1a40a42cf6d | [
"CC0-1.0"
] | null | null | null | src/Hooks/Chat/ChatMessages.ts | callmenikk/JetChat | 6f5ba02f6d112ed11e48f08c1a30a1a40a42cf6d | [
"CC0-1.0"
] | null | null | null | export type State = {
type: "MESSAGE" | "JOIN" | "LEFT" | "OWNER_TRANSFERSHIP";
message: {
sentBy: string; //client_id
username: string; //client_username,
sentAt: string; //Date format,
messageText: string; //client sent data,
client_profile: string; //client profile picture URL
message_id: string
reply?: {
mentioned: string; //replying username
mentioned_user_profile: string; //replying user profile source
mentioned_message: string,
mentioned_user_id: string
};
};
};
type Action = {
type: "MESSAGE" | "JOIN" | "LEFT" | "OWNER_TRANSFERSHIP" | "MAKE_EMPTY_MESSAGE_HISTORY";
payload: {
type: "MESSAGE" | "JOIN" | "LEFT" | "OWNER_TRANSFERSHIP";
message: {
sentBy: string; //client_id
username: string; //client_username,
sentAt: string; //Date format,
messageText: string; //client sent data
client_profile: string; //client profile picture URL
message_id: string
reply?: {
mentioned: string; //replying username
mentioned_user_profile: string; //replying user profile source
mentioned_message: string;
mentioned_user_id: string
};
};
};
};
const message: State[] = [];
export const allMessages = (
state: State[] = message,
action: Action
): State[] => {
switch (action.type) {
case "MESSAGE": {
const { sentBy, username, sentAt, messageText, client_profile, message_id } =
action.payload.message;
const {mentioned, mentioned_user_profile, mentioned_message, mentioned_user_id} = action.payload.message.reply!
return [
...state,
{
type: "MESSAGE",
message: {
message_id: message_id,
sentAt: sentAt,
username: username,
sentBy: sentBy,
messageText: messageText,
client_profile: client_profile,
reply: {
mentioned: mentioned, //replying username
mentioned_user_profile: mentioned_user_profile, //replying user profile source
mentioned_message: mentioned_message,
mentioned_user_id: mentioned_user_id
}
},
},
];
}
case "MAKE_EMPTY_MESSAGE_HISTORY" : {
state = []
return state
}
default:
return state;
}
};
| 28.707317 | 117 | 0.607901 | 76 | 1 | 0 | 2 | 4 | 4 | 0 | 0 | 20 | 2 | 0 | 33 | 582 | 0.005155 | 0.006873 | 0.006873 | 0.003436 | 0 | 0 | 1.818182 | 0.207869 | export type State = {
type;
message;
};
type Action = {
type;
payload;
};
const message = [];
export const allMessages = (
state = message,
action
) => {
switch (action.type) {
case "MESSAGE": {
const { sentBy, username, sentAt, messageText, client_profile, message_id } =
action.payload.message;
const {mentioned, mentioned_user_profile, mentioned_message, mentioned_user_id} = action.payload.message.reply!
return [
...state,
{
type: "MESSAGE",
message: {
message_id: message_id,
sentAt: sentAt,
username: username,
sentBy: sentBy,
messageText: messageText,
client_profile: client_profile,
reply: {
mentioned: mentioned, //replying username
mentioned_user_profile: mentioned_user_profile, //replying user profile source
mentioned_message: mentioned_message,
mentioned_user_id: mentioned_user_id
}
},
},
];
}
case "MAKE_EMPTY_MESSAGE_HISTORY" : {
state = []
return state
}
default:
return state;
}
};
|
41476772cf45b474d30df1bf426a5396a1568478 | 4,047 | ts | TypeScript | problemset/erect-the-fence/index.ts | OUDUIDUI/leet-code | 50e61ce16d1c419ccefc075ae9ead721cdd1cdbb | [
"MIT"
] | 6 | 2022-01-17T03:19:56.000Z | 2022-01-17T05:45:39.000Z | problemset/erect-the-fence/index.ts | OUDUIDUI/leet-code | 50e61ce16d1c419ccefc075ae9ead721cdd1cdbb | [
"MIT"
] | null | null | null | problemset/erect-the-fence/index.ts | OUDUIDUI/leet-code | 50e61ce16d1c419ccefc075ae9ead721cdd1cdbb | [
"MIT"
] | null | null | null | /**
* Jarvis 算法
* @desc 时间复杂度 O(N²) 空间复杂度 O(N)
* @param trees
* @returns
*/
export function outerTrees(trees: number[][]): number[][] {
const len = trees.length
if (len < 4)
return trees
let leftMost = 0
for (let i = 0; i < len; i++) {
if (trees[i][0] < trees[leftMost][0])
leftMost = i
}
const res: number[][] = []
const cross = (p: number[], q: number[], r: number[]) => (q[0] - p[0]) * (r[1] - q[1]) - (q[1] - p[1]) * (r[0] - q[0])
const visit = new Array(len).fill(false)
let p = leftMost
do {
let q = (p + 1) % len
for (let r = 0; r < len; r++) {
// 如果 r 在 pq 右侧,则 q = r
if (cross(trees[p], trees[q], trees[r]) < 0)
q = r
}
// 是否存在点 i,使得 p、q、i 在同一条直线上
for (let i = 0; i < len; i++) {
if (visit[i] || i === p || i === q)
continue
if (cross(trees[p], trees[q], trees[i]) === 0) {
res.push(trees[i])
visit[i] = true
}
}
if (!visit[q]) {
res.push(trees[q])
visit[q] = true
}
p = q
} while (p !== leftMost)
return res
}
/**
* Graham 算法
* @desc 时间复杂度 O(NlogN) 空间复杂度 O(N)
* @param trees
* @returns
*/
export function outerTrees2(trees: number[][]): number[][] {
const len = trees.length
if (len < 4)
return trees
let bottom = 0
// 找到 y 最小的点 bottom
for (let i = 0; i < len; i++) {
if (trees[i][1] < trees[bottom][i])
bottom = i
}
const swap = (trees: number[][], i: number, j: number) => {
[
trees[i][0],
trees[i][1],
trees[j][0],
trees[j][1],
]
= [
trees[j][0],
trees[j][1],
trees[i][0],
trees[i][1],
]
return trees
}
const cross = (p: number[], q: number[], r: number[]) => (q[1] - p[1]) * (r[0] - q[0]) - (q[0] - p[0]) * (r[1] - q[1])
const distance = (p: number[], q: number[]) => (p[0] - q[0]) * (p[0] - q[0]) + (p[1] - q[1]) * (p[1] - q[1])
trees = swap(trees, bottom, 0)
// 以 bottom 原点,按照极坐标的角度大小进行排序
trees.sort((a, b) => {
const diff = cross(trees[0], a, b) - cross(trees[0], b, a)
return diff === 0 ? distance(trees[0], a) - distance(trees[0], b) : diff > 0 ? 1 : -1
})
// 对于凸包最后且在同一条直线的元素按照距离从小到大进行排序
let r = len - 1
while (r > 0 && cross(trees[0], trees[len - 1], trees[r]) === 0)
r--
for (let l = r + 1, h = len - 1; l < h; l++, h--)
trees = swap(trees, l, h)
const stack = [trees[0], trees[1]]
for (let i = 2; i < len; i++) {
let top = stack.pop()!
// 如果当前元素与栈顶的两个元素构成的向量顺时针旋转,则弹出栈顶元素
while (cross(stack[stack.length - 1], top, trees[i]) > 0)
top = stack.pop()!
stack.push(top)
stack.push(trees[i])
}
return stack
}
/**
* Andrew 算法
* @desc 时间复杂度 O(NlogN) 空间复杂度 O(N)
* @param trees
* @returns
*/
export function outerTrees3(trees: number[][]): number[][] {
const len = trees.length
if (len < 4)
return trees
// 按照 x 大小进行排序,如果 x 相同,则按照 y 的大小进行排序
trees.sort((a, b) => {
if (a[0] === b[0])
return a[1] - b[1]
return a[0] - b[0]
})
const hull = []
const used = new Array(len).fill(false)
// hull[0] 需要入栈两次,不进行标记
hull.push(0)
const cross = (p: number[], q: number[], r: number[]) => (q[0] - p[0]) * (r[1] - q[1]) - (q[1] - p[1]) * (r[0] - q[0])
// 求出凸包的下半部分
for (let i = 1; i < len; i++) {
while (hull.length > 1 && cross(trees[hull[hull.length - 2]], trees[hull[hull.length - 1]], trees[i]) < 0) {
used[hull[hull.length - 1]] = false
hull.pop()
}
used[i] = true
hull.push(i)
}
const m = hull.length
// 求出凸包的上半部分
for (let i = len - 2; i >= 0; i--) {
if (!used[i]) {
while (hull.length > m && cross(trees[hull[hull.length - 2]], trees[hull[hull.length - 1]], trees[i]) < 0) {
used[hull[hull.length - 1]] = false
hull.pop()
}
used[i] = true
hull.push(i)
}
}
// hull[0] 同时参与凸包的上半部分检测,需要去掉重复的 hull[0]
hull.pop()
const size = hull.length
const res: number[][] = []
for (let i = 0; i < size; i++)
res[i] = trees[hull[i]]
return res
}
| 22.483333 | 120 | 0.492958 | 120 | 10 | 0 | 21 | 33 | 0 | 3 | 0 | 22 | 0 | 0 | 13.6 | 1,659 | 0.018686 | 0.019892 | 0 | 0 | 0 | 0 | 0.34375 | 0.279111 | /**
* Jarvis 算法
* @desc 时间复杂度 O(N²) 空间复杂度 O(N)
* @param trees
* @returns
*/
export function outerTrees(trees) {
const len = trees.length
if (len < 4)
return trees
let leftMost = 0
for (let i = 0; i < len; i++) {
if (trees[i][0] < trees[leftMost][0])
leftMost = i
}
const res = []
/* Example usages of 'cross' are shown below:
cross(trees[p], trees[q], trees[r]) < 0;
cross(trees[p], trees[q], trees[i]) === 0;
cross(trees[0], a, b) - cross(trees[0], b, a);
r > 0 && cross(trees[0], trees[len - 1], trees[r]) === 0;
cross(stack[stack.length - 1], top, trees[i]) > 0;
hull.length > 1 && cross(trees[hull[hull.length - 2]], trees[hull[hull.length - 1]], trees[i]) < 0;
hull.length > m && cross(trees[hull[hull.length - 2]], trees[hull[hull.length - 1]], trees[i]) < 0;
*/
/* Example usages of 'cross' are shown below:
cross(trees[p], trees[q], trees[r]) < 0;
cross(trees[p], trees[q], trees[i]) === 0;
cross(trees[0], a, b) - cross(trees[0], b, a);
r > 0 && cross(trees[0], trees[len - 1], trees[r]) === 0;
cross(stack[stack.length - 1], top, trees[i]) > 0;
hull.length > 1 && cross(trees[hull[hull.length - 2]], trees[hull[hull.length - 1]], trees[i]) < 0;
hull.length > m && cross(trees[hull[hull.length - 2]], trees[hull[hull.length - 1]], trees[i]) < 0;
*/
const cross = (p, q, r) => (q[0] - p[0]) * (r[1] - q[1]) - (q[1] - p[1]) * (r[0] - q[0])
const visit = new Array(len).fill(false)
let p = leftMost
do {
let q = (p + 1) % len
for (let r = 0; r < len; r++) {
// 如果 r 在 pq 右侧,则 q = r
if (cross(trees[p], trees[q], trees[r]) < 0)
q = r
}
// 是否存在点 i,使得 p、q、i 在同一条直线上
for (let i = 0; i < len; i++) {
if (visit[i] || i === p || i === q)
continue
if (cross(trees[p], trees[q], trees[i]) === 0) {
res.push(trees[i])
visit[i] = true
}
}
if (!visit[q]) {
res.push(trees[q])
visit[q] = true
}
p = q
} while (p !== leftMost)
return res
}
/**
* Graham 算法
* @desc 时间复杂度 O(NlogN) 空间复杂度 O(N)
* @param trees
* @returns
*/
export function outerTrees2(trees) {
const len = trees.length
if (len < 4)
return trees
let bottom = 0
// 找到 y 最小的点 bottom
for (let i = 0; i < len; i++) {
if (trees[i][1] < trees[bottom][i])
bottom = i
}
/* Example usages of 'swap' are shown below:
trees = swap(trees, bottom, 0);
trees = swap(trees, l, h);
*/
const swap = (trees, i, j) => {
[
trees[i][0],
trees[i][1],
trees[j][0],
trees[j][1],
]
= [
trees[j][0],
trees[j][1],
trees[i][0],
trees[i][1],
]
return trees
}
/* Example usages of 'cross' are shown below:
cross(trees[p], trees[q], trees[r]) < 0;
cross(trees[p], trees[q], trees[i]) === 0;
cross(trees[0], a, b) - cross(trees[0], b, a);
r > 0 && cross(trees[0], trees[len - 1], trees[r]) === 0;
cross(stack[stack.length - 1], top, trees[i]) > 0;
hull.length > 1 && cross(trees[hull[hull.length - 2]], trees[hull[hull.length - 1]], trees[i]) < 0;
hull.length > m && cross(trees[hull[hull.length - 2]], trees[hull[hull.length - 1]], trees[i]) < 0;
*/
const cross = (p, q, r) => (q[1] - p[1]) * (r[0] - q[0]) - (q[0] - p[0]) * (r[1] - q[1])
/* Example usages of 'distance' are shown below:
diff === 0 ? distance(trees[0], a) - distance(trees[0], b) : diff > 0 ? 1 : -1;
*/
const distance = (p, q) => (p[0] - q[0]) * (p[0] - q[0]) + (p[1] - q[1]) * (p[1] - q[1])
trees = swap(trees, bottom, 0)
// 以 bottom 原点,按照极坐标的角度大小进行排序
trees.sort((a, b) => {
const diff = cross(trees[0], a, b) - cross(trees[0], b, a)
return diff === 0 ? distance(trees[0], a) - distance(trees[0], b) : diff > 0 ? 1 : -1
})
// 对于凸包最后且在同一条直线的元素按照距离从小到大进行排序
let r = len - 1
while (r > 0 && cross(trees[0], trees[len - 1], trees[r]) === 0)
r--
for (let l = r + 1, h = len - 1; l < h; l++, h--)
trees = swap(trees, l, h)
const stack = [trees[0], trees[1]]
for (let i = 2; i < len; i++) {
let top = stack.pop()!
// 如果当前元素与栈顶的两个元素构成的向量顺时针旋转,则弹出栈顶元素
while (cross(stack[stack.length - 1], top, trees[i]) > 0)
top = stack.pop()!
stack.push(top)
stack.push(trees[i])
}
return stack
}
/**
* Andrew 算法
* @desc 时间复杂度 O(NlogN) 空间复杂度 O(N)
* @param trees
* @returns
*/
export function outerTrees3(trees) {
const len = trees.length
if (len < 4)
return trees
// 按照 x 大小进行排序,如果 x 相同,则按照 y 的大小进行排序
trees.sort((a, b) => {
if (a[0] === b[0])
return a[1] - b[1]
return a[0] - b[0]
})
const hull = []
const used = new Array(len).fill(false)
// hull[0] 需要入栈两次,不进行标记
hull.push(0)
/* Example usages of 'cross' are shown below:
cross(trees[p], trees[q], trees[r]) < 0;
cross(trees[p], trees[q], trees[i]) === 0;
cross(trees[0], a, b) - cross(trees[0], b, a);
r > 0 && cross(trees[0], trees[len - 1], trees[r]) === 0;
cross(stack[stack.length - 1], top, trees[i]) > 0;
hull.length > 1 && cross(trees[hull[hull.length - 2]], trees[hull[hull.length - 1]], trees[i]) < 0;
hull.length > m && cross(trees[hull[hull.length - 2]], trees[hull[hull.length - 1]], trees[i]) < 0;
*/
/* Example usages of 'cross' are shown below:
cross(trees[p], trees[q], trees[r]) < 0;
cross(trees[p], trees[q], trees[i]) === 0;
cross(trees[0], a, b) - cross(trees[0], b, a);
r > 0 && cross(trees[0], trees[len - 1], trees[r]) === 0;
cross(stack[stack.length - 1], top, trees[i]) > 0;
hull.length > 1 && cross(trees[hull[hull.length - 2]], trees[hull[hull.length - 1]], trees[i]) < 0;
hull.length > m && cross(trees[hull[hull.length - 2]], trees[hull[hull.length - 1]], trees[i]) < 0;
*/
const cross = (p, q, r) => (q[0] - p[0]) * (r[1] - q[1]) - (q[1] - p[1]) * (r[0] - q[0])
// 求出凸包的下半部分
for (let i = 1; i < len; i++) {
while (hull.length > 1 && cross(trees[hull[hull.length - 2]], trees[hull[hull.length - 1]], trees[i]) < 0) {
used[hull[hull.length - 1]] = false
hull.pop()
}
used[i] = true
hull.push(i)
}
const m = hull.length
// 求出凸包的上半部分
for (let i = len - 2; i >= 0; i--) {
if (!used[i]) {
while (hull.length > m && cross(trees[hull[hull.length - 2]], trees[hull[hull.length - 1]], trees[i]) < 0) {
used[hull[hull.length - 1]] = false
hull.pop()
}
used[i] = true
hull.push(i)
}
}
// hull[0] 同时参与凸包的上半部分检测,需要去掉重复的 hull[0]
hull.pop()
const size = hull.length
const res = []
for (let i = 0; i < size; i++)
res[i] = trees[hull[i]]
return res
}
|
c9441d47f1f54e90d593f8c411745b0065c0ee23 | 1,664 | ts | TypeScript | packages/rsocket-core/__tests__/test-utils/toMatchYields.ts | Artur-/rsocket-js | 285e3b47e5708d46519adfe1639c5371f55f1ec1 | [
"Apache-2.0"
] | 1 | 2022-01-29T06:09:40.000Z | 2022-01-29T06:09:40.000Z | packages/rsocket-core/__tests__/test-utils/toMatchYields.ts | Artur-/rsocket-js | 285e3b47e5708d46519adfe1639c5371f55f1ec1 | [
"Apache-2.0"
] | null | null | null | packages/rsocket-core/__tests__/test-utils/toMatchYields.ts | Artur-/rsocket-js | 285e3b47e5708d46519adfe1639c5371f55f1ec1 | [
"Apache-2.0"
] | null | null | null | // Modified from https://github.com/doniyor2109/jest-generator
const toOrdinalSuffix = (num) => {
const int = parseInt(num),
digits = [int % 10, int % 100],
ordinals = ["st", "nd", "rd", "th"],
oPattern = [1, 2, 3, 4],
tPattern = [11, 12, 13, 14, 15, 16, 17, 18, 19];
return oPattern.includes(digits[0]) && !tPattern.includes(digits[1])
? int + ordinals[digits[0] - 1]
: int + ordinals[3];
};
export default function toMatchYields(iterator, yieldValues) {
let yieldIndex = 0;
let pass = true;
let received;
let expected;
let iteratorValue;
do {
const [expectedYieldValue] = yieldValues[yieldIndex] || [];
const [, argumentForYield] = yieldValues[yieldIndex - 1] || [];
if (argumentForYield instanceof Error) {
iteratorValue = iterator.throw(argumentForYield);
} else {
iteratorValue = iterator.next(argumentForYield);
}
const yieldedValue = iteratorValue.value;
const isYieldValueSameAsExpected = this.equals(
yieldedValue,
expectedYieldValue
);
if (!isYieldValueSameAsExpected) {
expected = expectedYieldValue;
received = yieldedValue;
pass = false;
break;
}
yieldIndex++;
} while (iteratorValue.done === false);
const expectedMessage = this.utils.printExpected(expected);
const receivedMessage = this.utils.printReceived(received);
return {
pass,
actual: received,
message: () => `${toOrdinalSuffix(
yieldIndex + 1
)} generator value produced did not match with expected.\n
Produced: \n
${receivedMessage}\n
Expected:\n
${expectedMessage}
`,
};
}
| 26.412698 | 70 | 0.633413 | 52 | 3 | 0 | 3 | 17 | 0 | 1 | 0 | 0 | 0 | 1 | 18.666667 | 477 | 0.012579 | 0.035639 | 0 | 0 | 0.002096 | 0 | 0 | 0.315916 | // Modified from https://github.com/doniyor2109/jest-generator
/* Example usages of 'toOrdinalSuffix' are shown below:
toOrdinalSuffix(yieldIndex + 1);
*/
const toOrdinalSuffix = (num) => {
const int = parseInt(num),
digits = [int % 10, int % 100],
ordinals = ["st", "nd", "rd", "th"],
oPattern = [1, 2, 3, 4],
tPattern = [11, 12, 13, 14, 15, 16, 17, 18, 19];
return oPattern.includes(digits[0]) && !tPattern.includes(digits[1])
? int + ordinals[digits[0] - 1]
: int + ordinals[3];
};
export default function toMatchYields(iterator, yieldValues) {
let yieldIndex = 0;
let pass = true;
let received;
let expected;
let iteratorValue;
do {
const [expectedYieldValue] = yieldValues[yieldIndex] || [];
const [, argumentForYield] = yieldValues[yieldIndex - 1] || [];
if (argumentForYield instanceof Error) {
iteratorValue = iterator.throw(argumentForYield);
} else {
iteratorValue = iterator.next(argumentForYield);
}
const yieldedValue = iteratorValue.value;
const isYieldValueSameAsExpected = this.equals(
yieldedValue,
expectedYieldValue
);
if (!isYieldValueSameAsExpected) {
expected = expectedYieldValue;
received = yieldedValue;
pass = false;
break;
}
yieldIndex++;
} while (iteratorValue.done === false);
const expectedMessage = this.utils.printExpected(expected);
const receivedMessage = this.utils.printReceived(received);
return {
pass,
actual: received,
message: () => `${toOrdinalSuffix(
yieldIndex + 1
)} generator value produced did not match with expected.\n
Produced: \n
${receivedMessage}\n
Expected:\n
${expectedMessage}
`,
};
}
|
222cf2ead8695b3c66085604fc83a7c64bdfb130 | 3,186 | ts | TypeScript | solutions/day05.ts | GiyoMoon/aoc2021 | 83d7e9018ed3b628353bc9a0a37b70a1462ecd74 | [
"Unlicense"
] | null | null | null | solutions/day05.ts | GiyoMoon/aoc2021 | 83d7e9018ed3b628353bc9a0a37b70a1462ecd74 | [
"Unlicense"
] | 1 | 2022-02-03T11:04:17.000Z | 2022-02-03T11:04:17.000Z | solutions/day05.ts | GiyoMoon/aoc2021 | 83d7e9018ed3b628353bc9a0a37b70a1462ecd74 | [
"Unlicense"
] | null | null | null | export default class Day5 {
private _heatmap: number[][];
public solve(input: string): { part1: any, part2: any; } {
const vents = input.split('\n').map(v => {
const coords = v.split(' -> ');
return [...coords[0].split(',').map(n => parseInt(n)), ...coords[1].split(',').map(n => parseInt(n))];
});
// part 1
let filteredVents = vents.filter(v => v[0] === v[2] || v[1] === v[3]);
this._heatmap = [];
filteredVents.forEach(vent => {
if (vent[0] === vent[2]) {
this._addHorizontalVent(vent);
} else {
this._addVerticalVent(vent);
}
});
const criticalCoordsPart1 = this._getCriticalCoords();
// part 2
filteredVents = vents.filter(v => v[0] === v[2] || v[1] === v[3] || Math.abs(v[0] - v[2]) === Math.abs(v[1] - v[3]));
this._heatmap = [];
filteredVents.forEach(vent => {
if (vent[0] === vent[2]) {
this._addHorizontalVent(vent);
} else if (vent[1] === vent[3]) {
this._addVerticalVent(vent);
} else {
this._addDiagonalVent(vent);
}
});
const criticalCoordsPart2 = this._getCriticalCoords();
return { part1: criticalCoordsPart1, part2: criticalCoordsPart2 };
}
private _addHorizontalVent(vent: number[]) {
const lowerCoord = vent[1] > vent[3] ? vent[3] : vent[1];
new Array(Math.abs(vent[1] - vent[3]) + 1).fill('').forEach((_, i) => {
if (!this._heatmap[lowerCoord + i]) {
this._heatmap[lowerCoord + i] = [];
}
if (this._heatmap[lowerCoord + i][vent[0]]) {
this._heatmap[lowerCoord + i][vent[0]] += 1;
} else {
this._heatmap[lowerCoord + i][vent[0]] = 1;
}
});
}
private _addVerticalVent(vent: number[]) {
const lowerCoord = vent[0] > vent[2] ? vent[2] : vent[0];
new Array(Math.abs(vent[2] - vent[0]) + 1).fill('').forEach((_, i) => {
if (!this._heatmap[vent[1]]) {
this._heatmap[vent[1]] = [];
}
if (this._heatmap[vent[1]][lowerCoord + i]) {
this._heatmap[vent[1]][lowerCoord + i] += 1;
} else {
this._heatmap[vent[1]][lowerCoord + i] = 1;
}
});
};
private _addDiagonalVent(vent: number[]) {
const lowerCoordY = vent[1] > vent[3] ? vent[3] : vent[1];
const turn = vent[1] > vent[3] ? true : false;
let multiplier = 1;
if (turn && vent[2] < vent[0]) {
multiplier = -1;
} else if (!turn && vent[2] < vent[0]) {
multiplier = -1;
}
new Array(Math.abs(vent[1] - vent[3]) + 1).fill('').forEach((_, i) => {
const x = turn ? (vent[2] - i * multiplier) : (vent[0] + i * multiplier);
if (!this._heatmap[lowerCoordY + i]) {
this._heatmap[lowerCoordY + i] = [];
}
if (this._heatmap[lowerCoordY + i][x]) {
this._heatmap[lowerCoordY + i][x] += 1;
} else {
this._heatmap[lowerCoordY + i][x] = 1;
}
});
}
private _getCriticalCoords() {
let criticalCoords = 0;
this._heatmap.forEach(line => {
if (line) {
line.forEach(m => {
if (m && m > 1) {
criticalCoords++;
}
});
}
});
return criticalCoords;
}
}
| 28.963636 | 121 | 0.52103 | 92 | 17 | 0 | 19 | 12 | 1 | 4 | 2 | 5 | 1 | 0 | 7.764706 | 1,017 | 0.035398 | 0.011799 | 0.000983 | 0.000983 | 0 | 0.040816 | 0.102041 | 0.293265 | export default class Day5 {
private _heatmap;
public solve(input) {
const vents = input.split('\n').map(v => {
const coords = v.split(' -> ');
return [...coords[0].split(',').map(n => parseInt(n)), ...coords[1].split(',').map(n => parseInt(n))];
});
// part 1
let filteredVents = vents.filter(v => v[0] === v[2] || v[1] === v[3]);
this._heatmap = [];
filteredVents.forEach(vent => {
if (vent[0] === vent[2]) {
this._addHorizontalVent(vent);
} else {
this._addVerticalVent(vent);
}
});
const criticalCoordsPart1 = this._getCriticalCoords();
// part 2
filteredVents = vents.filter(v => v[0] === v[2] || v[1] === v[3] || Math.abs(v[0] - v[2]) === Math.abs(v[1] - v[3]));
this._heatmap = [];
filteredVents.forEach(vent => {
if (vent[0] === vent[2]) {
this._addHorizontalVent(vent);
} else if (vent[1] === vent[3]) {
this._addVerticalVent(vent);
} else {
this._addDiagonalVent(vent);
}
});
const criticalCoordsPart2 = this._getCriticalCoords();
return { part1: criticalCoordsPart1, part2: criticalCoordsPart2 };
}
private _addHorizontalVent(vent) {
const lowerCoord = vent[1] > vent[3] ? vent[3] : vent[1];
new Array(Math.abs(vent[1] - vent[3]) + 1).fill('').forEach((_, i) => {
if (!this._heatmap[lowerCoord + i]) {
this._heatmap[lowerCoord + i] = [];
}
if (this._heatmap[lowerCoord + i][vent[0]]) {
this._heatmap[lowerCoord + i][vent[0]] += 1;
} else {
this._heatmap[lowerCoord + i][vent[0]] = 1;
}
});
}
private _addVerticalVent(vent) {
const lowerCoord = vent[0] > vent[2] ? vent[2] : vent[0];
new Array(Math.abs(vent[2] - vent[0]) + 1).fill('').forEach((_, i) => {
if (!this._heatmap[vent[1]]) {
this._heatmap[vent[1]] = [];
}
if (this._heatmap[vent[1]][lowerCoord + i]) {
this._heatmap[vent[1]][lowerCoord + i] += 1;
} else {
this._heatmap[vent[1]][lowerCoord + i] = 1;
}
});
};
private _addDiagonalVent(vent) {
const lowerCoordY = vent[1] > vent[3] ? vent[3] : vent[1];
const turn = vent[1] > vent[3] ? true : false;
let multiplier = 1;
if (turn && vent[2] < vent[0]) {
multiplier = -1;
} else if (!turn && vent[2] < vent[0]) {
multiplier = -1;
}
new Array(Math.abs(vent[1] - vent[3]) + 1).fill('').forEach((_, i) => {
const x = turn ? (vent[2] - i * multiplier) : (vent[0] + i * multiplier);
if (!this._heatmap[lowerCoordY + i]) {
this._heatmap[lowerCoordY + i] = [];
}
if (this._heatmap[lowerCoordY + i][x]) {
this._heatmap[lowerCoordY + i][x] += 1;
} else {
this._heatmap[lowerCoordY + i][x] = 1;
}
});
}
private _getCriticalCoords() {
let criticalCoords = 0;
this._heatmap.forEach(line => {
if (line) {
line.forEach(m => {
if (m && m > 1) {
criticalCoords++;
}
});
}
});
return criticalCoords;
}
}
|
22df358673565dcee46071280b05b031077329af | 3,657 | ts | TypeScript | clients/scheduler/src/utils/dates/calendar.ts | canvas-medical/embed | 3aea6b3348df108a815226c8d0d43796a5755f32 | [
"Apache-2.0"
] | 5 | 2022-03-08T17:59:21.000Z | 2022-03-29T16:09:36.000Z | clients/scheduler/src/utils/dates/calendar.ts | canvas-medical/embed | 3aea6b3348df108a815226c8d0d43796a5755f32 | [
"Apache-2.0"
] | 23 | 2022-03-24T21:10:28.000Z | 2022-03-24T22:24:25.000Z | clients/scheduler/src/utils/dates/calendar.ts | canvas-medical/embed | 3aea6b3348df108a815226c8d0d43796a5755f32 | [
"Apache-2.0"
] | null | null | null | export type MonthAndYearType = {
string: string
date: Date
}
const monthStrings = [
'January',
'February',
'March',
'April',
'May',
'June',
'July',
'August',
'September',
'October',
'Novemeber',
'Decemeber',
]
export const getMonthAndYearOptions = (): MonthAndYearType[] => {
const date = new Date()
const year = date.getFullYear()
const startMonth = date.getMonth()
const months: MonthAndYearType[] = []
for (let i = 0; i < 12; i++) {
if (startMonth + i > 11) {
months.push({
string: `${monthStrings[startMonth + i - 12]} ${year + 1}`,
date: new Date(year + 1, startMonth + i - 12, 1),
})
} else {
months.push({
string: `${monthStrings[startMonth + i]} ${year}`,
date: new Date(year, startMonth + i, 1),
})
}
}
return months
}
export const sameMonthAndYear = (dateA: Date, dateB: Date) => {
return (
dateA.getMonth() === dateB.getMonth() &&
dateA.getFullYear() === dateB.getFullYear()
)
}
export const getNextMonth = (date: Date) => {
const month = date.getMonth()
const year = date.getFullYear()
if (month === 11) {
return new Date(year + 1, 0, 1)
}
return new Date(year, month + 1, 1)
}
export const getPreviousMonth = (date: Date) => {
const today = new Date()
const month = date.getMonth()
const year = date.getFullYear()
if (month === 0) {
if (today.getFullYear() === year - 1 && today.getMonth() === 11) {
return new Date(year - 1, 11, today.getDate())
}
return new Date(year - 1, 11, 1)
}
if (today.getFullYear() === year && today.getMonth() === month - 1) {
return new Date(year, month - 1, today.getDate())
}
return new Date(year, month - 1, 1)
}
const getDateString = (year: number, month: number, day: number) => {
return new Date(year, month, day).toDateString()
}
const isLeapYear = (date: Date) => {
const year = date.getFullYear()
return year % 400 === 0 || (year % 4 === 0 && year % 100 !== 0)
}
const getDaysInMonth = (date: Date) => {
const leapYear = isLeapYear(date)
const month = date.getMonth()
// getMonth() returns zero indexed month, so each month is the normal month number - 1
// I.E. January is 0, February is 1, March is 2, etc.
switch (month) {
case 1:
if (leapYear) {
return 29
}
return 28
case 3:
case 5:
case 8:
case 10:
return 30
default:
return 31
}
}
export const generateDays = (date: Date) => {
const year = date.getFullYear()
const month = date.getMonth()
const daysInMonth = getDaysInMonth(date)
const today = new Date()
const days = []
for (let i = 1; i < daysInMonth + 1; i++) {
if (
i < today.getDate() &&
month <= today.getMonth() &&
year <= today.getFullYear()
) {
days.push({
date: i,
disabled: true,
dateString: getDateString(year, month, i),
})
} else {
days.push({
date: i,
disabled: false,
dateString: getDateString(year, month, i),
})
}
}
return days
}
// Generates an array of "skip days" to place the first day of the month
// on the right day of the week
export const getSkipDays = (date: Date) => {
const year = date.getFullYear()
const month = date.getMonth()
const firstDay = new Date(year, month, 1).getDay()
const skipppedDays = []
for (let i = 0; i < firstDay; i++) {
skipppedDays.push(i)
}
return skipppedDays
}
export const getMonthAndYearString = (date: Date) => {
const year = date.getFullYear()
const month = date.getMonth()
return `${monthStrings[month]} ${year}`
}
| 22.435583 | 88 | 0.585726 | 134 | 10 | 0 | 12 | 37 | 2 | 3 | 0 | 4 | 1 | 0 | 9.6 | 1,150 | 0.01913 | 0.032174 | 0.001739 | 0.00087 | 0 | 0 | 0.065574 | 0.322033 | export type MonthAndYearType = {
string
date
}
const monthStrings = [
'January',
'February',
'March',
'April',
'May',
'June',
'July',
'August',
'September',
'October',
'Novemeber',
'Decemeber',
]
export const getMonthAndYearOptions = () => {
const date = new Date()
const year = date.getFullYear()
const startMonth = date.getMonth()
const months = []
for (let i = 0; i < 12; i++) {
if (startMonth + i > 11) {
months.push({
string: `${monthStrings[startMonth + i - 12]} ${year + 1}`,
date: new Date(year + 1, startMonth + i - 12, 1),
})
} else {
months.push({
string: `${monthStrings[startMonth + i]} ${year}`,
date: new Date(year, startMonth + i, 1),
})
}
}
return months
}
export const sameMonthAndYear = (dateA, dateB) => {
return (
dateA.getMonth() === dateB.getMonth() &&
dateA.getFullYear() === dateB.getFullYear()
)
}
export const getNextMonth = (date) => {
const month = date.getMonth()
const year = date.getFullYear()
if (month === 11) {
return new Date(year + 1, 0, 1)
}
return new Date(year, month + 1, 1)
}
export const getPreviousMonth = (date) => {
const today = new Date()
const month = date.getMonth()
const year = date.getFullYear()
if (month === 0) {
if (today.getFullYear() === year - 1 && today.getMonth() === 11) {
return new Date(year - 1, 11, today.getDate())
}
return new Date(year - 1, 11, 1)
}
if (today.getFullYear() === year && today.getMonth() === month - 1) {
return new Date(year, month - 1, today.getDate())
}
return new Date(year, month - 1, 1)
}
/* Example usages of 'getDateString' are shown below:
getDateString(year, month, i);
*/
const getDateString = (year, month, day) => {
return new Date(year, month, day).toDateString()
}
/* Example usages of 'isLeapYear' are shown below:
isLeapYear(date);
*/
const isLeapYear = (date) => {
const year = date.getFullYear()
return year % 400 === 0 || (year % 4 === 0 && year % 100 !== 0)
}
/* Example usages of 'getDaysInMonth' are shown below:
getDaysInMonth(date);
*/
const getDaysInMonth = (date) => {
const leapYear = isLeapYear(date)
const month = date.getMonth()
// getMonth() returns zero indexed month, so each month is the normal month number - 1
// I.E. January is 0, February is 1, March is 2, etc.
switch (month) {
case 1:
if (leapYear) {
return 29
}
return 28
case 3:
case 5:
case 8:
case 10:
return 30
default:
return 31
}
}
export const generateDays = (date) => {
const year = date.getFullYear()
const month = date.getMonth()
const daysInMonth = getDaysInMonth(date)
const today = new Date()
const days = []
for (let i = 1; i < daysInMonth + 1; i++) {
if (
i < today.getDate() &&
month <= today.getMonth() &&
year <= today.getFullYear()
) {
days.push({
date: i,
disabled: true,
dateString: getDateString(year, month, i),
})
} else {
days.push({
date: i,
disabled: false,
dateString: getDateString(year, month, i),
})
}
}
return days
}
// Generates an array of "skip days" to place the first day of the month
// on the right day of the week
export const getSkipDays = (date) => {
const year = date.getFullYear()
const month = date.getMonth()
const firstDay = new Date(year, month, 1).getDay()
const skipppedDays = []
for (let i = 0; i < firstDay; i++) {
skipppedDays.push(i)
}
return skipppedDays
}
export const getMonthAndYearString = (date) => {
const year = date.getFullYear()
const month = date.getMonth()
return `${monthStrings[month]} ${year}`
}
|
22e04477d1c4c020cbd5772bd3cbec80d0b15d26 | 2,775 | ts | TypeScript | problemset/all-one-data-structure/index.ts | OUDUIDUI/leet-code | 50e61ce16d1c419ccefc075ae9ead721cdd1cdbb | [
"MIT"
] | 6 | 2022-01-17T03:19:56.000Z | 2022-01-17T05:45:39.000Z | problemset/all-one-data-structure/index.ts | OUDUIDUI/leet-code | 50e61ce16d1c419ccefc075ae9ead721cdd1cdbb | [
"MIT"
] | null | null | null | problemset/all-one-data-structure/index.ts | OUDUIDUI/leet-code | 50e61ce16d1c419ccefc075ae9ead721cdd1cdbb | [
"MIT"
] | null | null | null | export class AllOne {
root: Node = new Node()
nodes: Map<string, Node> = new Map<string, Node>()
constructor() {
// 初始化链表哨兵,下面判断节点的next若为root的话,则表示next为空,prev同理
this.root.prev = this.root
this.root.next = this.root
}
/**
* 新增key,如存在增加计数
* @param key
*/
inc(key: string): void {
// 如果存在该key值
if (this.nodes.has(key)) {
// 获取该key值的双链表
const cur = this.nodes.get(key)!
const next = cur.next!
if (next === this.root || next.count > cur.count + 1) {
this.nodes.set(key, cur.insert(new Node(key, cur.count + 1)))
}
else {
next.keys.add(key)
this.nodes.set(key, next)
}
cur.keys.delete(key)
if (cur.keys.size === 0) cur.remove()
}
// 如果不存在该key值
else {
if (this.root.next === this.root || this.root.next!.count > 1) {
this.nodes.set(key, this.root.insert(new Node(key, 1)))
}
else {
this.root.next!.keys.add(key)
this.nodes.set(key, this.root.next!)
}
}
}
/**
* 对应字符串 key 计数减一
* @param key
*/
dec(key: string): void {
// 如果没有对应字符串,直接返回
if (!this.nodes.has(key)) return
// 获取该key值的双链表
const cur = this.nodes.get(key)!
// key仅出现一次,将其移除nodes
if (cur.count === 1) {
this.nodes.delete(key)
}
// key 出现不止一次
else {
const pre = cur.prev!
if (pre === this.root || pre.count < cur.count - 1) {
this.nodes.set(key, pre.insert(new Node(key, cur.count - 1)))
}
else {
pre.keys.add(key)
this.nodes.set(key, pre)
}
}
cur.keys.delete(key)
if (cur.keys.size === 0) cur.remove()
}
/**
* 返回任意一个计数最小的字符串
*/
getMaxKey(): string {
if (!this.root.prev) return ''
let maxKey = ''
// 在链表不为空时,返回链表尾节点的 keys 中的任一元素
if (this.root.prev!.keys.size !== 0)
maxKey = Array.from(this.root.prev!.keys)[0]
return maxKey
}
/**
* 返回任意一个计数最大的字符串
*/
getMinKey(): string {
if (!this.root.next) return ''
let minKey = ''
// 在链表不为空时,返回链表头节点的 keys 中的任一元素
if (this.root.next!.keys.size !== 0)
minKey = Array.from(this.root.next!.keys)[0]
return minKey
}
}
/**
* 双向链表
*/
class Node {
count: number
keys: Set<string>
prev: Node | null = null // 上一个节点
next: Node | null = null // 下一个节点
constructor(key = '', count = 0) {
this.count = count
this.keys = new Set<string>([key])
}
/**
* 在末尾插入新节点
* @param node
*/
insert(node: Node) {
node.prev = this
node.next = this.next
node.prev.next = node
node.next && (node.next.prev = node)
return node
}
/**
* 移除当前节点
*/
remove() {
this.prev && (this.prev.next = this.next)
this.next && (this.next.prev = this.prev)
}
}
| 20.708955 | 70 | 0.543423 | 86 | 8 | 0 | 5 | 6 | 6 | 2 | 0 | 11 | 2 | 0 | 7.5 | 987 | 0.013171 | 0.006079 | 0.006079 | 0.002026 | 0 | 0 | 0.44 | 0.223924 | export class AllOne {
root = new Node()
nodes = new Map<string, Node>()
constructor() {
// 初始化链表哨兵,下面判断节点的next若为root的话,则表示next为空,prev同理
this.root.prev = this.root
this.root.next = this.root
}
/**
* 新增key,如存在增加计数
* @param key
*/
inc(key) {
// 如果存在该key值
if (this.nodes.has(key)) {
// 获取该key值的双链表
const cur = this.nodes.get(key)!
const next = cur.next!
if (next === this.root || next.count > cur.count + 1) {
this.nodes.set(key, cur.insert(new Node(key, cur.count + 1)))
}
else {
next.keys.add(key)
this.nodes.set(key, next)
}
cur.keys.delete(key)
if (cur.keys.size === 0) cur.remove()
}
// 如果不存在该key值
else {
if (this.root.next === this.root || this.root.next!.count > 1) {
this.nodes.set(key, this.root.insert(new Node(key, 1)))
}
else {
this.root.next!.keys.add(key)
this.nodes.set(key, this.root.next!)
}
}
}
/**
* 对应字符串 key 计数减一
* @param key
*/
dec(key) {
// 如果没有对应字符串,直接返回
if (!this.nodes.has(key)) return
// 获取该key值的双链表
const cur = this.nodes.get(key)!
// key仅出现一次,将其移除nodes
if (cur.count === 1) {
this.nodes.delete(key)
}
// key 出现不止一次
else {
const pre = cur.prev!
if (pre === this.root || pre.count < cur.count - 1) {
this.nodes.set(key, pre.insert(new Node(key, cur.count - 1)))
}
else {
pre.keys.add(key)
this.nodes.set(key, pre)
}
}
cur.keys.delete(key)
if (cur.keys.size === 0) cur.remove()
}
/**
* 返回任意一个计数最小的字符串
*/
getMaxKey() {
if (!this.root.prev) return ''
let maxKey = ''
// 在链表不为空时,返回链表尾节点的 keys 中的任一元素
if (this.root.prev!.keys.size !== 0)
maxKey = Array.from(this.root.prev!.keys)[0]
return maxKey
}
/**
* 返回任意一个计数最大的字符串
*/
getMinKey() {
if (!this.root.next) return ''
let minKey = ''
// 在链表不为空时,返回链表头节点的 keys 中的任一元素
if (this.root.next!.keys.size !== 0)
minKey = Array.from(this.root.next!.keys)[0]
return minKey
}
}
/**
* 双向链表
*/
class Node {
count
keys
prev = null // 上一个节点
next = null // 下一个节点
constructor(key = '', count = 0) {
this.count = count
this.keys = new Set<string>([key])
}
/**
* 在末尾插入新节点
* @param node
*/
insert(node) {
node.prev = this
node.next = this.next
node.prev.next = node
node.next && (node.next.prev = node)
return node
}
/**
* 移除当前节点
*/
remove() {
this.prev && (this.prev.next = this.next)
this.next && (this.next.prev = this.prev)
}
}
|
e26005141389cbb08cda3e19995b88d306446290 | 2,342 | ts | TypeScript | src/lib/hooks/usePagination.ts | sveltevk/VKSUI | fba13c1f66e6891e8d9b6934d1711bf2f94e2f46 | [
"MIT"
] | 7 | 2022-03-06T08:05:58.000Z | 2022-03-29T13:15:28.000Z | src/lib/hooks/usePagination.ts | sveltevk/VKSUI | fba13c1f66e6891e8d9b6934d1711bf2f94e2f46 | [
"MIT"
] | null | null | null | src/lib/hooks/usePagination.ts | sveltevk/VKSUI | fba13c1f66e6891e8d9b6934d1711bf2f94e2f46 | [
"MIT"
] | null | null | null | interface UsePagintaionProps {
/**
* Текущая страница.
*/
currentPage?: number;
/**
* Кол-во всегда видимых страниц по краям текущей страницы.
*/
siblingCount?: number;
/**
* Кол-во всегда видимых страниц в начале и в конце.
*/
boundaryCount?: number;
/**
* Общее кол-во страниц.
*/
totalPages?: number;
}
export type PaginationPageType = 'start-ellipsis' | 'end-ellipsis' | number;
export type UsePaginationResult = PaginationPageType[];
/**
* Хук взаимствован у @mui с некоторыми изменениями.
* [usePagination.js](https://github.com/mui/material-ui/blob/master/packages/mui-material/src/usePagination/usePagination.js).
*
* Примеры вывода:
* v
* [1, 2, 3, 4, 5, 'end-ellipsis', 10]
* v
* [1, 'start-ellipsis', 4, 5, 6, 'end-ellipsis', 10]
* v
* [1, 'start-ellipsis', 6, 7, 8, 9, 10]
*/
export const usePagination = ({
currentPage = 1,
siblingCount = 1,
boundaryCount = 1,
totalPages: endPage = 1
}: UsePagintaionProps = {}): UsePaginationResult => {
const range = (from: number, to: number, step = 1) => {
const range = [];
let i = from;
while (i <= to) {
range.push(i);
i += step;
}
return range;
};
const startPages = range(1, Math.min(boundaryCount, endPage));
const endPages = range(Math.max(endPage - boundaryCount + 1, boundaryCount + 1), endPage);
const lowerBoundaryWhenCurrentPageHigh = endPage - boundaryCount - 1 - 2 * siblingCount;
const siblingsStart = Math.max(
Math.min(currentPage - siblingCount, lowerBoundaryWhenCurrentPageHigh),
boundaryCount + 2
);
const upperBounadryWhenCurrentPageLow = boundaryCount + 2 + 2 * siblingCount;
const siblingsEnd = Math.min(
Math.max(currentPage + siblingCount, upperBounadryWhenCurrentPageLow),
endPages.length > 0 ? endPages[0] - 2 : endPage - 1
);
const pages: UsePaginationResult = startPages;
if (siblingsStart > boundaryCount + 2) {
pages.push('start-ellipsis');
} else if (boundaryCount + 1 < endPage - boundaryCount) {
pages.push(boundaryCount + 1);
}
pages.push(...range(siblingsStart, siblingsEnd));
if (siblingsEnd < endPage - boundaryCount - 1) {
pages.push('end-ellipsis');
} else if (endPage - boundaryCount > boundaryCount) {
pages.push(endPage - boundaryCount);
}
pages.push(...endPages);
return pages;
};
| 26.314607 | 128 | 0.665243 | 50 | 2 | 0 | 4 | 11 | 4 | 1 | 0 | 7 | 3 | 0 | 21 | 835 | 0.007186 | 0.013174 | 0.00479 | 0.003593 | 0 | 0 | 0.333333 | 0.23557 | interface UsePagintaionProps {
/**
* Текущая страница.
*/
currentPage?;
/**
* Кол-во всегда видимых страниц по краям текущей страницы.
*/
siblingCount?;
/**
* Кол-во всегда видимых страниц в начале и в конце.
*/
boundaryCount?;
/**
* Общее кол-во страниц.
*/
totalPages?;
}
export type PaginationPageType = 'start-ellipsis' | 'end-ellipsis' | number;
export type UsePaginationResult = PaginationPageType[];
/**
* Хук взаимствован у @mui с некоторыми изменениями.
* [usePagination.js](https://github.com/mui/material-ui/blob/master/packages/mui-material/src/usePagination/usePagination.js).
*
* Примеры вывода:
* v
* [1, 2, 3, 4, 5, 'end-ellipsis', 10]
* v
* [1, 'start-ellipsis', 4, 5, 6, 'end-ellipsis', 10]
* v
* [1, 'start-ellipsis', 6, 7, 8, 9, 10]
*/
export const usePagination = ({
currentPage = 1,
siblingCount = 1,
boundaryCount = 1,
totalPages: endPage = 1
} = {}) => {
/* Example usages of 'range' are shown below:
var range = [];
range.push(i);
return range;
range(1, Math.min(boundaryCount, endPage));
range(Math.max(endPage - boundaryCount + 1, boundaryCount + 1), endPage);
range(siblingsStart, siblingsEnd);
*/
const range = (from, to, step = 1) => {
const range = [];
let i = from;
while (i <= to) {
range.push(i);
i += step;
}
return range;
};
const startPages = range(1, Math.min(boundaryCount, endPage));
const endPages = range(Math.max(endPage - boundaryCount + 1, boundaryCount + 1), endPage);
const lowerBoundaryWhenCurrentPageHigh = endPage - boundaryCount - 1 - 2 * siblingCount;
const siblingsStart = Math.max(
Math.min(currentPage - siblingCount, lowerBoundaryWhenCurrentPageHigh),
boundaryCount + 2
);
const upperBounadryWhenCurrentPageLow = boundaryCount + 2 + 2 * siblingCount;
const siblingsEnd = Math.min(
Math.max(currentPage + siblingCount, upperBounadryWhenCurrentPageLow),
endPages.length > 0 ? endPages[0] - 2 : endPage - 1
);
const pages = startPages;
if (siblingsStart > boundaryCount + 2) {
pages.push('start-ellipsis');
} else if (boundaryCount + 1 < endPage - boundaryCount) {
pages.push(boundaryCount + 1);
}
pages.push(...range(siblingsStart, siblingsEnd));
if (siblingsEnd < endPage - boundaryCount - 1) {
pages.push('end-ellipsis');
} else if (endPage - boundaryCount > boundaryCount) {
pages.push(endPage - boundaryCount);
}
pages.push(...endPages);
return pages;
};
|
e28b80476b0b16c0c6e3488245ade077d4b0b7ea | 1,600 | ts | TypeScript | src/tiltfile-error-parser.ts | tilt-dev/vscode-tilt | 6777d9d3772025d2a59dce283e2e147879897820 | [
"Apache-2.0"
] | 3 | 2022-03-23T21:42:14.000Z | 2022-03-30T08:37:53.000Z | src/tiltfile-error-parser.ts | tilt-dev/vscode-tilt | 6777d9d3772025d2a59dce283e2e147879897820 | [
"Apache-2.0"
] | null | null | null | src/tiltfile-error-parser.ts | tilt-dev/vscode-tilt | 6777d9d3772025d2a59dce283e2e147879897820 | [
"Apache-2.0"
] | null | null | null | const locationPattern = `(?<file>[A-Za-z0-9\/ \\\._-]+):(?<line>[1-9][0-9]*):(?<col>[1-9][0-9]*)`
const tracebackLocationRe = new RegExp(`^\\s*${locationPattern}`)
const simpleErrorRe = new RegExp(`^${locationPattern}: (?<message>.+)`)
const loadErrorRe = new RegExp(
`Error: cannot load \\S+: ${locationPattern}: .+`
)
export type Location = {
path: string
line: number
col: number
}
// m must be a match from `pathLineColPattern`
function matchToLocation(m: RegExpMatchArray): Location {
return {
path: m.groups.file,
line: parseInt(m.groups.line),
col: parseInt(m.groups.col),
}
}
export function parseTiltfileError(error: string):
| {
message: string
locations: Location[]
}
| undefined {
if (!error) {
return undefined
}
if (error.startsWith("Traceback")) {
const lines = error.split("\n")
let locations = new Array<Location>()
for (let i = 1; i < lines.length; i++) {
const line = lines[i]
let match = line.match(tracebackLocationRe)
if (match) {
locations.push(matchToLocation(match))
} else {
match = line.match(loadErrorRe)
if (match) {
locations.push(matchToLocation(match))
}
const message = lines.splice(i, lines.length - i).join("\n")
return {
message: message,
locations: locations,
}
}
}
}
const match = error.match(simpleErrorRe)
if (match) {
return {
message: match.groups.message,
locations: [matchToLocation(match)],
}
}
return { message: "", locations: [] }
}
| 25.396825 | 97 | 0.5975 | 57 | 2 | 0 | 2 | 11 | 3 | 1 | 0 | 5 | 1 | 0 | 18.5 | 462 | 0.008658 | 0.02381 | 0.006494 | 0.002165 | 0 | 0 | 0.277778 | 0.27153 | const locationPattern = `(?<file>[A-Za-z0-9\/ \\\._-]+):(?<line>[1-9][0-9]*):(?<col>[1-9][0-9]*)`
const tracebackLocationRe = new RegExp(`^\\s*${locationPattern}`)
const simpleErrorRe = new RegExp(`^${locationPattern}: (?<message>.+)`)
const loadErrorRe = new RegExp(
`Error: cannot load \\S+: ${locationPattern}: .+`
)
export type Location = {
path
line
col
}
// m must be a match from `pathLineColPattern`
/* Example usages of 'matchToLocation' are shown below:
locations.push(matchToLocation(match));
matchToLocation(match);
*/
function matchToLocation(m) {
return {
path: m.groups.file,
line: parseInt(m.groups.line),
col: parseInt(m.groups.col),
}
}
export function parseTiltfileError(error) {
if (!error) {
return undefined
}
if (error.startsWith("Traceback")) {
const lines = error.split("\n")
let locations = new Array<Location>()
for (let i = 1; i < lines.length; i++) {
const line = lines[i]
let match = line.match(tracebackLocationRe)
if (match) {
locations.push(matchToLocation(match))
} else {
match = line.match(loadErrorRe)
if (match) {
locations.push(matchToLocation(match))
}
const message = lines.splice(i, lines.length - i).join("\n")
return {
message: message,
locations: locations,
}
}
}
}
const match = error.match(simpleErrorRe)
if (match) {
return {
message: match.groups.message,
locations: [matchToLocation(match)],
}
}
return { message: "", locations: [] }
}
|
e2a4719ad32c2139942288ce9ce6e902cc54eaad | 3,734 | ts | TypeScript | packages/page-engine/src/config/utils.ts | hhhqm/one-for-all | 7d21f5cca2b7a8ade73902260599ae0cc2afbfb2 | [
"Apache-2.0"
] | 1 | 2022-03-30T03:49:18.000Z | 2022-03-30T03:49:18.000Z | packages/page-engine/src/config/utils.ts | hhhqm/one-for-all | 7d21f5cca2b7a8ade73902260599ae0cc2afbfb2 | [
"Apache-2.0"
] | null | null | null | packages/page-engine/src/config/utils.ts | hhhqm/one-for-all | 7d21f5cca2b7a8ade73902260599ae0cc2afbfb2 | [
"Apache-2.0"
] | null | null | null | type StyleKey = 'value' | 'unit';
export const STYLE_NUMBER = [
'width', 'height', 'fontSize', 'lineHeight', 'borderWidth', 'fontWeight',
'marginTop', 'marginLeft', 'marginRight', 'marginBottom', 'borderTopWidth', 'borderLeftWidth',
'borderRightWidth', 'borderBottomWidth', 'paddingTop', 'paddingLeft', 'paddingRight', 'paddingBottom',
'borderTopLeftRadius', 'borderTopRightRadius', 'borderBottomRightRadius', 'borderBottomLeftRadius',
'zIndex',
];
const NEW_STYLES = [
'width', 'height', 'fontSize', 'lineHeight', 'top', 'left', 'right', 'bottom',
];
// 拿到样式格式化为表单所需要的格式
export function parseStyleToForm(styles: Record<string, string | number>): Record<string, string | number> {
const newStyles: Record<string, string | number> = {};
if (typeof (styles) !== 'object' || styles === null) {
return newStyles;
}
Object.entries(styles).forEach((style) => {
const [key, value] = style;
if (key === 'backgroundImage') {
newStyles[key] = handleImageUrl(value as string);
return;
}
if (NEW_STYLES.includes(key)) {
const _value = parseStyleString(value as (string | number));
newStyles[key] = _value.value;
newStyles[`${key}Unit`] = _value.unit;
return;
}
newStyles[key] = value;
});
return newStyles;
}
// 将表单格式的样式格式化为css所接受样式,并移除 为空,为 0的值
export const formatStyles = (styles: Record<string, string | number>): Record<string, string | number> => {
const newStyles: Record<string, string | number> = {};
if (typeof (styles) !== 'object' || styles === null) {
return newStyles;
}
Object.entries(styles).forEach((style) => {
const [key, value] = style;
if (value === '' || value === 0) return;
if (key.indexOf('Unit') >= 0) return;
if (key === 'backgroundImage') {
if (value === 'none') return;
newStyles[key] = `url(${value})`;
return;
}
if (NEW_STYLES.includes(key)) {
const _value = formatStyleString(value, (styles[`${key}Unit`] as string) || 'px');
newStyles[key] = _value;
return;
}
if (STYLE_NUMBER.includes(key)) {
newStyles[key] = Number(value) || 0;
return;
}
newStyles[key] = value;
});
return newStyles;
};
// 根据值解析得出 值以及单位
export function parseStyleString(value: string | number): Record<StyleKey, string> {
const _value = {
value: '',
unit: 'px',
};
if (value === 0 || !value || !(['string', 'number'].includes(typeof (value)))) return _value;
if (typeof (value) === 'number') {
_value.value = value.toString();
_value.unit = 'px';
return _value;
}
// auto
if (value === 'auto') {
_value.value = 'auto';
_value.unit = 'auto';
return _value;
}
// px
if (value.indexOf('px') >= 0) {
const _site = value.indexOf('px');
_value.value = value.substring(0, _site);
return _value;
}
// %
if (value.indexOf('%') >= 0) {
const _site = value.indexOf('%');
_value.value = value.substring(0, _site);
_value.unit = '%';
return _value;
}
return _value;
}
export function formatStyleString(value: string | number, unitValue = 'px'): string {
const newValue = '';
if (value === 0 || !value) return '0' + unitValue;
if (value === 'auto') {
return 'auto';
}
if (unitValue === 'px' || unitValue === '%') {
return value.toString() + unitValue;
}
return newValue;
}
// todo: 单独处理边框样式
// function handleBorderStyle(): Record<string, string | number> {
// const newStyles = {};
// return newStyles;
// }
function handleImageUrl(url: string): string {
let _url = '';
if (url.indexOf('url') === 0) {
_url = url.substring(4, url.length - 1);
}
if (url === 'none') {
return _url;
}
return _url;
}
| 24.405229 | 108 | 0.602035 | 109 | 7 | 0 | 8 | 14 | 0 | 3 | 0 | 30 | 1 | 7 | 16.857143 | 1,132 | 0.013251 | 0.012367 | 0 | 0.000883 | 0.006184 | 0 | 1.034483 | 0.241422 | type StyleKey = 'value' | 'unit';
export const STYLE_NUMBER = [
'width', 'height', 'fontSize', 'lineHeight', 'borderWidth', 'fontWeight',
'marginTop', 'marginLeft', 'marginRight', 'marginBottom', 'borderTopWidth', 'borderLeftWidth',
'borderRightWidth', 'borderBottomWidth', 'paddingTop', 'paddingLeft', 'paddingRight', 'paddingBottom',
'borderTopLeftRadius', 'borderTopRightRadius', 'borderBottomRightRadius', 'borderBottomLeftRadius',
'zIndex',
];
const NEW_STYLES = [
'width', 'height', 'fontSize', 'lineHeight', 'top', 'left', 'right', 'bottom',
];
// 拿到样式格式化为表单所需要的格式
export function parseStyleToForm(styles) {
const newStyles = {};
if (typeof (styles) !== 'object' || styles === null) {
return newStyles;
}
Object.entries(styles).forEach((style) => {
const [key, value] = style;
if (key === 'backgroundImage') {
newStyles[key] = handleImageUrl(value as string);
return;
}
if (NEW_STYLES.includes(key)) {
const _value = parseStyleString(value as (string | number));
newStyles[key] = _value.value;
newStyles[`${key}Unit`] = _value.unit;
return;
}
newStyles[key] = value;
});
return newStyles;
}
// 将表单格式的样式格式化为css所接受样式,并移除 为空,为 0的值
export const formatStyles = (styles) => {
const newStyles = {};
if (typeof (styles) !== 'object' || styles === null) {
return newStyles;
}
Object.entries(styles).forEach((style) => {
const [key, value] = style;
if (value === '' || value === 0) return;
if (key.indexOf('Unit') >= 0) return;
if (key === 'backgroundImage') {
if (value === 'none') return;
newStyles[key] = `url(${value})`;
return;
}
if (NEW_STYLES.includes(key)) {
const _value = formatStyleString(value, (styles[`${key}Unit`] as string) || 'px');
newStyles[key] = _value;
return;
}
if (STYLE_NUMBER.includes(key)) {
newStyles[key] = Number(value) || 0;
return;
}
newStyles[key] = value;
});
return newStyles;
};
// 根据值解析得出 值以及单位
export /* Example usages of 'parseStyleString' are shown below:
parseStyleString(value as (string | number));
*/
function parseStyleString(value) {
const _value = {
value: '',
unit: 'px',
};
if (value === 0 || !value || !(['string', 'number'].includes(typeof (value)))) return _value;
if (typeof (value) === 'number') {
_value.value = value.toString();
_value.unit = 'px';
return _value;
}
// auto
if (value === 'auto') {
_value.value = 'auto';
_value.unit = 'auto';
return _value;
}
// px
if (value.indexOf('px') >= 0) {
const _site = value.indexOf('px');
_value.value = value.substring(0, _site);
return _value;
}
// %
if (value.indexOf('%') >= 0) {
const _site = value.indexOf('%');
_value.value = value.substring(0, _site);
_value.unit = '%';
return _value;
}
return _value;
}
export /* Example usages of 'formatStyleString' are shown below:
formatStyleString(value, (styles[`${key}Unit`] as string) || 'px');
*/
function formatStyleString(value, unitValue = 'px') {
const newValue = '';
if (value === 0 || !value) return '0' + unitValue;
if (value === 'auto') {
return 'auto';
}
if (unitValue === 'px' || unitValue === '%') {
return value.toString() + unitValue;
}
return newValue;
}
// todo: 单独处理边框样式
// function handleBorderStyle(): Record<string, string | number> {
// const newStyles = {};
// return newStyles;
// }
/* Example usages of 'handleImageUrl' are shown below:
newStyles[key] = handleImageUrl(value as string);
*/
function handleImageUrl(url) {
let _url = '';
if (url.indexOf('url') === 0) {
_url = url.substring(4, url.length - 1);
}
if (url === 'none') {
return _url;
}
return _url;
}
|
e2fa05881cd41c5c0c8f60afc63cab23165b1c3a | 3,044 | ts | TypeScript | src/utils/extractors/utils.ts | kqp6/copilot-clone | 2fa8ebd2966fbf204d7b047a237d7e1e8319839c | [
"MIT"
] | 1 | 2022-03-26T20:19:12.000Z | 2022-03-26T20:19:12.000Z | src/utils/extractors/utils.ts | kqp6/copilot-clone | 2fa8ebd2966fbf204d7b047a237d7e1e8319839c | [
"MIT"
] | null | null | null | src/utils/extractors/utils.ts | kqp6/copilot-clone | 2fa8ebd2966fbf204d7b047a237d7e1e8319839c | [
"MIT"
] | null | null | null | const keywords = ["def", "void", "int", "if", "else", "while", "return", "true", "false", "null", "this.", "print", "do", "", ""];
const high_confidence_keywords = ['#!/bin/bash', 'select *', 'select ?', 'select count', '* from', '? from', 'where',
'order by', 'group by', 'left join', 'right join', 'inner join', 'outer join', 'exec '];
const symbol_keywords = ["=>", "==", "!=", ">", "<", ">=", "<=", "&&", "||"];
const low_confidence_keywords = ['trace', 'error', 'exception', 'warn'];
// Check whether the input should be considered as code input or random text
export function isCodeValid(input: string): boolean {
input = input.toLowerCase();
const openAngle = input.split('<').length - 1;
const closedAngle = input.split('>').length - 1;
const openBrackets = input.split('[').length - 1;
const closedBrackets = input.split(']').length - 1;
const openCurly = input.split('{').length - 1;
const closedCurly = input.split('}').length - 1;
const openParen = input.split('(').length - 1;
const closedParen = input.split(')').length - 1;
const bracketTotal = openAngle + closedAngle + openBrackets + closedBrackets + openCurly + closedCurly + openParen + closedParen;
// calculate the inequality of brackets. the lower the number the more unequal
const inequality = -Math.abs(openAngle - closedAngle) -
Math.abs(openBrackets - closedBrackets) -
Math.abs(openCurly - closedCurly) -
Math.abs(openParen - closedParen);
const semicolons = input.split(';').length - 1;
const colons = input.split(':').length - 1;
const quotes = input.split('"').length - 1;
const singleQuotes = input.split("'").length - 1;
let keywordsFound = 0;
let highKeywordsFound = 0;
let lowKeywordsFound = 0;
let symbolsFound = 0;
// test keywords
input.split(' ').map(n => n.replace('\n', '')).filter(n => n != '').forEach(word => {
if (keywords.includes(word)) {
keywordsFound++;
}
});
high_confidence_keywords.forEach(word => {
if (input.includes(word)) {
highKeywordsFound++;
}
});
low_confidence_keywords.forEach(word => {
if (input.includes(word)) {
lowKeywordsFound++;
}
});
symbol_keywords.forEach(symbol => {
if (input.includes(symbol)) {
symbolsFound++;
}
});
let confidence = 0;
confidence += bracketTotal > 0 ? .5 : -.5;
confidence += input.length > 8 ? .5 : -.3;
confidence += (inequality < 0 ? inequality / 10 : bracketTotal == 0 ? 0 : .3 * bracketTotal) * (20 / input.length);
confidence += semicolons > 0 ? 1 : -.5;
confidence += colons > 0 ? .2 : -.2;
confidence += keywordsFound * .7;
confidence += 3 * highKeywordsFound;
confidence += -2 * lowKeywordsFound;
confidence += symbolsFound;
confidence += input.endsWith(';') ? .7 : 0;
confidence += quotes > 0 ? .5 : 0;
confidence += singleQuotes > 0 ? .5 : 0;
return confidence >= 1;
} | 39.025641 | 133 | 0.589028 | 63 | 7 | 0 | 7 | 23 | 0 | 0 | 0 | 2 | 0 | 0 | 10 | 855 | 0.016374 | 0.026901 | 0 | 0 | 0 | 0 | 0.054054 | 0.296193 | const keywords = ["def", "void", "int", "if", "else", "while", "return", "true", "false", "null", "this.", "print", "do", "", ""];
const high_confidence_keywords = ['#!/bin/bash', 'select *', 'select ?', 'select count', '* from', '? from', 'where',
'order by', 'group by', 'left join', 'right join', 'inner join', 'outer join', 'exec '];
const symbol_keywords = ["=>", "==", "!=", ">", "<", ">=", "<=", "&&", "||"];
const low_confidence_keywords = ['trace', 'error', 'exception', 'warn'];
// Check whether the input should be considered as code input or random text
export function isCodeValid(input) {
input = input.toLowerCase();
const openAngle = input.split('<').length - 1;
const closedAngle = input.split('>').length - 1;
const openBrackets = input.split('[').length - 1;
const closedBrackets = input.split(']').length - 1;
const openCurly = input.split('{').length - 1;
const closedCurly = input.split('}').length - 1;
const openParen = input.split('(').length - 1;
const closedParen = input.split(')').length - 1;
const bracketTotal = openAngle + closedAngle + openBrackets + closedBrackets + openCurly + closedCurly + openParen + closedParen;
// calculate the inequality of brackets. the lower the number the more unequal
const inequality = -Math.abs(openAngle - closedAngle) -
Math.abs(openBrackets - closedBrackets) -
Math.abs(openCurly - closedCurly) -
Math.abs(openParen - closedParen);
const semicolons = input.split(';').length - 1;
const colons = input.split(':').length - 1;
const quotes = input.split('"').length - 1;
const singleQuotes = input.split("'").length - 1;
let keywordsFound = 0;
let highKeywordsFound = 0;
let lowKeywordsFound = 0;
let symbolsFound = 0;
// test keywords
input.split(' ').map(n => n.replace('\n', '')).filter(n => n != '').forEach(word => {
if (keywords.includes(word)) {
keywordsFound++;
}
});
high_confidence_keywords.forEach(word => {
if (input.includes(word)) {
highKeywordsFound++;
}
});
low_confidence_keywords.forEach(word => {
if (input.includes(word)) {
lowKeywordsFound++;
}
});
symbol_keywords.forEach(symbol => {
if (input.includes(symbol)) {
symbolsFound++;
}
});
let confidence = 0;
confidence += bracketTotal > 0 ? .5 : -.5;
confidence += input.length > 8 ? .5 : -.3;
confidence += (inequality < 0 ? inequality / 10 : bracketTotal == 0 ? 0 : .3 * bracketTotal) * (20 / input.length);
confidence += semicolons > 0 ? 1 : -.5;
confidence += colons > 0 ? .2 : -.2;
confidence += keywordsFound * .7;
confidence += 3 * highKeywordsFound;
confidence += -2 * lowKeywordsFound;
confidence += symbolsFound;
confidence += input.endsWith(';') ? .7 : 0;
confidence += quotes > 0 ? .5 : 0;
confidence += singleQuotes > 0 ? .5 : 0;
return confidence >= 1;
} |
d016916c068c717b240224b9dfe56464202627ad | 22,233 | ts | TypeScript | src/turndown.ts | notable/html2markdown | 9b0f7e365d168cd28c36ce89e0f479eaa4b62462 | [
"MIT"
] | 1 | 2022-03-30T23:05:21.000Z | 2022-03-30T23:05:21.000Z | src/turndown.ts | notable/html2markdown | 9b0f7e365d168cd28c36ce89e0f479eaa4b62462 | [
"MIT"
] | null | null | null | src/turndown.ts | notable/html2markdown | 9b0f7e365d168cd28c36ce89e0f479eaa4b62462 | [
"MIT"
] | null | null | null |
// @ts-nocheck
function extend (destination) {
for (var i = 1; i < arguments.length; i++) {
var source = arguments[i];
for (var key in source) {
if (source.hasOwnProperty(key)) destination[key] = source[key];
}
}
return destination
}
function repeat (character, count) {
return Array(count + 1).join(character)
}
var blockElements = [
'address', 'article', 'aside', 'audio', 'blockquote', 'body', 'canvas',
'center', 'dd', 'dir', 'div', 'dl', 'dt', 'fieldset', 'figcaption',
'figure', 'footer', 'form', 'frameset', 'h1', 'h2', 'h3', 'h4', 'h5', 'h6',
'header', 'hgroup', 'hr', 'html', 'isindex', 'li', 'main', 'menu', 'nav',
'noframes', 'noscript', 'ol', 'output', 'p', 'pre', 'section', 'table',
'tbody', 'td', 'tfoot', 'th', 'thead', 'tr', 'ul'
];
function isBlock (node) {
return blockElements.indexOf(node.nodeName.toLowerCase()) !== -1
}
var voidElements = [
'area', 'base', 'br', 'col', 'command', 'embed', 'hr', 'img', 'input',
'keygen', 'link', 'meta', 'param', 'source', 'track', 'wbr'
];
function isVoid (node) {
return voidElements.indexOf(node.nodeName.toLowerCase()) !== -1
}
function hasVoid (node) {
return (
node.getElementsByTagName &&
voidElements.some(function (name) {
return node.getElementsByTagName(name).length
})
)
}
var rules = {};
rules.paragraph = {
filter: 'p',
replacement: function (content) {
return '\n\n' + content + '\n\n'
}
};
rules.lineBreak = {
filter: 'br',
replacement: function (content, node, options) {
return options.br + '\n'
}
};
rules.heading = {
filter: ['h1', 'h2', 'h3', 'h4', 'h5', 'h6'],
replacement: function (content, node, options) {
var hLevel = Number(node.nodeName.charAt(1));
if (options.headingStyle === 'setext' && hLevel < 3) {
var underline = repeat((hLevel === 1 ? '=' : '-'), content.length);
return (
'\n\n' + content + '\n' + underline + '\n\n'
)
} else {
return '\n\n' + repeat('#', hLevel) + ' ' + content + '\n\n'
}
}
};
rules.blockquote = {
filter: 'blockquote',
replacement: function (content) {
content = content.replace(/^\n+|\n+$/g, '');
content = content.replace(/^/gm, '> ');
return '\n\n' + content + '\n\n'
}
};
rules.list = {
filter: ['ul', 'ol'],
replacement: function (content, node) {
var parent = node.parentNode;
var siblingElements = parent.children;
var lastSiblingElement = siblingElements[siblingElements.length - 1];
if (parent.nodeName === 'LI' && node === lastSiblingElement) {
return '\n' + content
} else {
return '\n\n' + content + '\n\n'
}
}
};
rules.listItem = {
filter: 'li',
replacement: function (content, node, options) {
content = content
.replace(/^\n+/, '') // remove leading newlines
.replace(/\n+$/, '\n') // replace trailing newlines with just a single one
.replace(/\n/gm, '\n '); // indent
var prefix = options.bulletListMarker + ' ';
var parent = node.parentNode;
if (parent.nodeName === 'OL') {
var start = parent.getAttribute('start');
var index = Array.prototype.indexOf.call(parent.children, node);
prefix = (start ? Number(start) + index : index + 1) + '. ';
}
return (
prefix + content + (node.nextSibling && !/\n$/.test(content) ? '\n' : '')
)
}
};
rules.indentedCodeBlock = {
filter: function (node, options) {
return (
options.codeBlockStyle === 'indented' &&
node.nodeName === 'PRE' &&
node.firstChild &&
node.firstChild.nodeName === 'CODE'
)
},
replacement: function (content, node, options) {
return (
'\n\n ' +
node.firstChild.textContent.replace(/\n/g, '\n ') +
'\n\n'
)
}
};
rules.fencedCodeBlock = {
filter: function (node, options) {
return (
options.codeBlockStyle === 'fenced' &&
node.nodeName === 'PRE' &&
node.firstChild &&
node.firstChild.nodeName === 'CODE'
)
},
replacement: function (content, node, options) {
var className = node.firstChild.getAttribute('class') || '';
var language = (className.match(/language-(\S+)/) || [null, ''])[1];
return (
'\n\n' + options.fence + language + '\n' +
node.firstChild.textContent +
'\n' + options.fence + '\n\n'
)
}
};
rules.horizontalRule = {
filter: 'hr',
replacement: function (content, node, options) {
return '\n\n' + options.hr + '\n\n'
}
};
rules.inlineLink = {
filter: function (node, options) {
return (
options.linkStyle === 'inlined' &&
node.nodeName === 'A' &&
node.getAttribute('href')
)
},
replacement: function (content, node) {
var href = node.getAttribute('href');
var title = node.getAttribute('title') ? ' "' + node.getAttribute('title') + '"' : '';
return '[' + content + '](' + href + title + ')'
}
};
rules.referenceLink = {
filter: function (node, options) {
return (
options.linkStyle === 'referenced' &&
node.nodeName === 'A' &&
node.getAttribute('href')
)
},
replacement: function (content, node, options) {
var href = node.getAttribute('href');
var title = node.title ? ' "' + node.title + '"' : '';
var replacement;
var reference;
switch (options.linkReferenceStyle) {
case 'collapsed':
replacement = '[' + content + '][]';
reference = '[' + content + ']: ' + href + title;
break
case 'shortcut':
replacement = '[' + content + ']';
reference = '[' + content + ']: ' + href + title;
break
default:
var id = this.references.length + 1;
replacement = '[' + content + '][' + id + ']';
reference = '[' + id + ']: ' + href + title;
}
this.references.push(reference);
return replacement
},
references: [],
append: function (options) {
var references = '';
if (this.references.length) {
references = '\n\n' + this.references.join('\n') + '\n\n';
this.references = []; // Reset references
}
return references
}
};
rules.emphasis = {
filter: ['em', 'i'],
replacement: function (content, node, options) {
if (!content.trim()) return ''
return options.emDelimiter + content + options.emDelimiter
}
};
rules.strong = {
filter: ['strong', 'b'],
replacement: function (content, node, options) {
if (!content.trim()) return ''
return options.strongDelimiter + content + options.strongDelimiter
}
};
rules.code = {
filter: function (node) {
var hasSiblings = node.previousSibling || node.nextSibling;
var isCodeBlock = node.parentNode.nodeName === 'PRE' && !hasSiblings;
return node.nodeName === 'CODE' && !isCodeBlock
},
replacement: function (content) {
if (!content.trim()) return ''
var delimiter = '`';
var leadingSpace = '';
var trailingSpace = '';
var matches = content.match(/`+/gm);
if (matches) {
if (/^`/.test(content)) leadingSpace = ' ';
if (/`$/.test(content)) trailingSpace = ' ';
while (matches.indexOf(delimiter) !== -1) delimiter = delimiter + '`';
}
return delimiter + leadingSpace + content + trailingSpace + delimiter
}
};
rules.image = {
filter: 'img',
replacement: function (content, node) {
var alt = node.getAttribute('alt') || '';
var src = node.getAttribute('src') || '';
var title = node.getAttribute('title') || '';
var titlePart = title ? ' "' + title + '"' : '';
return src ? '![' + alt + ']' + '(' + src + titlePart + ')' : ''
}
};
/**
* Manages a collection of rules used to convert HTML to Markdown
*/
function Rules (options) {
this.options = options;
this._keep = [];
this._remove = [];
this.blankRule = {
replacement: options.blankReplacement
};
this.keepReplacement = options.keepReplacement;
this.defaultRule = {
replacement: options.defaultReplacement
};
this.array = [];
for (var key in options.rules) this.array.push(options.rules[key]);
}
Rules.prototype = {
add: function (key, rule) {
this.array.unshift(rule);
},
keep: function (filter) {
this._keep.unshift({
filter: filter,
replacement: this.keepReplacement
});
},
remove: function (filter) {
this._remove.unshift({
filter: filter,
replacement: function () {
return ''
}
});
},
forNode: function (node) {
if (node.isBlank) return this.blankRule
var rule;
if ((rule = findRule(this.array, node, this.options))) return rule
if ((rule = findRule(this._keep, node, this.options))) return rule
if ((rule = findRule(this._remove, node, this.options))) return rule
return this.defaultRule
},
forEach: function (fn) {
for (var i = 0; i < this.array.length; i++) fn(this.array[i], i);
}
};
function findRule (rules, node, options) {
for (var i = 0; i < rules.length; i++) {
var rule = rules[i];
if (filterValue(rule, node, options)) return rule
}
return void 0
}
function filterValue (rule, node, options) {
var filter = rule.filter;
if (typeof filter === 'string') {
if (filter === node.nodeName.toLowerCase()) return true
} else if (Array.isArray(filter)) {
if (filter.indexOf(node.nodeName.toLowerCase()) > -1) return true
} else if (typeof filter === 'function') {
if (filter.call(rule, node, options)) return true
} else {
throw new TypeError('`filter` needs to be a string, array, or function')
}
}
/**
* The collapseWhitespace function is adapted from collapse-whitespace
* by Luc Thevenard.
*
* The MIT License (MIT)
*
* Copyright (c) 2014 Luc Thevenard <lucthevenard@gmail.com>
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
/**
* collapseWhitespace(options) removes extraneous whitespace from an the given element.
*
* @param {Object} options
*/
function collapseWhitespace (options) {
var element = options.element;
var isBlock = options.isBlock;
var isVoid = options.isVoid;
var isPre = options.isPre || function (node) {
return node.nodeName === 'PRE'
};
if (!element.firstChild || isPre(element)) return
var prevText = null;
var prevVoid = false;
var prev = null;
var node = next(prev, element, isPre);
while (node !== element) {
if (node.nodeType === 3 || node.nodeType === 4) { // Node.TEXT_NODE or Node.CDATA_SECTION_NODE
var text = node.data.replace(/[ \r\n\t]+/g, ' ');
if ((!prevText || / $/.test(prevText.data)) &&
!prevVoid && text[0] === ' ') {
text = text.substr(1);
}
// `text` might be empty at this point.
if (!text) {
node = remove(node);
continue
}
node.data = text;
prevText = node;
} else if (node.nodeType === 1) { // Node.ELEMENT_NODE
if (isBlock(node) || node.nodeName === 'BR') {
if (prevText) {
prevText.data = prevText.data.replace(/ $/, '');
}
prevText = null;
prevVoid = false;
} else if (isVoid(node)) {
// Avoid trimming space around non-block, non-BR void elements.
prevText = null;
prevVoid = true;
}
} else {
node = remove(node);
continue
}
var nextNode = next(prev, node, isPre);
prev = node;
node = nextNode;
}
if (prevText) {
prevText.data = prevText.data.replace(/ $/, '');
if (!prevText.data) {
remove(prevText);
}
}
}
/**
* remove(node) removes the given node from the DOM and returns the
* next node in the sequence.
*
* @param {Node} node
* @return {Node} node
*/
function remove (node) {
var next = node.nextSibling || node.parentNode;
node.parentNode.removeChild(node);
return next
}
/**
* next(prev, current, isPre) returns the next node in the sequence, given the
* current and previous nodes.
*
* @param {Node} prev
* @param {Node} current
* @param {Function} isPre
* @return {Node}
*/
function next (prev, current, isPre) {
if ((prev && prev.parentNode === current) || isPre(current)) {
return current.nextSibling || current.parentNode
}
return current.firstChild || current.nextSibling || current.parentNode
}
/*
* Set up window for Node.js
*/
var root = (typeof window !== 'undefined' ? window : {});
/*
* Parsing HTML strings
*/
function RootNode (input, options) {
var root;
if (typeof input === 'string') {
var doc = htmlParser(options).parseFromString(
// DOM parsers arrange elements in the <head> and <body>.
// Wrapping in a custom element ensures elements are reliably arranged in
// a single element.
'<x-turndown id="turndown-root">' + input + '</x-turndown>',
'text/html'
);
root = doc.getElementsByTagName('x-turndown')[0];
} else {
root = input.cloneNode(true);
}
Array.from ( doc.querySelectorAll ( 'colgroup' ) ).forEach ( ele => ele.parentNode.removeChild ( ele ) ); // Deleting colgroups
collapseWhitespace({
element: root,
isBlock: isBlock,
isVoid: isVoid
});
return root
}
var _htmlParser;
function htmlParser (options) {
_htmlParser = _htmlParser || new options.parser();
return _htmlParser
}
function Node (node) {
node.isBlock = isBlock(node);
node.isCode = node.nodeName.toLowerCase() === 'code' || node.parentNode.isCode;
node.isBlank = isBlank(node);
node.flankingWhitespace = flankingWhitespace(node);
return node
}
function isBlank (node) {
return (
['A', 'TH', 'TD', 'IFRAME', 'SCRIPT', 'AUDIO', 'VIDEO'].indexOf(node.nodeName) === -1 &&
/^\s*$/i.test(node.textContent) &&
!isVoid(node) &&
!hasVoid(node)
)
}
function flankingWhitespace (node) {
var leading = '';
var trailing = '';
if (!node.isBlock) {
var hasLeading = /^[ \r\n\t]/.test(node.textContent);
var hasTrailing = /[ \r\n\t]$/.test(node.textContent);
if (hasLeading && !isFlankedByWhitespace('left', node)) {
leading = ' ';
}
if (hasTrailing && !isFlankedByWhitespace('right', node)) {
trailing = ' ';
}
}
return { leading: leading, trailing: trailing }
}
function isFlankedByWhitespace (side, node) {
var sibling;
var regExp;
var isFlanked;
if (side === 'left') {
sibling = node.previousSibling;
regExp = / $/;
} else {
sibling = node.nextSibling;
regExp = /^ /;
}
if (sibling) {
if (sibling.nodeType === 3) {
isFlanked = regExp.test(sibling.nodeValue);
} else if (sibling.nodeType === 1 && !isBlock(sibling)) {
isFlanked = regExp.test(sibling.textContent);
}
}
return isFlanked
}
var reduce = Array.prototype.reduce;
var leadingNewLinesRegExp = /^\n*/;
var trailingNewLinesRegExp = /\n*$/;
var escapes = [
[/\\/g, '\\\\'],
[/\*/g, '\\*'],
[/^-/g, '\\-'],
[/^\+ /g, '\\+ '],
[/^(=+)/g, '\\$1'],
[/^(#{1,6}) /g, '\\$1 '],
[/`/g, '\\`'],
[/^~~~/g, '\\~~~'],
[/\[/g, '\\['],
[/\]/g, '\\]'],
[/^>/g, '\\>'],
[/_/g, '\\_'],
[/^(\d+)\. /g, '$1\\. ']
];
function TurndownService (options) {
if (!(this instanceof TurndownService)) return new TurndownService(options)
var defaults = {
rules: rules,
headingStyle: 'atx',
hr: '---',
bulletListMarker: '-',
codeBlockStyle: 'fenced',
fence: '```',
emDelimiter: '_',
strongDelimiter: '**',
linkStyle: 'inlined',
linkReferenceStyle: 'full',
br: ' ',
blankReplacement: function (content, node) {
return node.isBlock ? '\n\n' : ''
},
keepReplacement: function (content, node) {
return node.isBlock ? '\n\n' + node.outerHTML + '\n\n' : node.outerHTML
},
defaultReplacement: function (content, node) {
return node.isBlock ? '\n\n' + content + '\n\n' : content
},
parser: root.DOMParser
};
this.options = extend({}, defaults, options);
this.rules = new Rules(this.options);
}
TurndownService.prototype = {
/**
* The entry point for converting a string or DOM node to Markdown
* @public
* @param {String|HTMLElement} input The string or DOM node to convert
* @returns A Markdown representation of the input
* @type String
*/
turndown: function (input) {
if (!canConvert(input)) {
throw new TypeError(
input + ' is not a string, or an element/document/fragment node.'
)
}
if (input === '') return ''
var output = process.call(this, new RootNode(input, this.options));
return postProcess.call(this, output)
},
/**
* Add one or more plugins
* @public
* @param {Function|Array} plugin The plugin or array of plugins to add
* @returns The Turndown instance for chaining
* @type Object
*/
use: function (plugin) {
if (Array.isArray(plugin)) {
for (var i = 0; i < plugin.length; i++) this.use(plugin[i]);
} else if (typeof plugin === 'function') {
plugin(this);
} else {
throw new TypeError('plugin must be a Function or an Array of Functions')
}
return this
},
/**
* Adds a rule
* @public
* @param {String} key The unique key of the rule
* @param {Object} rule The rule
* @returns The Turndown instance for chaining
* @type Object
*/
addRule: function (key, rule) {
this.rules.add(key, rule);
return this
},
/**
* Keep a node (as HTML) that matches the filter
* @public
* @param {String|Array|Function} filter The unique key of the rule
* @returns The Turndown instance for chaining
* @type Object
*/
keep: function (filter) {
this.rules.keep(filter);
return this
},
/**
* Remove a node that matches the filter
* @public
* @param {String|Array|Function} filter The unique key of the rule
* @returns The Turndown instance for chaining
* @type Object
*/
remove: function (filter) {
this.rules.remove(filter);
return this
},
/**
* Escapes Markdown syntax
* @public
* @param {String} string The string to escape
* @returns A string with Markdown syntax escaped
* @type String
*/
escape: function (string) {
return escapes.reduce(function (accumulator, escape) {
return accumulator.replace(escape[0], escape[1])
}, string)
}
};
/**
* Reduces a DOM node down to its Markdown string equivalent
* @private
* @param {HTMLElement} parentNode The node to convert
* @returns A Markdown representation of the node
* @type String
*/
function process (parentNode) {
var self = this;
return reduce.call(parentNode.childNodes, function (output, node) {
node = new Node(node);
var replacement = '';
if (node.nodeType === 3) {
replacement = node.isCode ? node.nodeValue : self.escape(node.nodeValue);
} else if (node.nodeType === 1) {
replacement = replacementForNode.call(self, node);
}
return join(output, replacement)
}, '')
}
/**
* Appends strings as each rule requires and trims the output
* @private
* @param {String} output The conversion output
* @returns A trimmed version of the ouput
* @type String
*/
function postProcess (output) {
var self = this;
this.rules.forEach(function (rule) {
if (typeof rule.append === 'function') {
output = join(output, rule.append(self.options));
}
});
return output.replace(/^[\t\r\n]+/, '').replace(/[\t\r\n\s]+$/, '')
}
/**
* Converts an element node to its Markdown equivalent
* @private
* @param {HTMLElement} node The node to convert
* @returns A Markdown representation of the node
* @type String
*/
function replacementForNode (node) {
var rule = this.rules.forNode(node);
var content = process.call(this, node);
var whitespace = node.flankingWhitespace;
if (whitespace.leading || whitespace.trailing) content = content.trim();
return (
whitespace.leading +
rule.replacement(content, node, this.options) +
whitespace.trailing
)
}
/**
* Determines the new lines between the current output and the replacement
* @private
* @param {String} output The current conversion output
* @param {String} replacement The string to append to the output
* @returns The whitespace to separate the current output and the replacement
* @type String
*/
function separatingNewlines (output, replacement) {
var newlines = [
output.match(trailingNewLinesRegExp)[0],
replacement.match(leadingNewLinesRegExp)[0]
].sort();
var maxNewlines = newlines[newlines.length - 1];
return maxNewlines.length < 2 ? maxNewlines : '\n\n'
}
function join (string1, string2) {
var separator = separatingNewlines(string1, string2);
// Remove trailing/leading newlines and replace with separator
string1 = string1.replace(trailingNewLinesRegExp, '');
string2 = string2.replace(leadingNewLinesRegExp, '');
return string1 + separator + string2
}
/**
* Determines whether an input can be converted
* @private
* @param {String|HTMLElement} input Describe this parameter
* @returns Describe what it returns
* @type String|Object|Array|Boolean|Number
*/
function canConvert (input) {
return (
input != null && (
typeof input === 'string' ||
(input.nodeType && (
input.nodeType === 1 || input.nodeType === 9 || input.nodeType === 11
))
)
)
}
export default TurndownService;
| 25.792343 | 129 | 0.610039 | 588 | 66 | 0 | 108 | 77 | 0 | 17 | 0 | 0 | 0 | 8 | 6.30303 | 6,211 | 0.028015 | 0.012397 | 0 | 0 | 0.001288 | 0 | 0 | 0.280252 |
// @ts-nocheck
/* Example usages of 'extend' are shown below:
this.options = extend({}, defaults, options);
*/
function extend (destination) {
for (var i = 1; i < arguments.length; i++) {
var source = arguments[i];
for (var key in source) {
if (source.hasOwnProperty(key)) destination[key] = source[key];
}
}
return destination
}
/* Example usages of 'repeat' are shown below:
repeat((hLevel === 1 ? '=' : '-'), content.length);
'\n\n' + repeat('#', hLevel) + ' ' + content + '\n\n';
*/
function repeat (character, count) {
return Array(count + 1).join(character)
}
var blockElements = [
'address', 'article', 'aside', 'audio', 'blockquote', 'body', 'canvas',
'center', 'dd', 'dir', 'div', 'dl', 'dt', 'fieldset', 'figcaption',
'figure', 'footer', 'form', 'frameset', 'h1', 'h2', 'h3', 'h4', 'h5', 'h6',
'header', 'hgroup', 'hr', 'html', 'isindex', 'li', 'main', 'menu', 'nav',
'noframes', 'noscript', 'ol', 'output', 'p', 'pre', 'section', 'table',
'tbody', 'td', 'tfoot', 'th', 'thead', 'tr', 'ul'
];
/* Example usages of 'isBlock' are shown below:
var isBlock = options.isBlock;
options.isBlock;
isBlock(node) || node.nodeName === 'BR';
;
node.isBlock = isBlock(node);
!node.isBlock;
sibling.nodeType === 1 && !isBlock(sibling);
node.isBlock ? '\n\n' : '';
node.isBlock ? '\n\n' + node.outerHTML + '\n\n' : node.outerHTML;
node.isBlock ? '\n\n' + content + '\n\n' : content;
*/
function isBlock (node) {
return blockElements.indexOf(node.nodeName.toLowerCase()) !== -1
}
var voidElements = [
'area', 'base', 'br', 'col', 'command', 'embed', 'hr', 'img', 'input',
'keygen', 'link', 'meta', 'param', 'source', 'track', 'wbr'
];
/* Example usages of 'isVoid' are shown below:
var isVoid = options.isVoid;
options.isVoid;
isVoid(node);
;
['A', 'TH', 'TD', 'IFRAME', 'SCRIPT', 'AUDIO', 'VIDEO'].indexOf(node.nodeName) === -1 &&
/^\s*$/i.test(node.textContent) &&
!isVoid(node) &&
!hasVoid(node);
*/
function isVoid (node) {
return voidElements.indexOf(node.nodeName.toLowerCase()) !== -1
}
/* Example usages of 'hasVoid' are shown below:
['A', 'TH', 'TD', 'IFRAME', 'SCRIPT', 'AUDIO', 'VIDEO'].indexOf(node.nodeName) === -1 &&
/^\s*$/i.test(node.textContent) &&
!isVoid(node) &&
!hasVoid(node);
*/
function hasVoid (node) {
return (
node.getElementsByTagName &&
voidElements.some(function (name) {
return node.getElementsByTagName(name).length
})
)
}
var rules = {};
rules.paragraph = {
filter: 'p',
replacement: function (content) {
return '\n\n' + content + '\n\n'
}
};
rules.lineBreak = {
filter: 'br',
replacement: function (content, node, options) {
return options.br + '\n'
}
};
rules.heading = {
filter: ['h1', 'h2', 'h3', 'h4', 'h5', 'h6'],
replacement: function (content, node, options) {
var hLevel = Number(node.nodeName.charAt(1));
if (options.headingStyle === 'setext' && hLevel < 3) {
var underline = repeat((hLevel === 1 ? '=' : '-'), content.length);
return (
'\n\n' + content + '\n' + underline + '\n\n'
)
} else {
return '\n\n' + repeat('#', hLevel) + ' ' + content + '\n\n'
}
}
};
rules.blockquote = {
filter: 'blockquote',
replacement: function (content) {
content = content.replace(/^\n+|\n+$/g, '');
content = content.replace(/^/gm, '> ');
return '\n\n' + content + '\n\n'
}
};
rules.list = {
filter: ['ul', 'ol'],
replacement: function (content, node) {
var parent = node.parentNode;
var siblingElements = parent.children;
var lastSiblingElement = siblingElements[siblingElements.length - 1];
if (parent.nodeName === 'LI' && node === lastSiblingElement) {
return '\n' + content
} else {
return '\n\n' + content + '\n\n'
}
}
};
rules.listItem = {
filter: 'li',
replacement: function (content, node, options) {
content = content
.replace(/^\n+/, '') // remove leading newlines
.replace(/\n+$/, '\n') // replace trailing newlines with just a single one
.replace(/\n/gm, '\n '); // indent
var prefix = options.bulletListMarker + ' ';
var parent = node.parentNode;
if (parent.nodeName === 'OL') {
var start = parent.getAttribute('start');
var index = Array.prototype.indexOf.call(parent.children, node);
prefix = (start ? Number(start) + index : index + 1) + '. ';
}
return (
prefix + content + (node.nextSibling && !/\n$/.test(content) ? '\n' : '')
)
}
};
rules.indentedCodeBlock = {
filter: function (node, options) {
return (
options.codeBlockStyle === 'indented' &&
node.nodeName === 'PRE' &&
node.firstChild &&
node.firstChild.nodeName === 'CODE'
)
},
replacement: function (content, node, options) {
return (
'\n\n ' +
node.firstChild.textContent.replace(/\n/g, '\n ') +
'\n\n'
)
}
};
rules.fencedCodeBlock = {
filter: function (node, options) {
return (
options.codeBlockStyle === 'fenced' &&
node.nodeName === 'PRE' &&
node.firstChild &&
node.firstChild.nodeName === 'CODE'
)
},
replacement: function (content, node, options) {
var className = node.firstChild.getAttribute('class') || '';
var language = (className.match(/language-(\S+)/) || [null, ''])[1];
return (
'\n\n' + options.fence + language + '\n' +
node.firstChild.textContent +
'\n' + options.fence + '\n\n'
)
}
};
rules.horizontalRule = {
filter: 'hr',
replacement: function (content, node, options) {
return '\n\n' + options.hr + '\n\n'
}
};
rules.inlineLink = {
filter: function (node, options) {
return (
options.linkStyle === 'inlined' &&
node.nodeName === 'A' &&
node.getAttribute('href')
)
},
replacement: function (content, node) {
var href = node.getAttribute('href');
var title = node.getAttribute('title') ? ' "' + node.getAttribute('title') + '"' : '';
return '[' + content + '](' + href + title + ')'
}
};
rules.referenceLink = {
filter: function (node, options) {
return (
options.linkStyle === 'referenced' &&
node.nodeName === 'A' &&
node.getAttribute('href')
)
},
replacement: function (content, node, options) {
var href = node.getAttribute('href');
var title = node.title ? ' "' + node.title + '"' : '';
var replacement;
var reference;
switch (options.linkReferenceStyle) {
case 'collapsed':
replacement = '[' + content + '][]';
reference = '[' + content + ']: ' + href + title;
break
case 'shortcut':
replacement = '[' + content + ']';
reference = '[' + content + ']: ' + href + title;
break
default:
var id = this.references.length + 1;
replacement = '[' + content + '][' + id + ']';
reference = '[' + id + ']: ' + href + title;
}
this.references.push(reference);
return replacement
},
references: [],
append: function (options) {
var references = '';
if (this.references.length) {
references = '\n\n' + this.references.join('\n') + '\n\n';
this.references = []; // Reset references
}
return references
}
};
rules.emphasis = {
filter: ['em', 'i'],
replacement: function (content, node, options) {
if (!content.trim()) return ''
return options.emDelimiter + content + options.emDelimiter
}
};
rules.strong = {
filter: ['strong', 'b'],
replacement: function (content, node, options) {
if (!content.trim()) return ''
return options.strongDelimiter + content + options.strongDelimiter
}
};
rules.code = {
filter: function (node) {
var hasSiblings = node.previousSibling || node.nextSibling;
var isCodeBlock = node.parentNode.nodeName === 'PRE' && !hasSiblings;
return node.nodeName === 'CODE' && !isCodeBlock
},
replacement: function (content) {
if (!content.trim()) return ''
var delimiter = '`';
var leadingSpace = '';
var trailingSpace = '';
var matches = content.match(/`+/gm);
if (matches) {
if (/^`/.test(content)) leadingSpace = ' ';
if (/`$/.test(content)) trailingSpace = ' ';
while (matches.indexOf(delimiter) !== -1) delimiter = delimiter + '`';
}
return delimiter + leadingSpace + content + trailingSpace + delimiter
}
};
rules.image = {
filter: 'img',
replacement: function (content, node) {
var alt = node.getAttribute('alt') || '';
var src = node.getAttribute('src') || '';
var title = node.getAttribute('title') || '';
var titlePart = title ? ' "' + title + '"' : '';
return src ? '![' + alt + ']' + '(' + src + titlePart + ')' : ''
}
};
/**
* Manages a collection of rules used to convert HTML to Markdown
*/
/* Example usages of 'Rules' are shown below:
Rules.prototype = {
add: function (key, rule) {
this.array.unshift(rule);
},
keep: function (filter) {
this._keep.unshift({
filter: filter,
replacement: this.keepReplacement
});
},
remove: function (filter) {
this._remove.unshift({
filter: filter,
replacement: function () {
return '';
}
});
},
forNode: function (node) {
if (node.isBlank)
return this.blankRule;
var rule;
if ((rule = findRule(this.array, node, this.options)))
return rule;
if ((rule = findRule(this._keep, node, this.options)))
return rule;
if ((rule = findRule(this._remove, node, this.options)))
return rule;
return this.defaultRule;
},
forEach: function (fn) {
for (var i = 0; i < this.array.length; i++)
fn(this.array[i], i);
}
};
this.rules = new Rules(this.options);
*/
function Rules (options) {
this.options = options;
this._keep = [];
this._remove = [];
this.blankRule = {
replacement: options.blankReplacement
};
this.keepReplacement = options.keepReplacement;
this.defaultRule = {
replacement: options.defaultReplacement
};
this.array = [];
for (var key in options.rules) this.array.push(options.rules[key]);
}
Rules.prototype = {
add: function (key, rule) {
this.array.unshift(rule);
},
keep: function (filter) {
this._keep.unshift({
filter: filter,
replacement: this.keepReplacement
});
},
remove: function (filter) {
this._remove.unshift({
filter: filter,
replacement: function () {
return ''
}
});
},
forNode: function (node) {
if (node.isBlank) return this.blankRule
var rule;
if ((rule = findRule(this.array, node, this.options))) return rule
if ((rule = findRule(this._keep, node, this.options))) return rule
if ((rule = findRule(this._remove, node, this.options))) return rule
return this.defaultRule
},
forEach: function (fn) {
for (var i = 0; i < this.array.length; i++) fn(this.array[i], i);
}
};
/* Example usages of 'findRule' are shown below:
rule = findRule(this.array, node, this.options);
rule = findRule(this._keep, node, this.options);
rule = findRule(this._remove, node, this.options);
*/
function findRule (rules, node, options) {
for (var i = 0; i < rules.length; i++) {
var rule = rules[i];
if (filterValue(rule, node, options)) return rule
}
return void 0
}
/* Example usages of 'filterValue' are shown below:
filterValue(rule, node, options);
*/
function filterValue (rule, node, options) {
var filter = rule.filter;
if (typeof filter === 'string') {
if (filter === node.nodeName.toLowerCase()) return true
} else if (Array.isArray(filter)) {
if (filter.indexOf(node.nodeName.toLowerCase()) > -1) return true
} else if (typeof filter === 'function') {
if (filter.call(rule, node, options)) return true
} else {
throw new TypeError('`filter` needs to be a string, array, or function')
}
}
/**
* The collapseWhitespace function is adapted from collapse-whitespace
* by Luc Thevenard.
*
* The MIT License (MIT)
*
* Copyright (c) 2014 Luc Thevenard <lucthevenard@gmail.com>
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
/**
* collapseWhitespace(options) removes extraneous whitespace from an the given element.
*
* @param {Object} options
*/
/* Example usages of 'collapseWhitespace' are shown below:
collapseWhitespace({
element: root,
isBlock: isBlock,
isVoid: isVoid
});
*/
function collapseWhitespace (options) {
var element = options.element;
var isBlock = options.isBlock;
var isVoid = options.isVoid;
var isPre = options.isPre || function (node) {
return node.nodeName === 'PRE'
};
if (!element.firstChild || isPre(element)) return
var prevText = null;
var prevVoid = false;
var prev = null;
var node = next(prev, element, isPre);
while (node !== element) {
if (node.nodeType === 3 || node.nodeType === 4) { // Node.TEXT_NODE or Node.CDATA_SECTION_NODE
var text = node.data.replace(/[ \r\n\t]+/g, ' ');
if ((!prevText || / $/.test(prevText.data)) &&
!prevVoid && text[0] === ' ') {
text = text.substr(1);
}
// `text` might be empty at this point.
if (!text) {
node = remove(node);
continue
}
node.data = text;
prevText = node;
} else if (node.nodeType === 1) { // Node.ELEMENT_NODE
if (isBlock(node) || node.nodeName === 'BR') {
if (prevText) {
prevText.data = prevText.data.replace(/ $/, '');
}
prevText = null;
prevVoid = false;
} else if (isVoid(node)) {
// Avoid trimming space around non-block, non-BR void elements.
prevText = null;
prevVoid = true;
}
} else {
node = remove(node);
continue
}
var nextNode = next(prev, node, isPre);
prev = node;
node = nextNode;
}
if (prevText) {
prevText.data = prevText.data.replace(/ $/, '');
if (!prevText.data) {
remove(prevText);
}
}
}
/**
* remove(node) removes the given node from the DOM and returns the
* next node in the sequence.
*
* @param {Node} node
* @return {Node} node
*/
/* Example usages of 'remove' are shown below:
;
node = remove(node);
remove(prevText);
*
* Remove a node that matches the filter
* @public
* @param {String|Array|Function} filter The unique key of the rule
* @returns The Turndown instance for chaining
* @type Object
;
this.rules.remove(filter);
*/
function remove (node) {
var next = node.nextSibling || node.parentNode;
node.parentNode.removeChild(node);
return next
}
/**
* next(prev, current, isPre) returns the next node in the sequence, given the
* current and previous nodes.
*
* @param {Node} prev
* @param {Node} current
* @param {Function} isPre
* @return {Node}
*/
/* Example usages of 'next' are shown below:
next(prev, element, isPre);
next(prev, node, isPre);
var next = node.nextSibling || node.parentNode;
return next;
*/
function next (prev, current, isPre) {
if ((prev && prev.parentNode === current) || isPre(current)) {
return current.nextSibling || current.parentNode
}
return current.firstChild || current.nextSibling || current.parentNode
}
/*
* Set up window for Node.js
*/
var root = (typeof window !== 'undefined' ? window : {});
/*
* Parsing HTML strings
*/
/* Example usages of 'RootNode' are shown below:
process.call(this, new RootNode(input, this.options));
*/
function RootNode (input, options) {
var root;
if (typeof input === 'string') {
var doc = htmlParser(options).parseFromString(
// DOM parsers arrange elements in the <head> and <body>.
// Wrapping in a custom element ensures elements are reliably arranged in
// a single element.
'<x-turndown id="turndown-root">' + input + '</x-turndown>',
'text/html'
);
root = doc.getElementsByTagName('x-turndown')[0];
} else {
root = input.cloneNode(true);
}
Array.from ( doc.querySelectorAll ( 'colgroup' ) ).forEach ( ele => ele.parentNode.removeChild ( ele ) ); // Deleting colgroups
collapseWhitespace({
element: root,
isBlock: isBlock,
isVoid: isVoid
});
return root
}
var _htmlParser;
/* Example usages of 'htmlParser' are shown below:
htmlParser(options).parseFromString(
// DOM parsers arrange elements in the <head> and <body>.
// Wrapping in a custom element ensures elements are reliably arranged in
// a single element.
'<x-turndown id="turndown-root">' + input + '</x-turndown>', 'text/html');
*/
function htmlParser (options) {
_htmlParser = _htmlParser || new options.parser();
return _htmlParser
}
/* Example usages of 'Node' are shown below:
node = new Node(node);
*/
function Node (node) {
node.isBlock = isBlock(node);
node.isCode = node.nodeName.toLowerCase() === 'code' || node.parentNode.isCode;
node.isBlank = isBlank(node);
node.flankingWhitespace = flankingWhitespace(node);
return node
}
/* Example usages of 'isBlank' are shown below:
node.isBlank;
node.isBlank = isBlank(node);
*/
function isBlank (node) {
return (
['A', 'TH', 'TD', 'IFRAME', 'SCRIPT', 'AUDIO', 'VIDEO'].indexOf(node.nodeName) === -1 &&
/^\s*$/i.test(node.textContent) &&
!isVoid(node) &&
!hasVoid(node)
)
}
/* Example usages of 'flankingWhitespace' are shown below:
node.flankingWhitespace = flankingWhitespace(node);
node.flankingWhitespace;
*/
function flankingWhitespace (node) {
var leading = '';
var trailing = '';
if (!node.isBlock) {
var hasLeading = /^[ \r\n\t]/.test(node.textContent);
var hasTrailing = /[ \r\n\t]$/.test(node.textContent);
if (hasLeading && !isFlankedByWhitespace('left', node)) {
leading = ' ';
}
if (hasTrailing && !isFlankedByWhitespace('right', node)) {
trailing = ' ';
}
}
return { leading: leading, trailing: trailing }
}
/* Example usages of 'isFlankedByWhitespace' are shown below:
hasLeading && !isFlankedByWhitespace('left', node);
hasTrailing && !isFlankedByWhitespace('right', node);
*/
function isFlankedByWhitespace (side, node) {
var sibling;
var regExp;
var isFlanked;
if (side === 'left') {
sibling = node.previousSibling;
regExp = / $/;
} else {
sibling = node.nextSibling;
regExp = /^ /;
}
if (sibling) {
if (sibling.nodeType === 3) {
isFlanked = regExp.test(sibling.nodeValue);
} else if (sibling.nodeType === 1 && !isBlock(sibling)) {
isFlanked = regExp.test(sibling.textContent);
}
}
return isFlanked
}
var reduce = Array.prototype.reduce;
var leadingNewLinesRegExp = /^\n*/;
var trailingNewLinesRegExp = /\n*$/;
var escapes = [
[/\\/g, '\\\\'],
[/\*/g, '\\*'],
[/^-/g, '\\-'],
[/^\+ /g, '\\+ '],
[/^(=+)/g, '\\$1'],
[/^(#{1,6}) /g, '\\$1 '],
[/`/g, '\\`'],
[/^~~~/g, '\\~~~'],
[/\[/g, '\\['],
[/\]/g, '\\]'],
[/^>/g, '\\>'],
[/_/g, '\\_'],
[/^(\d+)\. /g, '$1\\. ']
];
/* Example usages of 'TurndownService' are shown below:
this instanceof TurndownService;
new TurndownService(options);
TurndownService.prototype = {
*
* The entry point for converting a string or DOM node to Markdown
* @public
* @param {String|HTMLElement} input The string or DOM node to convert
* @returns A Markdown representation of the input
* @type String
turndown: function (input) {
if (!canConvert(input)) {
throw new TypeError(input + ' is not a string, or an element/document/fragment node.');
}
if (input === '')
return '';
var output = process.call(this, new RootNode(input, this.options));
return postProcess.call(this, output);
},
*
* Add one or more plugins
* @public
* @param {Function|Array} plugin The plugin or array of plugins to add
* @returns The Turndown instance for chaining
* @type Object
use: function (plugin) {
if (Array.isArray(plugin)) {
for (var i = 0; i < plugin.length; i++)
this.use(plugin[i]);
}
else if (typeof plugin === 'function') {
plugin(this);
}
else {
throw new TypeError('plugin must be a Function or an Array of Functions');
}
return this;
},
*
* Adds a rule
* @public
* @param {String} key The unique key of the rule
* @param {Object} rule The rule
* @returns The Turndown instance for chaining
* @type Object
addRule: function (key, rule) {
this.rules.add(key, rule);
return this;
},
*
* Keep a node (as HTML) that matches the filter
* @public
* @param {String|Array|Function} filter The unique key of the rule
* @returns The Turndown instance for chaining
* @type Object
keep: function (filter) {
this.rules.keep(filter);
return this;
},
*
* Remove a node that matches the filter
* @public
* @param {String|Array|Function} filter The unique key of the rule
* @returns The Turndown instance for chaining
* @type Object
remove: function (filter) {
this.rules.remove(filter);
return this;
},
*
* Escapes Markdown syntax
* @public
* @param {String} string The string to escape
* @returns A string with Markdown syntax escaped
* @type String
escape: function (string) {
return escapes.reduce(function (accumulator, escape) {
return accumulator.replace(escape[0], escape[1]);
}, string);
}
};
;
*/
function TurndownService (options) {
if (!(this instanceof TurndownService)) return new TurndownService(options)
var defaults = {
rules: rules,
headingStyle: 'atx',
hr: '---',
bulletListMarker: '-',
codeBlockStyle: 'fenced',
fence: '```',
emDelimiter: '_',
strongDelimiter: '**',
linkStyle: 'inlined',
linkReferenceStyle: 'full',
br: ' ',
blankReplacement: function (content, node) {
return node.isBlock ? '\n\n' : ''
},
keepReplacement: function (content, node) {
return node.isBlock ? '\n\n' + node.outerHTML + '\n\n' : node.outerHTML
},
defaultReplacement: function (content, node) {
return node.isBlock ? '\n\n' + content + '\n\n' : content
},
parser: root.DOMParser
};
this.options = extend({}, defaults, options);
this.rules = new Rules(this.options);
}
TurndownService.prototype = {
/**
* The entry point for converting a string or DOM node to Markdown
* @public
* @param {String|HTMLElement} input The string or DOM node to convert
* @returns A Markdown representation of the input
* @type String
*/
turndown: function (input) {
if (!canConvert(input)) {
throw new TypeError(
input + ' is not a string, or an element/document/fragment node.'
)
}
if (input === '') return ''
var output = process.call(this, new RootNode(input, this.options));
return postProcess.call(this, output)
},
/**
* Add one or more plugins
* @public
* @param {Function|Array} plugin The plugin or array of plugins to add
* @returns The Turndown instance for chaining
* @type Object
*/
use: function (plugin) {
if (Array.isArray(plugin)) {
for (var i = 0; i < plugin.length; i++) this.use(plugin[i]);
} else if (typeof plugin === 'function') {
plugin(this);
} else {
throw new TypeError('plugin must be a Function or an Array of Functions')
}
return this
},
/**
* Adds a rule
* @public
* @param {String} key The unique key of the rule
* @param {Object} rule The rule
* @returns The Turndown instance for chaining
* @type Object
*/
addRule: function (key, rule) {
this.rules.add(key, rule);
return this
},
/**
* Keep a node (as HTML) that matches the filter
* @public
* @param {String|Array|Function} filter The unique key of the rule
* @returns The Turndown instance for chaining
* @type Object
*/
keep: function (filter) {
this.rules.keep(filter);
return this
},
/**
* Remove a node that matches the filter
* @public
* @param {String|Array|Function} filter The unique key of the rule
* @returns The Turndown instance for chaining
* @type Object
*/
remove: function (filter) {
this.rules.remove(filter);
return this
},
/**
* Escapes Markdown syntax
* @public
* @param {String} string The string to escape
* @returns A string with Markdown syntax escaped
* @type String
*/
escape: function (string) {
return escapes.reduce(function (accumulator, escape) {
return accumulator.replace(escape[0], escape[1])
}, string)
}
};
/**
* Reduces a DOM node down to its Markdown string equivalent
* @private
* @param {HTMLElement} parentNode The node to convert
* @returns A Markdown representation of the node
* @type String
*/
/* Example usages of 'process' are shown below:
process.call(this, new RootNode(input, this.options));
process.call(this, node);
*/
function process (parentNode) {
var self = this;
return reduce.call(parentNode.childNodes, function (output, node) {
node = new Node(node);
var replacement = '';
if (node.nodeType === 3) {
replacement = node.isCode ? node.nodeValue : self.escape(node.nodeValue);
} else if (node.nodeType === 1) {
replacement = replacementForNode.call(self, node);
}
return join(output, replacement)
}, '')
}
/**
* Appends strings as each rule requires and trims the output
* @private
* @param {String} output The conversion output
* @returns A trimmed version of the ouput
* @type String
*/
/* Example usages of 'postProcess' are shown below:
postProcess.call(this, output);
*/
function postProcess (output) {
var self = this;
this.rules.forEach(function (rule) {
if (typeof rule.append === 'function') {
output = join(output, rule.append(self.options));
}
});
return output.replace(/^[\t\r\n]+/, '').replace(/[\t\r\n\s]+$/, '')
}
/**
* Converts an element node to its Markdown equivalent
* @private
* @param {HTMLElement} node The node to convert
* @returns A Markdown representation of the node
* @type String
*/
/* Example usages of 'replacementForNode' are shown below:
replacement = replacementForNode.call(self, node);
*/
function replacementForNode (node) {
var rule = this.rules.forNode(node);
var content = process.call(this, node);
var whitespace = node.flankingWhitespace;
if (whitespace.leading || whitespace.trailing) content = content.trim();
return (
whitespace.leading +
rule.replacement(content, node, this.options) +
whitespace.trailing
)
}
/**
* Determines the new lines between the current output and the replacement
* @private
* @param {String} output The current conversion output
* @param {String} replacement The string to append to the output
* @returns The whitespace to separate the current output and the replacement
* @type String
*/
/* Example usages of 'separatingNewlines' are shown below:
separatingNewlines(string1, string2);
*/
function separatingNewlines (output, replacement) {
var newlines = [
output.match(trailingNewLinesRegExp)[0],
replacement.match(leadingNewLinesRegExp)[0]
].sort();
var maxNewlines = newlines[newlines.length - 1];
return maxNewlines.length < 2 ? maxNewlines : '\n\n'
}
/* Example usages of 'join' are shown below:
Array(count + 1).join(character);
references = '\n\n' + this.references.join('\n') + '\n\n';
join(output, replacement);
output = join(output, rule.append(self.options));
*/
function join (string1, string2) {
var separator = separatingNewlines(string1, string2);
// Remove trailing/leading newlines and replace with separator
string1 = string1.replace(trailingNewLinesRegExp, '');
string2 = string2.replace(leadingNewLinesRegExp, '');
return string1 + separator + string2
}
/**
* Determines whether an input can be converted
* @private
* @param {String|HTMLElement} input Describe this parameter
* @returns Describe what it returns
* @type String|Object|Array|Boolean|Number
*/
/* Example usages of 'canConvert' are shown below:
!canConvert(input);
*/
function canConvert (input) {
return (
input != null && (
typeof input === 'string' ||
(input.nodeType && (
input.nodeType === 1 || input.nodeType === 9 || input.nodeType === 11
))
)
)
}
export default TurndownService;
|
d07cdfa01eb1df4008718757bde2f642636113c1 | 3,164 | ts | TypeScript | solutions/day04.ts | GiyoMoon/aoc2021 | 83d7e9018ed3b628353bc9a0a37b70a1462ecd74 | [
"Unlicense"
] | null | null | null | solutions/day04.ts | GiyoMoon/aoc2021 | 83d7e9018ed3b628353bc9a0a37b70a1462ecd74 | [
"Unlicense"
] | 1 | 2022-02-03T11:04:17.000Z | 2022-02-03T11:04:17.000Z | solutions/day04.ts | GiyoMoon/aoc2021 | 83d7e9018ed3b628353bc9a0a37b70a1462ecd74 | [
"Unlicense"
] | null | null | null | export default class Day4 {
private _boards: number[][][];
private _highlightedNumbers: number[];
private _numbersInPool: number[];
private _drawnNumbers: number[];
public solve(input: string): { part1: any, part2: any; } {
this._drawnNumbers = input.split('\n')[0].split(',').map(n => parseInt(n));
this._boards = input.split('\n\n').slice(1).map(boardString => {
const board: number[][] = [];
boardString.split('\n').forEach((line) => {
board.push(line.match(/.{1,3}/g).map(n => parseInt(n.trim())));
});
return board;
});
// part 1
let winningBoard: number[][];
let numbersDrawn = 5;
while (!winningBoard) {
this._numbersInPool = this._drawnNumbers.slice(0, numbersDrawn);
winningBoard = this._boards.find(wb => this._checkForWinner(wb));
numbersDrawn++;
}
let multiplyBy = this._highlightedNumbers[this._highlightedNumbers.length - 1];
let totalOfNotHighlighted = 0;
winningBoard.forEach(row => {
row.forEach(number => {
if (!this._numbersInPool.includes(number)) {
totalOfNotHighlighted += number;
}
});
});
const part1Solution = totalOfNotHighlighted * multiplyBy;
// part 2
numbersDrawn = 5;
const winningBoards: number[][][] = [];
let editingBoards = [...this._boards];
while (winningBoards.length < this._boards.length) {
this._numbersInPool = this._drawnNumbers.slice(0, numbersDrawn);
winningBoards.push(...editingBoards.filter(wb => this._checkForWinner(wb)));
editingBoards = editingBoards.filter(b => !winningBoards.includes(b));
numbersDrawn++;
}
const lastBoard = winningBoards[winningBoards.length - 1];
multiplyBy = this._highlightedNumbers[this._highlightedNumbers.length - 1];
totalOfNotHighlighted = 0;
lastBoard.forEach(row => {
row.forEach(number => {
if (!this._numbersInPool.includes(number)) {
totalOfNotHighlighted += number;
}
});
});
const part2Solution = totalOfNotHighlighted * multiplyBy;
return { part1: part1Solution, part2: part2Solution };
}
private _checkForWinner(board: number[][]) {
let found = false;
// check rows
board.forEach(row => {
let bingo = true;
if (!found) {
this._highlightedNumbers = [];
row.forEach(number => {
this._highlightedNumbers.push(number);
if (!this._numbersInPool.includes(number)) {
bingo = false;
}
});
if (bingo) {
found = true;
}
}
});
// check columns
for (let x = 0; x < 5; x++) {
let bingo = true;
if (!found) {
this._highlightedNumbers = [];
board.forEach(row => {
this._highlightedNumbers.push(row[x]);
if (!this._numbersInPool.includes(row[x])) {
bingo = false;
}
});
if (bingo) {
found = true;
}
}
}
if (found) {
this._highlightedNumbers = this._numbersInPool.filter(n => this._highlightedNumbers.includes(n));
}
return found;
};
}
| 27.513043 | 103 | 0.586915 | 91 | 17 | 0 | 17 | 14 | 4 | 1 | 2 | 9 | 1 | 0 | 7.647059 | 838 | 0.040573 | 0.016706 | 0.004773 | 0.001193 | 0 | 0.038462 | 0.173077 | 0.320932 | export default class Day4 {
private _boards;
private _highlightedNumbers;
private _numbersInPool;
private _drawnNumbers;
public solve(input) {
this._drawnNumbers = input.split('\n')[0].split(',').map(n => parseInt(n));
this._boards = input.split('\n\n').slice(1).map(boardString => {
const board = [];
boardString.split('\n').forEach((line) => {
board.push(line.match(/.{1,3}/g).map(n => parseInt(n.trim())));
});
return board;
});
// part 1
let winningBoard;
let numbersDrawn = 5;
while (!winningBoard) {
this._numbersInPool = this._drawnNumbers.slice(0, numbersDrawn);
winningBoard = this._boards.find(wb => this._checkForWinner(wb));
numbersDrawn++;
}
let multiplyBy = this._highlightedNumbers[this._highlightedNumbers.length - 1];
let totalOfNotHighlighted = 0;
winningBoard.forEach(row => {
row.forEach(number => {
if (!this._numbersInPool.includes(number)) {
totalOfNotHighlighted += number;
}
});
});
const part1Solution = totalOfNotHighlighted * multiplyBy;
// part 2
numbersDrawn = 5;
const winningBoards = [];
let editingBoards = [...this._boards];
while (winningBoards.length < this._boards.length) {
this._numbersInPool = this._drawnNumbers.slice(0, numbersDrawn);
winningBoards.push(...editingBoards.filter(wb => this._checkForWinner(wb)));
editingBoards = editingBoards.filter(b => !winningBoards.includes(b));
numbersDrawn++;
}
const lastBoard = winningBoards[winningBoards.length - 1];
multiplyBy = this._highlightedNumbers[this._highlightedNumbers.length - 1];
totalOfNotHighlighted = 0;
lastBoard.forEach(row => {
row.forEach(number => {
if (!this._numbersInPool.includes(number)) {
totalOfNotHighlighted += number;
}
});
});
const part2Solution = totalOfNotHighlighted * multiplyBy;
return { part1: part1Solution, part2: part2Solution };
}
private _checkForWinner(board) {
let found = false;
// check rows
board.forEach(row => {
let bingo = true;
if (!found) {
this._highlightedNumbers = [];
row.forEach(number => {
this._highlightedNumbers.push(number);
if (!this._numbersInPool.includes(number)) {
bingo = false;
}
});
if (bingo) {
found = true;
}
}
});
// check columns
for (let x = 0; x < 5; x++) {
let bingo = true;
if (!found) {
this._highlightedNumbers = [];
board.forEach(row => {
this._highlightedNumbers.push(row[x]);
if (!this._numbersInPool.includes(row[x])) {
bingo = false;
}
});
if (bingo) {
found = true;
}
}
}
if (found) {
this._highlightedNumbers = this._numbersInPool.filter(n => this._highlightedNumbers.includes(n));
}
return found;
};
}
|
d0d1086bff94aa89cca676745f39b6a620f49706 | 2,586 | ts | TypeScript | src/Global/Util/InfoByte.ts | Divine-Star-LLC/DivineVoxelEngine | 656dc6e06fa4aecea460d91766b43c8f94d57e44 | [
"MIT"
] | 5 | 2022-02-02T03:50:38.000Z | 2022-02-08T04:23:42.000Z | src/Global/Util/InfoByte.ts | lucasdamianjohnson/DivineVoxelEngine | 157ce7863f6119d4a4d9b9c0886352068a06a2da | [
"MIT"
] | 1 | 2022-02-28T01:46:49.000Z | 2022-03-06T14:05:05.000Z | src/Global/Util/InfoByte.ts | lucasdamianjohnson/DivineVoxelEngine | 157ce7863f6119d4a4d9b9c0886352068a06a2da | [
"MIT"
] | 1 | 2022-02-02T12:55:33.000Z | 2022-02-02T12:55:33.000Z | type BinaryNums = 0 | 1;
type BinaryArray = BinaryNums[];
export const InfoByte = {
maxBit : 31,
minBit : 0,
maxDec : 2 ** 31 + 1,
minDec : 0,
byteValue : 0,
getNumberValue(): number {
return this.byteValue;
},
setNumberValue(newValue: number) {
if (newValue > this.maxDec || newValue < this.minDec) {
throw new Error(
`Value is out of range. Acceptable range is ${this.minDec} - ${this.maxDec}`
);
}
this.byteValue = newValue;
},
getBit(index: number): BinaryNums {
if (index > this.maxBit || index < this.minBit) {
throw new Error(
`Index is out of range. Acceptable range is ${this.minBit} - ${this.maxBit}`
);
}
const value = (this.byteValue >>> index) & 1;
return <BinaryNums>value;
},
getBitsArray(bitIndex: number, byteLength: number): BinaryArray {
if (bitIndex > this.maxBit + byteLength || bitIndex < this.minBit) {
throw new Error(
`Index is out of range. Acceptable range is ${this.minBit} - ${this.maxBit}`
);
}
const bits: BinaryArray = [];
for (let i = bitIndex; i < bitIndex + byteLength; i++) {
//@ts-ignore
bits.push((this.byteValue >>> i) & 1);
}
return bits;
},
getHalfByteDec(bitIndex: number): number {
if (bitIndex > this.maxBit + 4 || bitIndex < this.minBit) {
throw new Error(
`Index is out of range. Acceptable range is ${this.minBit} - ${this.maxBit}`
);
}
return (this.byteValue & (0x0f << bitIndex)) >> bitIndex;
},
setHalfByteBits(index: number, value: number) {
if (index > this.maxBit || index < this.minBit) {
throw new Error(
`Index is out of range. Acceptable range is ${this.minBit} - ${this.maxBit}`
);
}
if (value > 15) {
throw new Error(`Value is out range. Must not be greater than 16`);
}
this.byteValue = (this.byteValue & ~(0xf << index)) | (value << index);
},
setBit(index: number, value: BinaryNums) {
if (index > this.maxBit || index < this.minBit) {
throw new Error(
`Index is out of range. Acceptable range is ${this.minBit} - ${this.maxBit}`
);
}
if (value < 0 || value > 1) {
throw new Error("Value is not in range. Acceptable range is 0 - 1");
}
const setValue = 1 << index;
if (!value) {
this.byteValue = this.byteValue & ~setValue;
} else {
this.byteValue = this.byteValue | setValue;
}
},
toArray(): BinaryArray {
const returnArray: BinaryArray = [];
for (let i = 0; i <= this.maxBit; i++) {
returnArray.push(this.getBit(i));
}
return returnArray;
},
toString(delimiter = "") {
const array = this.toArray();
return array.join(delimiter);
},
};
| 25.86 | 80 | 0.624517 | 87 | 9 | 0 | 10 | 8 | 0 | 2 | 0 | 10 | 2 | 0 | 6.666667 | 829 | 0.022919 | 0.00965 | 0 | 0.002413 | 0 | 0 | 0.37037 | 0.259123 | type BinaryNums = 0 | 1;
type BinaryArray = BinaryNums[];
export const InfoByte = {
maxBit : 31,
minBit : 0,
maxDec : 2 ** 31 + 1,
minDec : 0,
byteValue : 0,
getNumberValue() {
return this.byteValue;
},
setNumberValue(newValue) {
if (newValue > this.maxDec || newValue < this.minDec) {
throw new Error(
`Value is out of range. Acceptable range is ${this.minDec} - ${this.maxDec}`
);
}
this.byteValue = newValue;
},
getBit(index) {
if (index > this.maxBit || index < this.minBit) {
throw new Error(
`Index is out of range. Acceptable range is ${this.minBit} - ${this.maxBit}`
);
}
const value = (this.byteValue >>> index) & 1;
return <BinaryNums>value;
},
getBitsArray(bitIndex, byteLength) {
if (bitIndex > this.maxBit + byteLength || bitIndex < this.minBit) {
throw new Error(
`Index is out of range. Acceptable range is ${this.minBit} - ${this.maxBit}`
);
}
const bits = [];
for (let i = bitIndex; i < bitIndex + byteLength; i++) {
//@ts-ignore
bits.push((this.byteValue >>> i) & 1);
}
return bits;
},
getHalfByteDec(bitIndex) {
if (bitIndex > this.maxBit + 4 || bitIndex < this.minBit) {
throw new Error(
`Index is out of range. Acceptable range is ${this.minBit} - ${this.maxBit}`
);
}
return (this.byteValue & (0x0f << bitIndex)) >> bitIndex;
},
setHalfByteBits(index, value) {
if (index > this.maxBit || index < this.minBit) {
throw new Error(
`Index is out of range. Acceptable range is ${this.minBit} - ${this.maxBit}`
);
}
if (value > 15) {
throw new Error(`Value is out range. Must not be greater than 16`);
}
this.byteValue = (this.byteValue & ~(0xf << index)) | (value << index);
},
setBit(index, value) {
if (index > this.maxBit || index < this.minBit) {
throw new Error(
`Index is out of range. Acceptable range is ${this.minBit} - ${this.maxBit}`
);
}
if (value < 0 || value > 1) {
throw new Error("Value is not in range. Acceptable range is 0 - 1");
}
const setValue = 1 << index;
if (!value) {
this.byteValue = this.byteValue & ~setValue;
} else {
this.byteValue = this.byteValue | setValue;
}
},
toArray() {
const returnArray = [];
for (let i = 0; i <= this.maxBit; i++) {
returnArray.push(this.getBit(i));
}
return returnArray;
},
toString(delimiter = "") {
const array = this.toArray();
return array.join(delimiter);
},
};
|
b81355c6d07e30b233de5d7aafdc08d6b6f34d1e | 2,038 | ts | TypeScript | word-search/index.ts | masx200/leetcode-test | bec83c7bc30fe3387a19bf8ae0c8685ed0aba2f4 | [
"MulanPSL-1.0"
] | 1 | 2022-03-30T11:10:14.000Z | 2022-03-30T11:10:14.000Z | word-search/index.ts | masx200/leetcode-test | bec83c7bc30fe3387a19bf8ae0c8685ed0aba2f4 | [
"MulanPSL-1.0"
] | null | null | null | word-search/index.ts | masx200/leetcode-test | bec83c7bc30fe3387a19bf8ae0c8685ed0aba2f4 | [
"MulanPSL-1.0"
] | null | null | null | export default function exist(board: string[][], word: string): boolean {
if (
word.length === 1 &&
board.length === 1 &&
board[0].length === 1 &&
word === board[0][0]
) {
return true;
}
if (word.length === 0) return false;
const row = board.length;
if (!row) return false;
const col = board[0].length;
if (!col) return false;
const first = word[0];
const visited: boolean[][] = Array.from(board).map((a) =>
Array.from(a).map(() => false)
);
// console.log(starts)
const directions: Array<[number, number]> = [
[0, 1],
[1, 0],
[0, -1],
[-1, 0],
];
function dfs(
word: string,
i: number,
j: number, /* visited: boolean[][] */
): boolean {
// console.log({ word, i, j })
// console.log(visited)
if (board[i][j] !== word[0]) return false;
else if (word.length === 1) return true;
visited[i][j] = true;
// let result = false
for (const [f, s] of directions) {
const x = i + f;
const y = j + s;
if (x >= 0 && y >= 0 && x < row && y < col) {
if (!visited[x][y]) {
if (dfs(word.slice(1), x, y /* visited */)) {
visited[i][j] = false;
return true;
} /* else {
// visited[x][y] = false
//visited[i][j] = false;
} */
}
}
}
visited[i][j] = false;
return false;
}
const all_chars = new Set(board.flat());
if (Array.prototype.some.call(word, (c) => !all_chars.has(c))) return false;
for (let i = 0; i < row; i++) {
for (let j = 0; j < col; j++) {
if (first === board[i][j]) {
const flag = dfs(word, i, j);
if (flag) {
return true;
}
}
}
}
return false;
}
| 27.173333 | 80 | 0.410697 | 61 | 5 | 0 | 7 | 11 | 0 | 1 | 0 | 10 | 0 | 0 | 15.8 | 567 | 0.021164 | 0.0194 | 0 | 0 | 0 | 0 | 0.434783 | 0.282689 | export default function exist(board, word) {
if (
word.length === 1 &&
board.length === 1 &&
board[0].length === 1 &&
word === board[0][0]
) {
return true;
}
if (word.length === 0) return false;
const row = board.length;
if (!row) return false;
const col = board[0].length;
if (!col) return false;
const first = word[0];
const visited = Array.from(board).map((a) =>
Array.from(a).map(() => false)
);
// console.log(starts)
const directions = [
[0, 1],
[1, 0],
[0, -1],
[-1, 0],
];
/* Example usages of 'dfs' are shown below:
dfs(word.slice(1), x, y visited );
dfs(word, i, j);
*/
function dfs(
word,
i,
j, /* visited: boolean[][] */
) {
// console.log({ word, i, j })
// console.log(visited)
if (board[i][j] !== word[0]) return false;
else if (word.length === 1) return true;
visited[i][j] = true;
// let result = false
for (const [f, s] of directions) {
const x = i + f;
const y = j + s;
if (x >= 0 && y >= 0 && x < row && y < col) {
if (!visited[x][y]) {
if (dfs(word.slice(1), x, y /* visited */)) {
visited[i][j] = false;
return true;
} /* else {
// visited[x][y] = false
//visited[i][j] = false;
} */
}
}
}
visited[i][j] = false;
return false;
}
const all_chars = new Set(board.flat());
if (Array.prototype.some.call(word, (c) => !all_chars.has(c))) return false;
for (let i = 0; i < row; i++) {
for (let j = 0; j < col; j++) {
if (first === board[i][j]) {
const flag = dfs(word, i, j);
if (flag) {
return true;
}
}
}
}
return false;
}
|
b839a293ce62e44e9d0f1f91b4b2e6cdfbf9f66e | 2,778 | ts | TypeScript | frontend/src/app/models/httpTypes/requests.model.ts | jackroi/connect-four | c4a08bc4873b2b3ac9ba718b509f385020a584ac | [
"MIT"
] | null | null | null | frontend/src/app/models/httpTypes/requests.model.ts | jackroi/connect-four | c4a08bc4873b2b3ac9ba718b509f385020a584ac | [
"MIT"
] | null | null | null | frontend/src/app/models/httpTypes/requests.model.ts | jackroi/connect-four | c4a08bc4873b2b3ac9ba718b509f385020a584ac | [
"MIT"
] | 1 | 2022-03-30T14:44:23.000Z | 2022-03-30T14:44:23.000Z | // Interfaces for the HTTP requests
export interface RequestBody {
}
export interface RegistrationRequestBody extends RequestBody {
username: string,
password: string,
isModerator: boolean,
}
export interface StandardPlayerRegistrationRequestBody extends RegistrationRequestBody {
isModerator: false,
name: string,
surname: string,
}
export interface ModeratorRegistrationRequestBody extends RegistrationRequestBody {
isModerator: true,
}
// Type guard function
export function isStandardPlayerRegistrationRequestBody(arg: any): arg is StandardPlayerRegistrationRequestBody {
return arg
&& arg.username
&& typeof (arg.username) === 'string'
&& arg.password
&& typeof (arg.password) === 'string'
&& arg.isModerator !== undefined && arg.isModerator !== null // Check explicity the inequality to undefined and null
&& !arg.isModerator
&& arg.name
&& typeof (arg.name) === 'string'
&& arg.surname
&& typeof (arg.surname) === 'string';
}
// Type guard function
export function isModeratorRegistrationRequestBody(arg: any): arg is ModeratorRegistrationRequestBody {
return arg
&& arg.username
&& typeof (arg.username) === 'string'
&& arg.password
&& typeof (arg.password) === 'string'
&& arg.isModerator !== undefined && arg.isModerator !== null // Check explicity the inequality to undefined and null
&& arg.isModerator;
}
export interface ConfirmModeratorRequestBody extends RequestBody {
password: string,
name: string,
surname: string,
}
// Type guard function
export function isConfirmModeratorRequestBody(arg: any): arg is ConfirmModeratorRequestBody {
return arg
&& arg.password
&& typeof (arg.password) === 'string'
&& arg.name
&& typeof (arg.name) === 'string'
&& arg.surname
&& typeof (arg.surname) === 'string';
}
export interface NotifyAvailabilityFriendRequestRequestBody extends RequestBody {
username: string,
}
// Type guard function
export function isNotifyAvailabilityFriendRequestRequestBody(arg: any): arg is NotifyAvailabilityFriendRequestRequestBody {
return arg
&& arg.username
&& typeof (arg.username) === 'string';
}
export interface NotifyUnavailabilityFriendRequestRequestBody extends RequestBody {
username: string,
}
// Type guard function
export function isNotifyUnavailabilityFriendRequestRequestBody(arg: any): arg is NotifyUnavailabilityFriendRequestRequestBody {
return arg
&& arg.username
&& typeof (arg.username) === 'string';
}
export interface AddMoveRequestBody extends RequestBody {
column: number,
}
// Type guard function
export function isAddMoveRequestBody(arg: any): arg is AddMoveRequestBody {
return arg
&& arg.column !== undefined
&& typeof (arg.column) === 'number';
}
| 28.346939 | 127 | 0.727142 | 75 | 6 | 0 | 6 | 0 | 13 | 0 | 6 | 11 | 8 | 12 | 5.666667 | 659 | 0.018209 | 0 | 0.019727 | 0.01214 | 0.018209 | 0.24 | 0.44 | 0.225092 | // Interfaces for the HTTP requests
export interface RequestBody {
}
export interface RegistrationRequestBody extends RequestBody {
username,
password,
isModerator,
}
export interface StandardPlayerRegistrationRequestBody extends RegistrationRequestBody {
isModerator,
name,
surname,
}
export interface ModeratorRegistrationRequestBody extends RegistrationRequestBody {
isModerator,
}
// Type guard function
export function isStandardPlayerRegistrationRequestBody(arg): arg is StandardPlayerRegistrationRequestBody {
return arg
&& arg.username
&& typeof (arg.username) === 'string'
&& arg.password
&& typeof (arg.password) === 'string'
&& arg.isModerator !== undefined && arg.isModerator !== null // Check explicity the inequality to undefined and null
&& !arg.isModerator
&& arg.name
&& typeof (arg.name) === 'string'
&& arg.surname
&& typeof (arg.surname) === 'string';
}
// Type guard function
export function isModeratorRegistrationRequestBody(arg): arg is ModeratorRegistrationRequestBody {
return arg
&& arg.username
&& typeof (arg.username) === 'string'
&& arg.password
&& typeof (arg.password) === 'string'
&& arg.isModerator !== undefined && arg.isModerator !== null // Check explicity the inequality to undefined and null
&& arg.isModerator;
}
export interface ConfirmModeratorRequestBody extends RequestBody {
password,
name,
surname,
}
// Type guard function
export function isConfirmModeratorRequestBody(arg): arg is ConfirmModeratorRequestBody {
return arg
&& arg.password
&& typeof (arg.password) === 'string'
&& arg.name
&& typeof (arg.name) === 'string'
&& arg.surname
&& typeof (arg.surname) === 'string';
}
export interface NotifyAvailabilityFriendRequestRequestBody extends RequestBody {
username,
}
// Type guard function
export function isNotifyAvailabilityFriendRequestRequestBody(arg): arg is NotifyAvailabilityFriendRequestRequestBody {
return arg
&& arg.username
&& typeof (arg.username) === 'string';
}
export interface NotifyUnavailabilityFriendRequestRequestBody extends RequestBody {
username,
}
// Type guard function
export function isNotifyUnavailabilityFriendRequestRequestBody(arg): arg is NotifyUnavailabilityFriendRequestRequestBody {
return arg
&& arg.username
&& typeof (arg.username) === 'string';
}
export interface AddMoveRequestBody extends RequestBody {
column,
}
// Type guard function
export function isAddMoveRequestBody(arg): arg is AddMoveRequestBody {
return arg
&& arg.column !== undefined
&& typeof (arg.column) === 'number';
}
|
b87c8398cb2a3f75914c79c287e1c1b0c377c42d | 2,859 | ts | TypeScript | problemset/strong-password-checker/index.ts | OUDUIDUI/leet-code | 50e61ce16d1c419ccefc075ae9ead721cdd1cdbb | [
"MIT"
] | 6 | 2022-01-17T03:19:56.000Z | 2022-01-17T05:45:39.000Z | problemset/strong-password-checker/index.ts | OUDUIDUI/leet-code | 50e61ce16d1c419ccefc075ae9ead721cdd1cdbb | [
"MIT"
] | null | null | null | problemset/strong-password-checker/index.ts | OUDUIDUI/leet-code | 50e61ce16d1c419ccefc075ae9ead721cdd1cdbb | [
"MIT"
] | null | null | null | /**
* 分类讨论
* @desc 时间复杂度 O(N) 空间复杂度 O(1)
* @param password
* @returns
*/
export function strongPasswordChecker(password: string): number {
const isLowerCase = (ch: string): boolean => (ch >= 'a' && ch <= 'z')
const isUpperCase = (ch: string): boolean => (ch >= 'A' && ch <= 'Z')
const isNumber = (ch: string): boolean => (ch >= '0' && ch <= '9')
const len = password.length
let hasLower: 0 | 1 = 0
let hasUpper: 0 | 1 = 0
let hasNumber: 0 | 1 = 0
for (let i = 0; i < len; i++) {
const ch = password.charAt(i)
if (isLowerCase(ch))
hasLower = 1
else if (isUpperCase(ch))
hasUpper = 1
else if (isNumber(ch))
hasNumber = 1
}
const categories = hasLower + hasUpper + hasNumber
// 少于 6 个的情况
if (len < 6) { return Math.max(6 - len, 3 - categories) }
// 少于或等于 20 个的情况
else if (len <= 20) {
let replace = 0 // 记录需要更换的个数
let count = 0 // 统计连续出现cur的次数
let cur = '#'
for (let i = 0; i < len; i++) {
const ch = password.charAt(i)
if (ch === cur) {
count++
}
else {
// 我们只需替换 count / 3 个元素,即隔两个换一个
replace += (count / 3) >> 0
// 重置
count = 1
cur = ch
}
}
// 最后在清空一下count,更新replace
replace += (count / 3) >> 0
return Math.max(replace, 3 - categories)
}
// 多于 20 个的情况
else {
let replace = 0 // 记录需要更换的个数
let remove = len - 20 // 需要删除的次数
let canRemove = 0
let count = 0
let cur = '#'
for (let i = 0; i < len; i++) {
const ch = password.charAt(i)
if (ch === cur) {
count++
}
else {
// 如果有一元素连续出现超过3次,且还有删除元素的空间的话
if (remove > 0 && count >= 3) {
// count % 3 === 0 的情况,利用一个删除次数来删除一个重复元素
// 因此将其变成了 count % 3 === 2 的情况,可以减少一次更换次数
if (count % 3 === 0) {
remove--
replace--
}
// count % 3 === 1 的情况,可以通过利用两次删除次数了换取减少一次更换次数
// 但这里的成本太大,希望把更多更换机会留给上面的情况,因此我们可以统计次数
// 在最后还有删除次数的时候,再进行更换
else if (count % 3 === 1) {
canRemove++
}
}
// 更新replace
replace += (count / 3) >> 0
count = 1
cur = ch
}
}
// 遍历后,清空count,更新replace
if (remove > 0 && count >= 3) {
if (count % 3 === 0) {
remove--
replace--
}
else if (count % 3 === 1) {
canRemove++
}
}
replace += Math.floor(count / 3)
// 使用 count % 3 === 1 的数量,由剩余的替换次数、组数和剩余的删除次数共同决定
let use = Math.min(Math.min(replace, canRemove), (remove >> 1))
replace -= use
remove -= use * 2
// 由于每有一次替换次数就一定有 3 个连续相同的字符(count / 3 决定),因此这里可以直接计算出使用 count % 3 === 2 的组的数量
use = Math.min(replace, (remove / 3) >> 0)
replace -= use
remove -= use * 3
return (len - 20) + Math.max(replace, 3 - categories)
}
}
| 23.628099 | 82 | 0.497377 | 82 | 4 | 0 | 4 | 23 | 0 | 3 | 0 | 8 | 0 | 0 | 20.75 | 1,065 | 0.007512 | 0.021596 | 0 | 0 | 0 | 0 | 0.258065 | 0.258668 | /**
* 分类讨论
* @desc 时间复杂度 O(N) 空间复杂度 O(1)
* @param password
* @returns
*/
export function strongPasswordChecker(password) {
/* Example usages of 'isLowerCase' are shown below:
isLowerCase(ch);
*/
const isLowerCase = (ch) => (ch >= 'a' && ch <= 'z')
/* Example usages of 'isUpperCase' are shown below:
isUpperCase(ch);
*/
const isUpperCase = (ch) => (ch >= 'A' && ch <= 'Z')
/* Example usages of 'isNumber' are shown below:
isNumber(ch);
*/
const isNumber = (ch) => (ch >= '0' && ch <= '9')
const len = password.length
let hasLower = 0
let hasUpper = 0
let hasNumber = 0
for (let i = 0; i < len; i++) {
const ch = password.charAt(i)
if (isLowerCase(ch))
hasLower = 1
else if (isUpperCase(ch))
hasUpper = 1
else if (isNumber(ch))
hasNumber = 1
}
const categories = hasLower + hasUpper + hasNumber
// 少于 6 个的情况
if (len < 6) { return Math.max(6 - len, 3 - categories) }
// 少于或等于 20 个的情况
else if (len <= 20) {
let replace = 0 // 记录需要更换的个数
let count = 0 // 统计连续出现cur的次数
let cur = '#'
for (let i = 0; i < len; i++) {
const ch = password.charAt(i)
if (ch === cur) {
count++
}
else {
// 我们只需替换 count / 3 个元素,即隔两个换一个
replace += (count / 3) >> 0
// 重置
count = 1
cur = ch
}
}
// 最后在清空一下count,更新replace
replace += (count / 3) >> 0
return Math.max(replace, 3 - categories)
}
// 多于 20 个的情况
else {
let replace = 0 // 记录需要更换的个数
let remove = len - 20 // 需要删除的次数
let canRemove = 0
let count = 0
let cur = '#'
for (let i = 0; i < len; i++) {
const ch = password.charAt(i)
if (ch === cur) {
count++
}
else {
// 如果有一元素连续出现超过3次,且还有删除元素的空间的话
if (remove > 0 && count >= 3) {
// count % 3 === 0 的情况,利用一个删除次数来删除一个重复元素
// 因此将其变成了 count % 3 === 2 的情况,可以减少一次更换次数
if (count % 3 === 0) {
remove--
replace--
}
// count % 3 === 1 的情况,可以通过利用两次删除次数了换取减少一次更换次数
// 但这里的成本太大,希望把更多更换机会留给上面的情况,因此我们可以统计次数
// 在最后还有删除次数的时候,再进行更换
else if (count % 3 === 1) {
canRemove++
}
}
// 更新replace
replace += (count / 3) >> 0
count = 1
cur = ch
}
}
// 遍历后,清空count,更新replace
if (remove > 0 && count >= 3) {
if (count % 3 === 0) {
remove--
replace--
}
else if (count % 3 === 1) {
canRemove++
}
}
replace += Math.floor(count / 3)
// 使用 count % 3 === 1 的数量,由剩余的替换次数、组数和剩余的删除次数共同决定
let use = Math.min(Math.min(replace, canRemove), (remove >> 1))
replace -= use
remove -= use * 2
// 由于每有一次替换次数就一定有 3 个连续相同的字符(count / 3 决定),因此这里可以直接计算出使用 count % 3 === 2 的组的数量
use = Math.min(replace, (remove / 3) >> 0)
replace -= use
remove -= use * 3
return (len - 20) + Math.max(replace, 3 - categories)
}
}
|
b8b1d3ef8fde25053af894e390905d52bb752905 | 1,574 | ts | TypeScript | uaa-serve/src/types/index.ts | brave9uy/dsn-uaa | 40ad83482a15f279d3f2559b21ed5ac890d7de5f | [
"MIT"
] | 3 | 2022-03-24T10:06:03.000Z | 2022-03-28T03:00:43.000Z | uaa-serve/src/types/index.ts | brave9uy/dsn-uaa | 40ad83482a15f279d3f2559b21ed5ac890d7de5f | [
"MIT"
] | null | null | null | uaa-serve/src/types/index.ts | brave9uy/dsn-uaa | 40ad83482a15f279d3f2559b21ed5ac890d7de5f | [
"MIT"
] | 1 | 2022-03-24T10:06:05.000Z | 2022-03-24T10:06:05.000Z | export interface IResult {
code: number;
data: any
msg: string,
total: number
}
export enum Order {
DESC = 'desc',
ASC = 'asc'
}
export class Page<T> {
page: number;
offset: number;
start: number;
total: number;
list: T[];
static of(page: number, size: number) {
const p = new Page()
p.page = page;
p.offset = size
p.start = (page - 1) * size
return p
}
paging(list: T[]) {
this.list = list.filter((o: T, i: number) => i >= this.start && i < this.start + this.offset)
return this
}
withTotal(total: number) {
this.total = total
return this
}
}
export const buildResult = (data: any, code: number) => {
const result: IResult = {
code,
msg: null,
total: 0,
data: null
}
if (Array.isArray(data)) {
result.total = data.length
} else {
if (typeof data === 'string') {
result.msg = data
}
result.total = 1
if (data instanceof Page) {
result.total = data.total
data = data.list
}
}
result.data = data
return result
}
export const returnSuccess = <T>(data: T) => {
return buildResult(data, 200)
}
export interface User {
id: number;
username: string;
mobile: string;
email: string;
name: string;
enabled: number;
}
export interface Permission {
id: number;
parent: number;
authority: string;
displayName: string;
icon: string;
uri: string;
enabled: number;
permissions?: Array<Permission>;
}
export interface Log {
id: number;
operationName: string;
username: string;
operationTime: string;
} | 17.296703 | 97 | 0.60864 | 81 | 6 | 0 | 9 | 4 | 27 | 1 | 2 | 29 | 5 | 2 | 5.166667 | 477 | 0.031447 | 0.008386 | 0.056604 | 0.010482 | 0.004193 | 0.043478 | 0.630435 | 0.286058 | export interface IResult {
code;
data
msg,
total
}
export enum Order {
DESC = 'desc',
ASC = 'asc'
}
export class Page<T> {
page;
offset;
start;
total;
list;
static of(page, size) {
const p = new Page()
p.page = page;
p.offset = size
p.start = (page - 1) * size
return p
}
paging(list) {
this.list = list.filter((o, i) => i >= this.start && i < this.start + this.offset)
return this
}
withTotal(total) {
this.total = total
return this
}
}
export /* Example usages of 'buildResult' are shown below:
buildResult(data, 200);
*/
const buildResult = (data, code) => {
const result = {
code,
msg: null,
total: 0,
data: null
}
if (Array.isArray(data)) {
result.total = data.length
} else {
if (typeof data === 'string') {
result.msg = data
}
result.total = 1
if (data instanceof Page) {
result.total = data.total
data = data.list
}
}
result.data = data
return result
}
export const returnSuccess = <T>(data) => {
return buildResult(data, 200)
}
export interface User {
id;
username;
mobile;
email;
name;
enabled;
}
export interface Permission {
id;
parent;
authority;
displayName;
icon;
uri;
enabled;
permissions?;
}
export interface Log {
id;
operationName;
username;
operationTime;
} |
b42aa570b31f6fce634afaeeaba873a00a2a1394 | 2,088 | ts | TypeScript | src/reader-lib/utils/markdown-toc-lib.ts | tutors-sdk/tutors-course-reader | ca3e097cd02df6a34f02322c0b7d8b27bfc5b06b | [
"MIT"
] | 1 | 2022-03-22T22:43:44.000Z | 2022-03-22T22:43:44.000Z | src/reader-lib/utils/markdown-toc-lib.ts | tutors-sdk/tutors-course-reader | ca3e097cd02df6a34f02322c0b7d8b27bfc5b06b | [
"MIT"
] | 8 | 2022-02-19T07:29:23.000Z | 2022-03-21T09:24:43.000Z | src/reader-lib/utils/markdown-toc-lib.ts | tutors-sdk/tutors-course-reader | ca3e097cd02df6a34f02322c0b7d8b27bfc5b06b | [
"MIT"
] | null | null | null | type TocItem = {
anchor: string;
level: number;
text: string;
};
type MetaInfo =
| {
type: "toc";
}
| {
type: "header";
anchor: string;
level: number;
text: string;
};
export function generateToc(source: string): string {
const toc: TocItem[] = [];
const regex = /(<h([1-6]).*?id="([^"]*?)".*?>(.+?)<\/h[1-6]>)|(<p>\[toc\]<\/p>)/g;
// find and collect all headers and [toc] node;
const collection: MetaInfo[] = [];
source.replace(regex, (wholeMatch, _, level, anchor, text) => {
if (wholeMatch === '<p>[toc]</p>') {
collection.push({ type: 'toc' });
} else {
text = text.replace(/<[^>]+>/g, '');
const tocItem = {
anchor,
level: Number(level),
text,
};
if (toc) {
toc.push(tocItem);
}
collection.push({
type: 'header',
...tocItem,
});
}
return '';
});
// calculate toc info
const tocCollection: TocItem[][] = [];
collection.forEach(({ type }, index) => {
if (type === 'toc') {
if (collection[index + 1] && collection[index + 1].type === 'header') {
const headers = [];
const { level: levelToToc } = collection[index + 1] as TocItem;
for (let i = index + 1; i < collection.length; i++) {
if (collection[i].type === 'toc') break;
const { level } = collection[i] as TocItem;
if (level === levelToToc) {
headers.push(collection[i] as TocItem);
}
}
tocCollection.push(headers);
} else {
tocCollection.push([]);
}
}
});
// replace [toc] node in source
source = source.replace(/<p>\[toc\]<\/p>[\n]*/g, () => {
const headers = tocCollection.shift();
if (headers && headers.length) {
const str = `<ol>${headers
.map(({ text, anchor }) => `<li><a style="cursor: pointer;" onClick="document.getElementById('${anchor}').scrollIntoView({ behavior: 'smooth', block: 'center' });">${text}</a></li>`)
.join('')}</ol>\n`;
return str;
}
return '';
});
return source;
}
| 25.777778 | 190 | 0.5091 | 70 | 5 | 0 | 9 | 11 | 3 | 0 | 0 | 8 | 2 | 3 | 19.2 | 610 | 0.022951 | 0.018033 | 0.004918 | 0.003279 | 0.004918 | 0 | 0.285714 | 0.286905 | type TocItem = {
anchor;
level;
text;
};
type MetaInfo =
| {
type;
}
| {
type;
anchor;
level;
text;
};
export function generateToc(source) {
const toc = [];
const regex = /(<h([1-6]).*?id="([^"]*?)".*?>(.+?)<\/h[1-6]>)|(<p>\[toc\]<\/p>)/g;
// find and collect all headers and [toc] node;
const collection = [];
source.replace(regex, (wholeMatch, _, level, anchor, text) => {
if (wholeMatch === '<p>[toc]</p>') {
collection.push({ type: 'toc' });
} else {
text = text.replace(/<[^>]+>/g, '');
const tocItem = {
anchor,
level: Number(level),
text,
};
if (toc) {
toc.push(tocItem);
}
collection.push({
type: 'header',
...tocItem,
});
}
return '';
});
// calculate toc info
const tocCollection = [];
collection.forEach(({ type }, index) => {
if (type === 'toc') {
if (collection[index + 1] && collection[index + 1].type === 'header') {
const headers = [];
const { level: levelToToc } = collection[index + 1] as TocItem;
for (let i = index + 1; i < collection.length; i++) {
if (collection[i].type === 'toc') break;
const { level } = collection[i] as TocItem;
if (level === levelToToc) {
headers.push(collection[i] as TocItem);
}
}
tocCollection.push(headers);
} else {
tocCollection.push([]);
}
}
});
// replace [toc] node in source
source = source.replace(/<p>\[toc\]<\/p>[\n]*/g, () => {
const headers = tocCollection.shift();
if (headers && headers.length) {
const str = `<ol>${headers
.map(({ text, anchor }) => `<li><a style="cursor: pointer;" onClick="document.getElementById('${anchor}').scrollIntoView({ behavior: 'smooth', block: 'center' });">${text}</a></li>`)
.join('')}</ol>\n`;
return str;
}
return '';
});
return source;
}
|
e515e6724820dbd8b7832080af0a2b071e47ff1c | 6,684 | ts | TypeScript | src/ChatEvents.ts | AsteriskZuo/react-native-easemob | 53763d1926344837979600c3f73b5b3e1bbc4ac6 | [
"MIT"
] | null | null | null | src/ChatEvents.ts | AsteriskZuo/react-native-easemob | 53763d1926344837979600c3f73b5b3e1bbc4ac6 | [
"MIT"
] | null | null | null | src/ChatEvents.ts | AsteriskZuo/react-native-easemob | 53763d1926344837979600c3f73b5b3e1bbc4ac6 | [
"MIT"
] | 2 | 2022-03-23T07:31:14.000Z | 2022-03-25T07:45:38.000Z | export enum ChatContactGroupEvent {
CONTACT_REMOVE,
CONTACT_ACCEPT,
CONTACT_DECLINE,
CONTACT_BAN,
CONTACT_ALLOW,
GROUP_CREATE,
GROUP_DESTROY,
GROUP_JOIN,
GROUP_LEAVE,
GROUP_APPLY,
GROUP_APPLY_ACCEPT,
GROUP_APPLY_DECLINE,
GROUP_INVITE,
GROUP_INVITE_ACCEPT,
GROUP_INVITE_DECLINE,
GROUP_KICK,
GROUP_BAN,
GROUP_ALLOW,
GROUP_BLOCK,
GROUP_UNBLOCK,
GROUP_ASSIGN_OWNER,
GROUP_ADD_ADMIN,
GROUP_REMOVE_ADMIN,
GROUP_ADD_MUTE,
GROUP_REMOVE_MUTE,
}
export function ChatContactGroupEventFromNumber(
params: number
): ChatContactGroupEvent {
switch (params) {
case 2:
return ChatContactGroupEvent.CONTACT_REMOVE;
case 3:
return ChatContactGroupEvent.CONTACT_ACCEPT;
case 4:
return ChatContactGroupEvent.CONTACT_DECLINE;
case 5:
return ChatContactGroupEvent.CONTACT_BAN;
case 6:
return ChatContactGroupEvent.CONTACT_ALLOW;
case 10:
return ChatContactGroupEvent.GROUP_CREATE;
case 11:
return ChatContactGroupEvent.GROUP_DESTROY;
case 12:
return ChatContactGroupEvent.GROUP_JOIN;
case 13:
return ChatContactGroupEvent.GROUP_LEAVE;
case 14:
return ChatContactGroupEvent.GROUP_APPLY;
case 15:
return ChatContactGroupEvent.GROUP_APPLY_ACCEPT;
case 16:
return ChatContactGroupEvent.GROUP_APPLY_DECLINE;
case 17:
return ChatContactGroupEvent.GROUP_INVITE;
case 18:
return ChatContactGroupEvent.GROUP_INVITE_ACCEPT;
case 19:
return ChatContactGroupEvent.GROUP_INVITE_DECLINE;
case 20:
return ChatContactGroupEvent.GROUP_KICK;
case 21:
return ChatContactGroupEvent.GROUP_BAN;
case 22:
return ChatContactGroupEvent.GROUP_ALLOW;
case 23:
return ChatContactGroupEvent.GROUP_BLOCK;
case 24:
return ChatContactGroupEvent.GROUP_UNBLOCK;
case 25:
return ChatContactGroupEvent.GROUP_ASSIGN_OWNER;
case 26:
return ChatContactGroupEvent.GROUP_ADD_ADMIN;
case 27:
return ChatContactGroupEvent.GROUP_REMOVE_ADMIN;
case 28:
return ChatContactGroupEvent.GROUP_ADD_MUTE;
case 29:
return ChatContactGroupEvent.GROUP_REMOVE_MUTE;
default:
throw new Error(`not exist this type: ${params}`);
}
}
/**
* The chat connection listener.
*
* For the occasion of onDisconnected during unstable network condition, you
* don't need to reconnect manually, the chat SDK will handle it automatically.
*
* There are only two states: onConnected, onDisconnected.
*
* Note: We recommend not to update UI based on those methods, because this
* method is called on worker thread. If you update UI in those methods, other
* UI errors might be invoked. Also do not insert heavy computation work here,
* which might invoke other listeners to handle this connection event.
*
* Register:
* ```typescript
* let listener = new (class s implements ChatConnectionListener {
* onTokenWillExpire(): void {
* console.log('ConnectScreen.onTokenWillExpire');
* }
* onTokenDidExpire(): void {
* console.log('ConnectScreen.onTokenDidExpire');
* }
* onConnected(): void {
* console.log('ConnectScreen.onConnected');
* }
* onDisconnected(errorCode?: number): void {
* console.log('ConnectScreen.onDisconnected', errorCode);
* }
* })();
* ChatClient.getInstance().addConnectionListener(listener);
* ```
* Unregister:
* ```typescript
* ChatClient.getInstance().removeConnectionListener(listener);
* ```
*/
export interface ChatConnectionListener {
/**
* Occurs when the SDK connects to the chat server successfully.
*/
onConnected(): void;
/**
* Occurs when the SDK disconnect from the chat server.
*
* Note that the logout may not be performed at the bottom level when the SDK is disconnected.
*
* @param errorCode The Error code, see {@link ChatError}
*/
onDisconnected(errorCode?: number): void;
/**
* Occurs when the token has expired.
*/
onTokenWillExpire(): void;
/**
* Occurs when the token is about to expire.
*/
onTokenDidExpire(): void;
}
export interface ChatMultiDeviceListener {
onContactEvent(
event?: ChatContactGroupEvent,
target?: string,
ext?: string
): void;
onGroupEvent(
event?: ChatContactGroupEvent,
target?: string,
usernames?: Array<string>
): void;
}
export interface ChatCustomListener {
onDataReceived(map: Map<string, any>): void;
}
export interface ChatContactEventListener {
/// 被[userName]添加为好友
onContactAdded(userName?: string): void;
/// 被[userName]从好友中删除
onContactDeleted(userName?: string): void;
/// 收到[userName]的好友申请,原因是[reason]
onContactInvited(userName?: string, reason?: string): void;
/// 发出的好友申请被[userName]同意
onFriendRequestAccepted(userName?: string): void;
/// 发出的好友申请被[userName]拒绝
onFriendRequestDeclined(userName?: string): void;
}
export interface ChatConversationListener {
onConversationUpdate(): void;
}
export interface ChatRoomEventListener {
/// id是[roomId],名称是[roomName]的聊天室被销毁
onChatRoomDestroyed(roomId: string, roomName?: string): void;
/// 有用户[participant]加入id是[roomId]的聊天室
onMemberJoinedFromChatRoom(roomId: string, participant: string): void;
/// 有用户[participant]离开id是[roomId],名字是[roomName]的聊天室
onMemberExitedFromChatRoom(
roomId: string,
roomName?: string,
participant?: string
): void;
/// 用户[participant]被id是[roomId],名称[roomName]的聊天室删除
onRemovedFromChatRoom(
roomId: string,
roomName?: string,
participant?: string
): void;
/// @nodoc id是[roomId]的聊天室禁言列表[mutes]有增加
onMuteListAddedFromChatRoom(
roomId: string,
mutes: Array<string>,
expireTime?: string
): void;
/// @nodoc id是[roomId]的聊天室禁言列表[mutes]有减少
onMuteListRemovedFromChatRoom(roomId: string, mutes: Array<string>): void;
/// @nodoc id是[roomId]的聊天室增加id是[admin]管理员
onAdminAddedFromChatRoom(roomId: string, admin: string): void;
/// @nodoc id是[roomId]的聊天室移除id是[admin]管理员
onAdminRemovedFromChatRoom(roomId: string, admin: string): void;
/// @nodoc id是[roomId]的聊天室所有者由[oldOwner]变更为[newOwner]
onOwnerChangedFromChatRoom(
roomId: string,
newOwner: string,
oldOwner: string
): void;
/// @nodoc id是[roomId]的聊天室公告变为[announcement]
onAnnouncementChangedFromChatRoom(roomId: string, announcement: string): void;
/// 有用户被添加到聊天室白名单
onWhiteListAddedFromChatRoom(roomId: string, members: Array<string>): void;
/// 有用户从聊天室白名单被移除
onWhiteListRemovedFromChatRoom(roomId: string, members: Array<string>): void;
/// 聊天室禁言状态发生变化
onAllChatRoomMemberMuteStateChanged(
roomId: string,
isAllMuted: boolean
): void;
}
| 26.951613 | 96 | 0.718432 | 150 | 1 | 26 | 45 | 0 | 0 | 0 | 1 | 69 | 6 | 0 | 54 | 1,969 | 0.023362 | 0 | 0 | 0.003047 | 0 | 0.013889 | 0.958333 | 0.228384 | export enum ChatContactGroupEvent {
CONTACT_REMOVE,
CONTACT_ACCEPT,
CONTACT_DECLINE,
CONTACT_BAN,
CONTACT_ALLOW,
GROUP_CREATE,
GROUP_DESTROY,
GROUP_JOIN,
GROUP_LEAVE,
GROUP_APPLY,
GROUP_APPLY_ACCEPT,
GROUP_APPLY_DECLINE,
GROUP_INVITE,
GROUP_INVITE_ACCEPT,
GROUP_INVITE_DECLINE,
GROUP_KICK,
GROUP_BAN,
GROUP_ALLOW,
GROUP_BLOCK,
GROUP_UNBLOCK,
GROUP_ASSIGN_OWNER,
GROUP_ADD_ADMIN,
GROUP_REMOVE_ADMIN,
GROUP_ADD_MUTE,
GROUP_REMOVE_MUTE,
}
export function ChatContactGroupEventFromNumber(
params
) {
switch (params) {
case 2:
return ChatContactGroupEvent.CONTACT_REMOVE;
case 3:
return ChatContactGroupEvent.CONTACT_ACCEPT;
case 4:
return ChatContactGroupEvent.CONTACT_DECLINE;
case 5:
return ChatContactGroupEvent.CONTACT_BAN;
case 6:
return ChatContactGroupEvent.CONTACT_ALLOW;
case 10:
return ChatContactGroupEvent.GROUP_CREATE;
case 11:
return ChatContactGroupEvent.GROUP_DESTROY;
case 12:
return ChatContactGroupEvent.GROUP_JOIN;
case 13:
return ChatContactGroupEvent.GROUP_LEAVE;
case 14:
return ChatContactGroupEvent.GROUP_APPLY;
case 15:
return ChatContactGroupEvent.GROUP_APPLY_ACCEPT;
case 16:
return ChatContactGroupEvent.GROUP_APPLY_DECLINE;
case 17:
return ChatContactGroupEvent.GROUP_INVITE;
case 18:
return ChatContactGroupEvent.GROUP_INVITE_ACCEPT;
case 19:
return ChatContactGroupEvent.GROUP_INVITE_DECLINE;
case 20:
return ChatContactGroupEvent.GROUP_KICK;
case 21:
return ChatContactGroupEvent.GROUP_BAN;
case 22:
return ChatContactGroupEvent.GROUP_ALLOW;
case 23:
return ChatContactGroupEvent.GROUP_BLOCK;
case 24:
return ChatContactGroupEvent.GROUP_UNBLOCK;
case 25:
return ChatContactGroupEvent.GROUP_ASSIGN_OWNER;
case 26:
return ChatContactGroupEvent.GROUP_ADD_ADMIN;
case 27:
return ChatContactGroupEvent.GROUP_REMOVE_ADMIN;
case 28:
return ChatContactGroupEvent.GROUP_ADD_MUTE;
case 29:
return ChatContactGroupEvent.GROUP_REMOVE_MUTE;
default:
throw new Error(`not exist this type: ${params}`);
}
}
/**
* The chat connection listener.
*
* For the occasion of onDisconnected during unstable network condition, you
* don't need to reconnect manually, the chat SDK will handle it automatically.
*
* There are only two states: onConnected, onDisconnected.
*
* Note: We recommend not to update UI based on those methods, because this
* method is called on worker thread. If you update UI in those methods, other
* UI errors might be invoked. Also do not insert heavy computation work here,
* which might invoke other listeners to handle this connection event.
*
* Register:
* ```typescript
* let listener = new (class s implements ChatConnectionListener {
* onTokenWillExpire(): void {
* console.log('ConnectScreen.onTokenWillExpire');
* }
* onTokenDidExpire(): void {
* console.log('ConnectScreen.onTokenDidExpire');
* }
* onConnected(): void {
* console.log('ConnectScreen.onConnected');
* }
* onDisconnected(errorCode?: number): void {
* console.log('ConnectScreen.onDisconnected', errorCode);
* }
* })();
* ChatClient.getInstance().addConnectionListener(listener);
* ```
* Unregister:
* ```typescript
* ChatClient.getInstance().removeConnectionListener(listener);
* ```
*/
export interface ChatConnectionListener {
/**
* Occurs when the SDK connects to the chat server successfully.
*/
onConnected();
/**
* Occurs when the SDK disconnect from the chat server.
*
* Note that the logout may not be performed at the bottom level when the SDK is disconnected.
*
* @param errorCode The Error code, see {@link ChatError}
*/
onDisconnected(errorCode?);
/**
* Occurs when the token has expired.
*/
onTokenWillExpire();
/**
* Occurs when the token is about to expire.
*/
onTokenDidExpire();
}
export interface ChatMultiDeviceListener {
onContactEvent(
event?,
target?,
ext?
);
onGroupEvent(
event?,
target?,
usernames?
);
}
export interface ChatCustomListener {
onDataReceived(map);
}
export interface ChatContactEventListener {
/// 被[userName]添加为好友
onContactAdded(userName?);
/// 被[userName]从好友中删除
onContactDeleted(userName?);
/// 收到[userName]的好友申请,原因是[reason]
onContactInvited(userName?, reason?);
/// 发出的好友申请被[userName]同意
onFriendRequestAccepted(userName?);
/// 发出的好友申请被[userName]拒绝
onFriendRequestDeclined(userName?);
}
export interface ChatConversationListener {
onConversationUpdate();
}
export interface ChatRoomEventListener {
/// id是[roomId],名称是[roomName]的聊天室被销毁
onChatRoomDestroyed(roomId, roomName?);
/// 有用户[participant]加入id是[roomId]的聊天室
onMemberJoinedFromChatRoom(roomId, participant);
/// 有用户[participant]离开id是[roomId],名字是[roomName]的聊天室
onMemberExitedFromChatRoom(
roomId,
roomName?,
participant?
);
/// 用户[participant]被id是[roomId],名称[roomName]的聊天室删除
onRemovedFromChatRoom(
roomId,
roomName?,
participant?
);
/// @nodoc id是[roomId]的聊天室禁言列表[mutes]有增加
onMuteListAddedFromChatRoom(
roomId,
mutes,
expireTime?
);
/// @nodoc id是[roomId]的聊天室禁言列表[mutes]有减少
onMuteListRemovedFromChatRoom(roomId, mutes);
/// @nodoc id是[roomId]的聊天室增加id是[admin]管理员
onAdminAddedFromChatRoom(roomId, admin);
/// @nodoc id是[roomId]的聊天室移除id是[admin]管理员
onAdminRemovedFromChatRoom(roomId, admin);
/// @nodoc id是[roomId]的聊天室所有者由[oldOwner]变更为[newOwner]
onOwnerChangedFromChatRoom(
roomId,
newOwner,
oldOwner
);
/// @nodoc id是[roomId]的聊天室公告变为[announcement]
onAnnouncementChangedFromChatRoom(roomId, announcement);
/// 有用户被添加到聊天室白名单
onWhiteListAddedFromChatRoom(roomId, members);
/// 有用户从聊天室白名单被移除
onWhiteListRemovedFromChatRoom(roomId, members);
/// 聊天室禁言状态发生变化
onAllChatRoomMemberMuteStateChanged(
roomId,
isAllMuted
);
}
|
e520f93da68052f73197a93027b9e1fc2ad3b793 | 2,619 | ts | TypeScript | src/modules/generate/tmpl.ts | eolinker/eoapi-core | 54da7dce148383dff757745d0fd4605579a74e27 | [
"Apache-2.0"
] | 1 | 2022-03-05T15:50:52.000Z | 2022-03-05T15:50:52.000Z | src/modules/generate/tmpl.ts | eolinker/eoapi-core | 54da7dce148383dff757745d0fd4605579a74e27 | [
"Apache-2.0"
] | null | null | null | src/modules/generate/tmpl.ts | eolinker/eoapi-core | 54da7dce148383dff757745d0fd4605579a74e27 | [
"Apache-2.0"
] | null | null | null | const template = {
genIndex: (name: string) =>
`module.exports = () => {
return {
id: '${name}',
name: '${name}',
core: '1.x',
version: '1.0.0',
description: '${name} module of EOAPI-Core',
package: 'Community',
cli__core(eo: any) {
eo.logger.info(\`run cli__core [\${this.name} \${this.version}]\`);
eo.command
.command('test')
.alias('t')
.argument('<hook>', 'hook name')
.description('display hooks description.')
.action((hook: string) => {
eo.logger.info(\`help of hook name \${hook}\`);
});
return eo;
},
app__db_load(eo: any) {
console.log('app__db_load');
eo.output.push('test');
return eo;
}
}
}`,
genPackageJSON: (name: string) =>
`{
"name": "${name}",
"version": "1.0.0",
"description": "A ${name} module of EOAPI-Core.",
"main": "dist/index.js",
"scripts": {
"test": "echo \\"Error: no test specified\\"",
"build": "tsc"
},
"author": "Eolink",
"license": "Apache-2.0 License",
"devDependencies": {
"@types/node": "^17.0.10"
}
}`,
genNpmignore: () =>
`src/
node_modules/
package-lock.json
tsconfig.json
.vscode/
.travis.yml
.idea`,
genGitignore: () =>
`node_modules/
dist/
.DS_Store
.idea
.vscode/`,
genTsconfig: () =>
`{
"compilerOptions": {
"target": "es5",
"module": "commonjs",
"declaration": true,
"rootDir": "src",
"outDir": "dist",
"esModuleInterop": true,
"forceConsistentCasingInFileNames": true,
"strict": true,
"skipLibCheck": true
},
"exclude": ["node_modules", "dist"]
}`,
genReadme: (name: string) =>
`# ${name}
This is a module of EOAPI-Core.
`,
genNpmpublish: () =>
`# This workflow will run tests using node and then publish a package to GitHub Packages when a release is created
# For more information see: https://help.github.com/actions/language-and-framework-guides/publishing-nodejs-packages
name: Node.js Package
on:
release:
types: [created]
jobs:
build:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v2
- uses: actions/setup-node@v2
with:
node-version: 16
- run: npm ci
- run: npm test
publish-npm:
needs: build
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v2
- uses: actions/setup-node@v2
with:
node-version: 16
registry-url: https://registry.npmjs.org/
- run: npm ci
- run: npm run build
- run: npm publish
env:
NODE_AUTH_TOKEN: \${{secrets.npm_token}}
`
}
export default template;
| 22.008403 | 116 | 0.575029 | 112 | 7 | 0 | 3 | 1 | 0 | 0 | 0 | 3 | 0 | 0 | 14.571429 | 832 | 0.012019 | 0.001202 | 0 | 0 | 0 | 0 | 0.272727 | 0.201754 | const template = {
genIndex: (name) =>
`module.exports = () => {
return {
id: '${name}',
name: '${name}',
core: '1.x',
version: '1.0.0',
description: '${name} module of EOAPI-Core',
package: 'Community',
cli__core(eo: any) {
eo.logger.info(\`run cli__core [\${this.name} \${this.version}]\`);
eo.command
.command('test')
.alias('t')
.argument('<hook>', 'hook name')
.description('display hooks description.')
.action((hook: string) => {
eo.logger.info(\`help of hook name \${hook}\`);
});
return eo;
},
app__db_load(eo: any) {
console.log('app__db_load');
eo.output.push('test');
return eo;
}
}
}`,
genPackageJSON: (name) =>
`{
"name": "${name}",
"version": "1.0.0",
"description": "A ${name} module of EOAPI-Core.",
"main": "dist/index.js",
"scripts": {
"test": "echo \\"Error: no test specified\\"",
"build": "tsc"
},
"author": "Eolink",
"license": "Apache-2.0 License",
"devDependencies": {
"@types/node": "^17.0.10"
}
}`,
genNpmignore: () =>
`src/
node_modules/
package-lock.json
tsconfig.json
.vscode/
.travis.yml
.idea`,
genGitignore: () =>
`node_modules/
dist/
.DS_Store
.idea
.vscode/`,
genTsconfig: () =>
`{
"compilerOptions": {
"target": "es5",
"module": "commonjs",
"declaration": true,
"rootDir": "src",
"outDir": "dist",
"esModuleInterop": true,
"forceConsistentCasingInFileNames": true,
"strict": true,
"skipLibCheck": true
},
"exclude": ["node_modules", "dist"]
}`,
genReadme: (name) =>
`# ${name}
This is a module of EOAPI-Core.
`,
genNpmpublish: () =>
`# This workflow will run tests using node and then publish a package to GitHub Packages when a release is created
# For more information see: https://help.github.com/actions/language-and-framework-guides/publishing-nodejs-packages
name: Node.js Package
on:
release:
types: [created]
jobs:
build:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v2
- uses: actions/setup-node@v2
with:
node-version: 16
- run: npm ci
- run: npm test
publish-npm:
needs: build
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v2
- uses: actions/setup-node@v2
with:
node-version: 16
registry-url: https://registry.npmjs.org/
- run: npm ci
- run: npm run build
- run: npm publish
env:
NODE_AUTH_TOKEN: \${{secrets.npm_token}}
`
}
export default template;
|
e554b8385c960287feaa53ddaf71ac2cedadc0f5 | 1,883 | ts | TypeScript | solutions/day03.ts | GiyoMoon/aoc2021 | 83d7e9018ed3b628353bc9a0a37b70a1462ecd74 | [
"Unlicense"
] | null | null | null | solutions/day03.ts | GiyoMoon/aoc2021 | 83d7e9018ed3b628353bc9a0a37b70a1462ecd74 | [
"Unlicense"
] | 1 | 2022-02-03T11:04:17.000Z | 2022-02-03T11:04:17.000Z | solutions/day03.ts | GiyoMoon/aoc2021 | 83d7e9018ed3b628353bc9a0a37b70a1462ecd74 | [
"Unlicense"
] | null | null | null | export default class Day3 {
private _binaryInput: string[];
public solve(input: string): { part1: any, part2: any; } {
this._binaryInput = input.split('\n');
// part 1
let bitCounts = new Array(this._binaryInput[0].length).fill(0);
this._binaryInput.forEach((bit) => {
const dArray = bit.split('');
dArray.forEach((bit, i) => {
if (bit === '1') {
bitCounts[i] += 1;
};
});
});
const inputCount = this._binaryInput.length;
let gamma = '';
let epsilon = '';
bitCounts.forEach((b) => {
if (b >= inputCount / 2) {
gamma += '1';
epsilon += '0';
} else {
gamma += '0';
epsilon += '1';
}
});
const part1Result = parseInt(gamma, 2) * parseInt(epsilon, 2);
// part 2
const generatorRating = this._getRating(1);
const scrubberRating = this._getRating(0);
const part2Result = parseInt(generatorRating, 2) * parseInt(scrubberRating, 2);
return { part1: part1Result, part2: part2Result };
}
private _getRating(lookingFor: number) {
let filteredInput = [...this._binaryInput];
for (let i = 0; filteredInput.length > 1; i++) {
const mostCommon = this._getMostCommonBit(filteredInput, i, lookingFor);
filteredInput = filteredInput.filter(v => {
const vArray = v.split('');
return vArray[i] === mostCommon;
});
}
return filteredInput[0];
}
private _getMostCommonBit(numbers: string[], index: number, lookingFor: number) {
const totalNumbers = numbers.length;
let bits = 0;
numbers.forEach(n => {
if (n[index] === '1') {
bits++;
};
});
let number;
if (lookingFor === 1) {
number = bits >= totalNumbers / 2 ? 1 : 0;
} else {
number = bits >= totalNumbers / 2 ? 0 : 1;
}
return number.toString();
}
}
| 25.445946 | 83 | 0.560807 | 59 | 8 | 0 | 11 | 16 | 1 | 2 | 2 | 6 | 1 | 0 | 8.875 | 543 | 0.034991 | 0.029466 | 0.001842 | 0.001842 | 0 | 0.055556 | 0.166667 | 0.350608 | export default class Day3 {
private _binaryInput;
public solve(input) {
this._binaryInput = input.split('\n');
// part 1
let bitCounts = new Array(this._binaryInput[0].length).fill(0);
this._binaryInput.forEach((bit) => {
const dArray = bit.split('');
dArray.forEach((bit, i) => {
if (bit === '1') {
bitCounts[i] += 1;
};
});
});
const inputCount = this._binaryInput.length;
let gamma = '';
let epsilon = '';
bitCounts.forEach((b) => {
if (b >= inputCount / 2) {
gamma += '1';
epsilon += '0';
} else {
gamma += '0';
epsilon += '1';
}
});
const part1Result = parseInt(gamma, 2) * parseInt(epsilon, 2);
// part 2
const generatorRating = this._getRating(1);
const scrubberRating = this._getRating(0);
const part2Result = parseInt(generatorRating, 2) * parseInt(scrubberRating, 2);
return { part1: part1Result, part2: part2Result };
}
private _getRating(lookingFor) {
let filteredInput = [...this._binaryInput];
for (let i = 0; filteredInput.length > 1; i++) {
const mostCommon = this._getMostCommonBit(filteredInput, i, lookingFor);
filteredInput = filteredInput.filter(v => {
const vArray = v.split('');
return vArray[i] === mostCommon;
});
}
return filteredInput[0];
}
private _getMostCommonBit(numbers, index, lookingFor) {
const totalNumbers = numbers.length;
let bits = 0;
numbers.forEach(n => {
if (n[index] === '1') {
bits++;
};
});
let number;
if (lookingFor === 1) {
number = bits >= totalNumbers / 2 ? 1 : 0;
} else {
number = bits >= totalNumbers / 2 ? 0 : 1;
}
return number.toString();
}
}
|
e5a28efe92e9884dc408328a4c42c242caaf43b3 | 1,839 | ts | TypeScript | lib/util/flatten.ts | xania/view | c894d5a7e9174e84bb5c18c4dc615d58eb1b77b7 | [
"MIT"
] | 8 | 2022-01-23T01:20:55.000Z | 2022-03-06T17:43:06.000Z | lib/util/flatten.ts | xania/view | c894d5a7e9174e84bb5c18c4dc615d58eb1b77b7 | [
"MIT"
] | 1 | 2022-03-06T17:47:27.000Z | 2022-03-31T13:26:59.000Z | lib/util/flatten.ts | xania/view | c894d5a7e9174e84bb5c18c4dc615d58eb1b77b7 | [
"MIT"
] | 1 | 2022-03-24T13:46:13.000Z | 2022-03-24T13:46:13.000Z | export default function flatten<T>(
tree: ArrayLike<T>,
childrenFn: (node: T) => ArrayLike<T> | undefined
) {
const retval: T[] = [];
if (!tree) return retval;
type StackType = T | StackType[] | undefined;
const stack: StackType[] = [];
for (let i = 0; i < tree.length; i++) {
stack[i] = tree[i];
}
while (stack.length > 0) {
var curr = stack.pop() as StackType;
if (Array.isArray(curr)) {
let length = curr.length;
while (length--) {
stack.push(curr[length]);
}
} else if (curr !== null && curr !== undefined) {
const children = childrenFn(curr);
if (children)
for (let i = children.length - 1; i >= 0; i--) {
stack[stack.length] = children[i];
}
retval.push(curr);
}
}
return retval;
}
export function bottomUp<T>(
tree: ArrayLike<T>,
childrenFn: (node: T) => ArrayLike<T> | undefined
) {
const visited = new Set<T>();
const retval: T[] = [];
if (!tree) return retval;
type StackType = T | StackType[] | undefined;
const stack: StackType[] = [];
for (let i = 0; i < tree.length; i++) {
stack[i] = tree[i];
}
while (stack.length > 0) {
var curr = stack.pop() as StackType;
if (Array.isArray(curr)) {
let length = curr.length;
while (length--) {
stack.push(curr[length]);
}
} else if (curr !== null && curr !== undefined) {
if (visited.has(curr)) {
visited.delete(curr);
retval.push(curr);
} else {
const children = childrenFn(curr);
if (children) {
visited.add(curr);
stack.push(curr);
for (let i = children.length - 1; i >= 0; i--) {
stack[stack.length] = children[i];
}
} else {
retval.push(curr);
}
}
}
}
return retval;
}
| 25.541667 | 58 | 0.529092 | 68 | 2 | 0 | 4 | 15 | 0 | 0 | 0 | 0 | 2 | 2 | 29 | 545 | 0.011009 | 0.027523 | 0 | 0.00367 | 0.00367 | 0 | 0 | 0.291196 | export default function flatten<T>(
tree,
childrenFn
) {
const retval = [];
if (!tree) return retval;
type StackType = T | StackType[] | undefined;
const stack = [];
for (let i = 0; i < tree.length; i++) {
stack[i] = tree[i];
}
while (stack.length > 0) {
var curr = stack.pop() as StackType;
if (Array.isArray(curr)) {
let length = curr.length;
while (length--) {
stack.push(curr[length]);
}
} else if (curr !== null && curr !== undefined) {
const children = childrenFn(curr);
if (children)
for (let i = children.length - 1; i >= 0; i--) {
stack[stack.length] = children[i];
}
retval.push(curr);
}
}
return retval;
}
export function bottomUp<T>(
tree,
childrenFn
) {
const visited = new Set<T>();
const retval = [];
if (!tree) return retval;
type StackType = T | StackType[] | undefined;
const stack = [];
for (let i = 0; i < tree.length; i++) {
stack[i] = tree[i];
}
while (stack.length > 0) {
var curr = stack.pop() as StackType;
if (Array.isArray(curr)) {
let length = curr.length;
while (length--) {
stack.push(curr[length]);
}
} else if (curr !== null && curr !== undefined) {
if (visited.has(curr)) {
visited.delete(curr);
retval.push(curr);
} else {
const children = childrenFn(curr);
if (children) {
visited.add(curr);
stack.push(curr);
for (let i = children.length - 1; i >= 0; i--) {
stack[stack.length] = children[i];
}
} else {
retval.push(curr);
}
}
}
}
return retval;
}
|
e5c7e376276a256d46d7cbc985f9e822b3f837bf | 3,789 | ts | TypeScript | src/Exports/pokemonTypeChart.ts | Zamur650/tapris | ca14e3067569f46e9befb926c629ce9497f80e98 | [
"MIT"
] | null | null | null | src/Exports/pokemonTypeChart.ts | Zamur650/tapris | ca14e3067569f46e9befb926c629ce9497f80e98 | [
"MIT"
] | 4 | 2022-01-18T00:38:15.000Z | 2022-03-22T05:01:09.000Z | src/Exports/pokemonTypeChart.ts | Zamur650/tapris | ca14e3067569f46e9befb926c629ce9497f80e98 | [
"MIT"
] | null | null | null | export interface TypeChart {
name: PokemonType;
2: PokemonType[];
0.5: PokemonType[];
0: PokemonType[];
}
export type PokemonType =
| "Normal"
| "Fighting"
| "Flying"
| "Poison"
| "Ground"
| "Rock"
| "Bug"
| "Ghost"
| "Steel"
| "Fire"
| "Water"
| "Grass"
| "Electric"
| "Psychic"
| "Ice"
| "Dragon"
| "Dark"
| "Fairy";
export interface Weaknesses {
name: PokemonType;
scale: number;
}
export const typeChart: TypeChart[] = [
{
name: "Normal",
2: ["Fighting"],
0.5: [],
0: ["Ghost"]
},
{
name: "Fighting",
2: ["Flying", "Psychic", "Fairy"],
0.5: ["Rock", "Bug", "Dark"],
0: []
},
{
name: "Flying",
2: ["Rock", "Electric", "Ice"],
0.5: ["Fighting", "Bug", "Grass"],
0: ["Ground"]
},
{
name: "Poison",
2: ["Ground", "Psychic"],
0.5: ["Fighting", "Poison", "Bug", "Grass", "Fairy"],
0: []
},
{
name: "Ground",
2: ["Water", "Grass", "Ice"],
0.5: ["Poison", "Rock"],
0: ["Electric"]
},
{
name: "Rock",
2: ["Fighting", "Ground", "Steel", "Water", "Grass"],
0.5: ["Normal", "Flying", "Poison", "Fire"],
0: []
},
{
name: "Bug",
2: ["Flying", "Rock", "Fire"],
0.5: ["Fighting", "Ground", "Grass"],
0: []
},
{
name: "Ghost",
2: ["Ghost", "Dark"],
0.5: ["Poison", "Bug"],
0: ["Normal", "Fighting"]
},
{
name: "Steel",
2: ["Fighting", "Ground", "Fire"],
0.5: [
"Normal",
"Flying",
"Poison",
"Rock",
"Bug",
"Steel",
"Grass",
"Psychic",
"Ice",
"Dragon",
"Fairy"
],
0: ["Poison"]
},
{
name: "Fire",
2: ["Ground", "Rock", "Water"],
0.5: ["Bug", "Steel", "Fire", "Grass", "Ice", "Fairy"],
0: []
},
{
name: "Water",
2: ["Grass", "Electric"],
0.5: ["Steel", "Fire", "Water", "Ice"],
0: []
},
{
name: "Grass",
2: ["Flying", "Poison", "Bug", "Fire", "Ice"],
0.5: ["Ground", "Water", "Grass", "Electric"],
0: []
},
{
name: "Electric",
2: ["Ground"],
0.5: ["Flying", "Steel", "Electric"],
0: []
},
{
name: "Psychic",
2: ["Bug", "Ghost", "Dark"],
0.5: ["Fighting", "Psychic"],
0: []
},
{
name: "Ice",
2: ["Fighting", "Rock", "Steel", "Fire"],
0.5: ["Ice"],
0: []
},
{
name: "Dragon",
2: ["Ice", "Dragon", "Fairy"],
0.5: ["Fire", "Water", "Grass", "Electric"],
0: []
},
{
name: "Dark",
2: ["Fighting", "Bug", "Fairy"],
0.5: ["Ghost", "Psychic", "Dark"],
0: []
},
{
name: "Fairy",
2: ["Poison", "Steel"],
0.5: ["Fighting", "Bug", "Dragon", "Dark"],
0: []
}
];
export function calcWeaknesses(pokemonTypes: PokemonType[]) {
let weaknesses: Weaknesses[] = [];
pokemonTypes.forEach((pokemonType: PokemonType) => {
typeChart.forEach((typeTypeChart: TypeChart) => {
if (typeTypeChart.name != pokemonType) return;
typeTypeChart["2"].forEach((type: PokemonType) => {
let existed = false;
for (let i = 0; i < weaknesses.length; i++) {
if (weaknesses[i].name == type) {
weaknesses[i].scale *= 2;
existed = true;
}
}
if (!existed) weaknesses = [...weaknesses, { name: type, scale: 2 }];
});
typeTypeChart["0.5"].forEach((type: PokemonType) => {
let existed = false;
for (let i = 0; i < weaknesses.length; i++) {
if (weaknesses[i].name == type) {
weaknesses[i].scale *= 0.5;
existed = true;
}
}
if (!existed) weaknesses = [...weaknesses, { name: type, scale: 0.5 }];
});
typeTypeChart["0"].forEach((type: PokemonType) => {
let existed = false;
for (let i = 0; i < weaknesses.length; i++) {
if (weaknesses[i].name == type) {
weaknesses[i].scale *= 0;
existed = true;
}
}
if (!existed) weaknesses = [...weaknesses, { name: type, scale: 0 }];
});
});
});
weaknesses = weaknesses.filter((v) => v.scale != 1);
return weaknesses;
}
| 17.957346 | 75 | 0.501452 | 191 | 7 | 0 | 7 | 8 | 6 | 0 | 0 | 1 | 3 | 0 | 18.142857 | 1,544 | 0.009067 | 0.005181 | 0.003886 | 0.001943 | 0 | 0 | 0.035714 | 0.211306 | export interface TypeChart {
name;
2;
0.5;
0;
}
export type PokemonType =
| "Normal"
| "Fighting"
| "Flying"
| "Poison"
| "Ground"
| "Rock"
| "Bug"
| "Ghost"
| "Steel"
| "Fire"
| "Water"
| "Grass"
| "Electric"
| "Psychic"
| "Ice"
| "Dragon"
| "Dark"
| "Fairy";
export interface Weaknesses {
name;
scale;
}
export const typeChart = [
{
name: "Normal",
2: ["Fighting"],
0.5: [],
0: ["Ghost"]
},
{
name: "Fighting",
2: ["Flying", "Psychic", "Fairy"],
0.5: ["Rock", "Bug", "Dark"],
0: []
},
{
name: "Flying",
2: ["Rock", "Electric", "Ice"],
0.5: ["Fighting", "Bug", "Grass"],
0: ["Ground"]
},
{
name: "Poison",
2: ["Ground", "Psychic"],
0.5: ["Fighting", "Poison", "Bug", "Grass", "Fairy"],
0: []
},
{
name: "Ground",
2: ["Water", "Grass", "Ice"],
0.5: ["Poison", "Rock"],
0: ["Electric"]
},
{
name: "Rock",
2: ["Fighting", "Ground", "Steel", "Water", "Grass"],
0.5: ["Normal", "Flying", "Poison", "Fire"],
0: []
},
{
name: "Bug",
2: ["Flying", "Rock", "Fire"],
0.5: ["Fighting", "Ground", "Grass"],
0: []
},
{
name: "Ghost",
2: ["Ghost", "Dark"],
0.5: ["Poison", "Bug"],
0: ["Normal", "Fighting"]
},
{
name: "Steel",
2: ["Fighting", "Ground", "Fire"],
0.5: [
"Normal",
"Flying",
"Poison",
"Rock",
"Bug",
"Steel",
"Grass",
"Psychic",
"Ice",
"Dragon",
"Fairy"
],
0: ["Poison"]
},
{
name: "Fire",
2: ["Ground", "Rock", "Water"],
0.5: ["Bug", "Steel", "Fire", "Grass", "Ice", "Fairy"],
0: []
},
{
name: "Water",
2: ["Grass", "Electric"],
0.5: ["Steel", "Fire", "Water", "Ice"],
0: []
},
{
name: "Grass",
2: ["Flying", "Poison", "Bug", "Fire", "Ice"],
0.5: ["Ground", "Water", "Grass", "Electric"],
0: []
},
{
name: "Electric",
2: ["Ground"],
0.5: ["Flying", "Steel", "Electric"],
0: []
},
{
name: "Psychic",
2: ["Bug", "Ghost", "Dark"],
0.5: ["Fighting", "Psychic"],
0: []
},
{
name: "Ice",
2: ["Fighting", "Rock", "Steel", "Fire"],
0.5: ["Ice"],
0: []
},
{
name: "Dragon",
2: ["Ice", "Dragon", "Fairy"],
0.5: ["Fire", "Water", "Grass", "Electric"],
0: []
},
{
name: "Dark",
2: ["Fighting", "Bug", "Fairy"],
0.5: ["Ghost", "Psychic", "Dark"],
0: []
},
{
name: "Fairy",
2: ["Poison", "Steel"],
0.5: ["Fighting", "Bug", "Dragon", "Dark"],
0: []
}
];
export function calcWeaknesses(pokemonTypes) {
let weaknesses = [];
pokemonTypes.forEach((pokemonType) => {
typeChart.forEach((typeTypeChart) => {
if (typeTypeChart.name != pokemonType) return;
typeTypeChart["2"].forEach((type) => {
let existed = false;
for (let i = 0; i < weaknesses.length; i++) {
if (weaknesses[i].name == type) {
weaknesses[i].scale *= 2;
existed = true;
}
}
if (!existed) weaknesses = [...weaknesses, { name: type, scale: 2 }];
});
typeTypeChart["0.5"].forEach((type) => {
let existed = false;
for (let i = 0; i < weaknesses.length; i++) {
if (weaknesses[i].name == type) {
weaknesses[i].scale *= 0.5;
existed = true;
}
}
if (!existed) weaknesses = [...weaknesses, { name: type, scale: 0.5 }];
});
typeTypeChart["0"].forEach((type) => {
let existed = false;
for (let i = 0; i < weaknesses.length; i++) {
if (weaknesses[i].name == type) {
weaknesses[i].scale *= 0;
existed = true;
}
}
if (!existed) weaknesses = [...weaknesses, { name: type, scale: 0 }];
});
});
});
weaknesses = weaknesses.filter((v) => v.scale != 1);
return weaknesses;
}
|
e5e071d82c234e126b482cc77c6bdea7b5f5be72 | 3,849 | ts | TypeScript | src/type.ts | furious-commander/fury | 8a018f85fd686efab5462019a7667ad752ebc69f | [
"MIT"
] | null | null | null | src/type.ts | furious-commander/fury | 8a018f85fd686efab5462019a7667ad752ebc69f | [
"MIT"
] | 3 | 2022-03-01T14:48:06.000Z | 2022-03-04T07:55:06.000Z | src/type.ts | furious-commander/madlad | 8a018f85fd686efab5462019a7667ad752ebc69f | [
"MIT"
] | null | null | null | export type CommandConstructor = { new (): LeafCommand | GroupCommand }
interface BaseCommand {
readonly name: string
readonly description: string
readonly alias?: string
}
export interface GroupCommand extends BaseCommand {
subCommandClasses: CommandConstructor[]
}
export interface LeafCommand extends BaseCommand {
run(): void | Promise<void>
}
export interface Argument<T = unknown> {
key: string
description: string
type?: 'string' | 'boolean' | 'number' | 'bigint' | 'hex-string'
required?: boolean | { when: string } | { unless: string }
conflicts?: string
default?: T
defaultDescription?: string
alias?: string
envKey?: string
minimum?: number | bigint
maximum?: number | bigint
length?: number
minimumLength?: number
maximumLength?: number
oddLength?: boolean
noErrors?: boolean
autocompletePath?: boolean
handler?: () => void
global?: boolean
array?: boolean
}
function prependName(group: Group, name: string) {
group.fullPath = name + ' ' + group.fullPath
group.depth++
for (const child of group.groups) {
prependName(child, name)
}
for (const child of group.commands) {
child.depth++
child.fullPath = name + ' ' + child.fullPath
}
}
export class Group {
public key: string
public description: string
public groups: Group[]
public commands: Command[]
public fullPath: string
public depth: number
constructor(key: string, description: string) {
this.key = key
this.description = description
this.groups = []
this.commands = []
this.fullPath = key
this.depth = 0
}
public withGroup(group: Group): Group {
this.groups.push(group)
prependName(group, this.fullPath)
return this
}
public withCommand(command: Command): Group {
this.commands.push(command)
command.depth++
command.fullPath = this.key + ' ' + command.fullPath
return this
}
}
export class Command {
public key: string
public description: string
public sibling?: string
public alias?: string
public options: Argument[]
public arguments: Argument[]
public fullPath: string
public depth: number
public leafCommand: LeafCommand
constructor(
key: string,
description: string,
leafCommand: LeafCommand,
settings?: { sibling?: string; alias?: string },
) {
this.key = key
this.description = description
this.leafCommand = leafCommand
if (settings) {
this.sibling = settings.sibling
this.alias = settings.alias
}
this.options = []
this.arguments = []
this.fullPath = key
this.depth = 0
}
withOption(x: Argument): Command {
this.options.push(x)
return this
}
withPositional(x: Argument): Command {
this.arguments.push(x)
return this
}
}
export type ParsedCommand = { command: Command; arguments: Record<string, unknown>; options: Record<string, unknown> }
export interface Context {
exitReason?: string
command?: Command | undefined
group?: Group | undefined
options: Record<string, unknown>
arguments: Record<string, unknown>
sourcemap: Record<string, 'default' | 'env' | 'explicit'>
sibling?: ParsedCommand
argumentIndex: number
}
export type ParsedContext = Context & { command: Command }
export interface Application {
name: string
command: string
version: string
description: string
}
export interface Parser {
suggest(line: string, offset: number, trailing: string): Promise<string[]>
parse(argv: string[]): Promise<string | Context | { exitReason: string }>
addGroup(group: Group): void
addCommand(command: Command): void
addGlobalOption(option: Argument): void
}
export interface Printer {
print(text: string): void
printError(text: string): void
printHeading(text: string): void
formatDim(text: string): string
formatImportant(text: string): string
}
| 23.327273 | 118 | 0.691089 | 141 | 7 | 11 | 24 | 0 | 54 | 1 | 0 | 78 | 13 | 0 | 5.285714 | 950 | 0.032632 | 0 | 0.056842 | 0.013684 | 0 | 0 | 0.8125 | 0.267686 | export type CommandConstructor = { new () }
interface BaseCommand {
readonly name
readonly description
readonly alias?
}
export interface GroupCommand extends BaseCommand {
subCommandClasses
}
export interface LeafCommand extends BaseCommand {
run()
}
export interface Argument<T = unknown> {
key
description
type?
required?
conflicts?
default?
defaultDescription?
alias?
envKey?
minimum?
maximum?
length?
minimumLength?
maximumLength?
oddLength?
noErrors?
autocompletePath?
handler?
global?
array?
}
/* Example usages of 'prependName' are shown below:
prependName(child, name);
prependName(group, this.fullPath);
*/
function prependName(group, name) {
group.fullPath = name + ' ' + group.fullPath
group.depth++
for (const child of group.groups) {
prependName(child, name)
}
for (const child of group.commands) {
child.depth++
child.fullPath = name + ' ' + child.fullPath
}
}
export class Group {
public key
public description
public groups
public commands
public fullPath
public depth
constructor(key, description) {
this.key = key
this.description = description
this.groups = []
this.commands = []
this.fullPath = key
this.depth = 0
}
public withGroup(group) {
this.groups.push(group)
prependName(group, this.fullPath)
return this
}
public withCommand(command) {
this.commands.push(command)
command.depth++
command.fullPath = this.key + ' ' + command.fullPath
return this
}
}
export class Command {
public key
public description
public sibling?
public alias?
public options
public arguments
public fullPath
public depth
public leafCommand
constructor(
key,
description,
leafCommand,
settings?,
) {
this.key = key
this.description = description
this.leafCommand = leafCommand
if (settings) {
this.sibling = settings.sibling
this.alias = settings.alias
}
this.options = []
this.arguments = []
this.fullPath = key
this.depth = 0
}
withOption(x) {
this.options.push(x)
return this
}
withPositional(x) {
this.arguments.push(x)
return this
}
}
export type ParsedCommand = { command; arguments; options }
export interface Context {
exitReason?
command?
group?
options
arguments
sourcemap
sibling?
argumentIndex
}
export type ParsedContext = Context & { command }
export interface Application {
name
command
version
description
}
export interface Parser {
suggest(line, offset, trailing)
parse(argv)
addGroup(group)
addCommand(command)
addGlobalOption(option)
}
export interface Printer {
print(text)
printError(text)
printHeading(text)
formatDim(text)
formatImportant(text)
}
|
f013c7a4d0f00346413e3f2f920efdd1b87d2338 | 1,726 | ts | TypeScript | src/utils/execution.ts | menduz/old-tiny-clojure | f3aa27ccfa48535e0d926cc63119c1f07781730e | [
"Apache-2.0"
] | null | null | null | src/utils/execution.ts | menduz/old-tiny-clojure | f3aa27ccfa48535e0d926cc63119c1f07781730e | [
"Apache-2.0"
] | 1 | 2022-01-22T08:49:02.000Z | 2022-01-22T08:49:02.000Z | src/utils/execution.ts | menduz/old-tiny-clojure | f3aa27ccfa48535e0d926cc63119c1f07781730e | [
"Apache-2.0"
] | null | null | null | export function readString(memory: ArrayBuffer, offset: number) {
const dv = new DataView(memory, offset);
let len = dv.getUint32(0, true);
if (len === 0) {
return '';
}
let currentOffset = 4;
len += 4;
const sb: string[] = [];
while (currentOffset < len) {
const r = dv.getUint16(currentOffset, true);
sb.push(String.fromCharCode(r));
currentOffset += 2;
}
return sb.join('');
}
export function readBytes(memory: ArrayBuffer, offset: number) {
const dv = new DataView(memory, offset);
let len = dv.getUint32(0, true);
if (len === 0) return [];
let currentOffset = 4;
len += 4;
const sb: number[] = [];
while (currentOffset < len) {
const r = dv.getUint8(currentOffset);
sb.push(r);
currentOffset += 1;
}
return sb;
}
const BLOCK_SIZE = 16;
const DUMP_LIMIT = 1024 * 64;
function padStart8(str: string) {
return ('x00000000' + str).substr(-8);
}
function padStart2(str: string) {
return ('x00' + str).substr(-2);
}
export function hexDump(memory: ArrayBuffer, max = DUMP_LIMIT, start = 0) {
const buffer = new Uint8Array(memory);
let lines = [];
for (let i = start; i < buffer.byteLength && i < max; i += BLOCK_SIZE) {
let address = padStart8(i.toString(16)); // address
let hexArray = [];
let asciiArray = [];
for (let b = 0; b < BLOCK_SIZE; b += 1) {
const value = buffer[i + b];
hexArray.push(padStart2(value.toString(16)));
asciiArray.push(value >= 0x20 && value < 0x7f ? String.fromCharCode(value) : '.');
}
let hexString = hexArray.join(' ');
let asciiString = asciiArray.join('');
lines.push(`${address} ${hexString} |${asciiString}|`);
}
return lines.join('\n');
}
| 22.128205 | 88 | 0.61066 | 56 | 5 | 0 | 9 | 22 | 0 | 2 | 0 | 6 | 0 | 0 | 8.8 | 561 | 0.024955 | 0.039216 | 0 | 0 | 0 | 0 | 0.166667 | 0.356889 | export function readString(memory, offset) {
const dv = new DataView(memory, offset);
let len = dv.getUint32(0, true);
if (len === 0) {
return '';
}
let currentOffset = 4;
len += 4;
const sb = [];
while (currentOffset < len) {
const r = dv.getUint16(currentOffset, true);
sb.push(String.fromCharCode(r));
currentOffset += 2;
}
return sb.join('');
}
export function readBytes(memory, offset) {
const dv = new DataView(memory, offset);
let len = dv.getUint32(0, true);
if (len === 0) return [];
let currentOffset = 4;
len += 4;
const sb = [];
while (currentOffset < len) {
const r = dv.getUint8(currentOffset);
sb.push(r);
currentOffset += 1;
}
return sb;
}
const BLOCK_SIZE = 16;
const DUMP_LIMIT = 1024 * 64;
/* Example usages of 'padStart8' are shown below:
padStart8(i.toString(16));
*/
function padStart8(str) {
return ('x00000000' + str).substr(-8);
}
/* Example usages of 'padStart2' are shown below:
hexArray.push(padStart2(value.toString(16)));
*/
function padStart2(str) {
return ('x00' + str).substr(-2);
}
export function hexDump(memory, max = DUMP_LIMIT, start = 0) {
const buffer = new Uint8Array(memory);
let lines = [];
for (let i = start; i < buffer.byteLength && i < max; i += BLOCK_SIZE) {
let address = padStart8(i.toString(16)); // address
let hexArray = [];
let asciiArray = [];
for (let b = 0; b < BLOCK_SIZE; b += 1) {
const value = buffer[i + b];
hexArray.push(padStart2(value.toString(16)));
asciiArray.push(value >= 0x20 && value < 0x7f ? String.fromCharCode(value) : '.');
}
let hexString = hexArray.join(' ');
let asciiString = asciiArray.join('');
lines.push(`${address} ${hexString} |${asciiString}|`);
}
return lines.join('\n');
}
|
f07301026e8faedc665115fbeb3f4f40e79115fa | 4,232 | ts | TypeScript | src/utils/get-video-data.ts | bgoonz/ellie-d3931 | 6f05defff1735af6f25f55b9e7a2c69f514fbbb4 | [
"Apache-2.0"
] | null | null | null | src/utils/get-video-data.ts | bgoonz/ellie-d3931 | 6f05defff1735af6f25f55b9e7a2c69f514fbbb4 | [
"Apache-2.0"
] | 26 | 2022-02-04T21:08:22.000Z | 2022-02-11T11:09:04.000Z | src/utils/get-video-data.ts | bgoonz/ellie-d3931 | 6f05defff1735af6f25f55b9e7a2c69f514fbbb4 | [
"Apache-2.0"
] | null | null | null | // Based on https://github.com/radiovisual/get-video-id
export default function getVideoData(videoUrl: string) {
let videoData = {
id: null,
service: null
};
if (/youtube|youtu\.be|y2u\.be|i.ytimg\./.test(videoUrl)) {
videoUrl = videoUrl.replace('/www.', '/');
videoUrl = videoUrl.replace('-nocookie', '');
videoData = {
id: getYoutubeId(videoUrl),
service: 'youtube'
};
} else if (/vimeo/.test(videoUrl)) {
videoUrl = videoUrl.replace('/www.', '/');
videoData = {
id: getVimeoId(videoUrl),
service: 'vimeo'
};
} else if (/\.mp4/.test(videoUrl)) {
videoData = {
id: videoUrl,
service: 'custom'
};
}
return videoData;
}
function getVimeoId(vimeoStr) {
let str = vimeoStr;
if (str.includes('#')) {
[str] = str.split('#');
}
if (str.includes('?') && !str.includes('clip_id=')) {
[str] = str.split('?');
}
let id;
let array;
const event = /https?:\/\/vimeo\.com\/event\/(\d+)$/;
const eventMatches = event.exec(str);
if (eventMatches && eventMatches[1]) {
return eventMatches[1];
}
const primary = /https?:\/\/vimeo\.com\/(\d+)/;
const matches = primary.exec(str);
if (matches && matches[1]) {
return matches[1];
}
const vimeoPipe = ['https?://player.vimeo.com/video/[0-9]+$', 'https?://vimeo.com/channels', 'groups', 'album'].join('|');
const vimeoRegex = new RegExp(vimeoPipe, 'gim');
if (vimeoRegex.test(str)) {
array = str.split('/');
if (array && array.length > 0) {
id = array.pop();
}
} else if (/clip_id=/gim.test(str)) {
array = str.split('clip_id=');
if (array && array.length > 0) {
[id] = array[1].split('&');
}
}
return id;
}
function getYoutubeId(youtubeStr) {
let str = youtubeStr;
// Remove time hash at the end of the string
str = str.replace(/#t=.*$/, '');
// Strip the leading protocol
str = str.replace(/^https?:\/\//, '');
// Shortcode
const shortcode = /youtube:\/\/|youtu\.be\/|y2u\.be\//g;
if (shortcode.test(str)) {
const shortcodeid = str.split(shortcode)[1];
return stripParameters(shortcodeid);
}
// /v/ or /vi/
const inlinev = /\/v\/|\/vi\//g;
if (inlinev.test(str)) {
const inlineid = str.split(inlinev)[1];
return stripParameters(inlineid);
}
// V= or vi=
const parameterv = /v=|vi=/g;
if (parameterv.test(str)) {
const array = str.split(parameterv);
return stripParameters(array[1].split('&')[0]);
}
// Format an_webp
const parameterwebp = /\/an_webp\//g;
if (parameterwebp.test(str)) {
const webp = str.split(parameterwebp)[1];
return stripParameters(webp);
}
// /e/
const eformat = /\/e\//g;
if (eformat.test(str)) {
const estring = str.split(eformat)[1];
return stripParameters(estring);
}
// Embed
const embedreg = /\/embed\//g;
if (embedreg.test(str)) {
const embedid = str.split(embedreg)[1];
return stripParameters(embedid);
}
// ignore /user/username pattern
const usernamereg = /\/user\/([a-zA-Z\d]*)$/g;
if (usernamereg.test(str)) {
return undefined;
}
// User
const userreg = /\/user\/(?!.*videos)/g;
if (userreg.test(str)) {
const elements = str.split('/');
return stripParameters(elements.pop());
}
// Attribution_link
const attrreg = /\/attribution_link\?.*v%3D([^%&]*)(%26|&|$)/;
if (attrreg.test(str)) {
return stripParameters(str.match(attrreg)[1]);
}
return undefined;
}
function stripParameters(shortcodeString) {
// Split parameters or split folder separator
if (shortcodeString.includes('?')) {
return shortcodeString.split('?')[0];
}
if (shortcodeString.includes('/')) {
return shortcodeString.split('/')[0];
}
if (shortcodeString.includes('&')) {
return shortcodeString.split('&')[0];
}
return shortcodeString;
}
| 24.045455 | 126 | 0.541588 | 122 | 4 | 0 | 4 | 27 | 0 | 3 | 0 | 1 | 0 | 0 | 28.5 | 1,225 | 0.006531 | 0.022041 | 0 | 0 | 0 | 0 | 0.028571 | 0.258154 | // Based on https://github.com/radiovisual/get-video-id
export default function getVideoData(videoUrl) {
let videoData = {
id: null,
service: null
};
if (/youtube|youtu\.be|y2u\.be|i.ytimg\./.test(videoUrl)) {
videoUrl = videoUrl.replace('/www.', '/');
videoUrl = videoUrl.replace('-nocookie', '');
videoData = {
id: getYoutubeId(videoUrl),
service: 'youtube'
};
} else if (/vimeo/.test(videoUrl)) {
videoUrl = videoUrl.replace('/www.', '/');
videoData = {
id: getVimeoId(videoUrl),
service: 'vimeo'
};
} else if (/\.mp4/.test(videoUrl)) {
videoData = {
id: videoUrl,
service: 'custom'
};
}
return videoData;
}
/* Example usages of 'getVimeoId' are shown below:
getVimeoId(videoUrl);
*/
function getVimeoId(vimeoStr) {
let str = vimeoStr;
if (str.includes('#')) {
[str] = str.split('#');
}
if (str.includes('?') && !str.includes('clip_id=')) {
[str] = str.split('?');
}
let id;
let array;
const event = /https?:\/\/vimeo\.com\/event\/(\d+)$/;
const eventMatches = event.exec(str);
if (eventMatches && eventMatches[1]) {
return eventMatches[1];
}
const primary = /https?:\/\/vimeo\.com\/(\d+)/;
const matches = primary.exec(str);
if (matches && matches[1]) {
return matches[1];
}
const vimeoPipe = ['https?://player.vimeo.com/video/[0-9]+$', 'https?://vimeo.com/channels', 'groups', 'album'].join('|');
const vimeoRegex = new RegExp(vimeoPipe, 'gim');
if (vimeoRegex.test(str)) {
array = str.split('/');
if (array && array.length > 0) {
id = array.pop();
}
} else if (/clip_id=/gim.test(str)) {
array = str.split('clip_id=');
if (array && array.length > 0) {
[id] = array[1].split('&');
}
}
return id;
}
/* Example usages of 'getYoutubeId' are shown below:
getYoutubeId(videoUrl);
*/
function getYoutubeId(youtubeStr) {
let str = youtubeStr;
// Remove time hash at the end of the string
str = str.replace(/#t=.*$/, '');
// Strip the leading protocol
str = str.replace(/^https?:\/\//, '');
// Shortcode
const shortcode = /youtube:\/\/|youtu\.be\/|y2u\.be\//g;
if (shortcode.test(str)) {
const shortcodeid = str.split(shortcode)[1];
return stripParameters(shortcodeid);
}
// /v/ or /vi/
const inlinev = /\/v\/|\/vi\//g;
if (inlinev.test(str)) {
const inlineid = str.split(inlinev)[1];
return stripParameters(inlineid);
}
// V= or vi=
const parameterv = /v=|vi=/g;
if (parameterv.test(str)) {
const array = str.split(parameterv);
return stripParameters(array[1].split('&')[0]);
}
// Format an_webp
const parameterwebp = /\/an_webp\//g;
if (parameterwebp.test(str)) {
const webp = str.split(parameterwebp)[1];
return stripParameters(webp);
}
// /e/
const eformat = /\/e\//g;
if (eformat.test(str)) {
const estring = str.split(eformat)[1];
return stripParameters(estring);
}
// Embed
const embedreg = /\/embed\//g;
if (embedreg.test(str)) {
const embedid = str.split(embedreg)[1];
return stripParameters(embedid);
}
// ignore /user/username pattern
const usernamereg = /\/user\/([a-zA-Z\d]*)$/g;
if (usernamereg.test(str)) {
return undefined;
}
// User
const userreg = /\/user\/(?!.*videos)/g;
if (userreg.test(str)) {
const elements = str.split('/');
return stripParameters(elements.pop());
}
// Attribution_link
const attrreg = /\/attribution_link\?.*v%3D([^%&]*)(%26|&|$)/;
if (attrreg.test(str)) {
return stripParameters(str.match(attrreg)[1]);
}
return undefined;
}
/* Example usages of 'stripParameters' are shown below:
stripParameters(shortcodeid);
stripParameters(inlineid);
stripParameters(array[1].split('&')[0]);
stripParameters(webp);
stripParameters(estring);
stripParameters(embedid);
stripParameters(elements.pop());
stripParameters(str.match(attrreg)[1]);
*/
function stripParameters(shortcodeString) {
// Split parameters or split folder separator
if (shortcodeString.includes('?')) {
return shortcodeString.split('?')[0];
}
if (shortcodeString.includes('/')) {
return shortcodeString.split('/')[0];
}
if (shortcodeString.includes('&')) {
return shortcodeString.split('&')[0];
}
return shortcodeString;
}
|
f0b92cf86128cd18a92f56508e4133c38e81ac61 | 2,210 | ts | TypeScript | helpers/utils.ts | MTRNord/matrix-art | beff2a426993d0e091f99fddcb0a5ad7243c120b | [
"ECL-2.0",
"Apache-2.0"
] | 19 | 2022-01-02T07:03:15.000Z | 2022-03-14T02:37:48.000Z | helpers/utils.ts | MTRNord/matrix-art | beff2a426993d0e091f99fddcb0a5ad7243c120b | [
"ECL-2.0",
"Apache-2.0"
] | 30 | 2022-01-05T15:39:57.000Z | 2022-03-31T08:39:02.000Z | helpers/utils.ts | MTRNord/matrix-art | beff2a426993d0e091f99fddcb0a5ad7243c120b | [
"ECL-2.0",
"Apache-2.0"
] | 1 | 2022-01-20T11:09:50.000Z | 2022-01-20T11:09:50.000Z | export interface IDeferred<T> {
resolve: (value: T) => void;
reject: (reason?: any) => void;
promise: Promise<T>;
}
// Returns a Deferred
export function defer<T = void>(): IDeferred<T> {
let resolve!: (value: T) => void;
let reject!: (reason?: any) => void;
const promise = new Promise<T>((_resolve, _reject) => {
resolve = _resolve;
reject = _reject;
});
return { resolve, reject, promise };
}
export function getLicenseUrl(license_type: string): string {
switch (license_type) {
case "cc-by-4.0":
return "https://creativecommons.org/licenses/by/4.0/";
case "cc-by-sa-4.0":
return "https://creativecommons.org/licenses/by-sa/4.0/";
case "cc-by-nc-4.0":
return "https://creativecommons.org/licenses/by-nc/4.0/";
case "cc-by-nc-sa-4.0":
return "https://creativecommons.org/licenses/by-nc-sa/4.0/";
case "cc-by-nd-4.0":
return "https://creativecommons.org/licenses/by-nd/4.0/";
case "cc-by-nc-nd-4.0":
return "https://creativecommons.org/licenses/by-nc-nd/4.0/";
case "CC0-1.0":
return "https://creativecommons.org/publicdomain/zero/1.0/";
default:
return "";
}
}
export function getLicenseName(license_type: string): string {
switch (license_type) {
case "cc-by-4.0":
return "Attribution 4.0 International (CC BY 4.0)";
case "cc-by-sa-4.0":
return "Attribution-ShareAlike 4.0 International (CC BY-SA 4.0)";
case "cc-by-nc-4.0":
return "Attribution-NonCommercial 4.0 International (CC BY-NC 4.0)";
case "cc-by-nc-sa-4.0":
return "Attribution-NonCommercial-ShareAlike 4.0 International (CC BY-NC-SA 4.0)";
case "cc-by-nd-4.0":
return "Attribution-NoDerivatives 4.0 International (CC BY-ND 4.0)";
case "cc-by-nc-nd-4.0":
return "Attribution-NonCommercial-NoDerivatives 4.0 International (CC BY-NC-ND 4.0)";
case "CC0-1.0":
return "CC0 1.0 Universal (CC0 1.0) Public Domain Dedication";
default:
return "Unknown License";
}
} | 36.833333 | 97 | 0.5819 | 54 | 4 | 0 | 4 | 3 | 3 | 0 | 2 | 9 | 1 | 0 | 11.25 | 688 | 0.011628 | 0.00436 | 0.00436 | 0.001453 | 0 | 0.142857 | 0.642857 | 0.210744 | export interface IDeferred<T> {
resolve;
reject;
promise;
}
// Returns a Deferred
export function defer<T = void>() {
let resolve!;
let reject!;
const promise = new Promise<T>((_resolve, _reject) => {
resolve = _resolve;
reject = _reject;
});
return { resolve, reject, promise };
}
export function getLicenseUrl(license_type) {
switch (license_type) {
case "cc-by-4.0":
return "https://creativecommons.org/licenses/by/4.0/";
case "cc-by-sa-4.0":
return "https://creativecommons.org/licenses/by-sa/4.0/";
case "cc-by-nc-4.0":
return "https://creativecommons.org/licenses/by-nc/4.0/";
case "cc-by-nc-sa-4.0":
return "https://creativecommons.org/licenses/by-nc-sa/4.0/";
case "cc-by-nd-4.0":
return "https://creativecommons.org/licenses/by-nd/4.0/";
case "cc-by-nc-nd-4.0":
return "https://creativecommons.org/licenses/by-nc-nd/4.0/";
case "CC0-1.0":
return "https://creativecommons.org/publicdomain/zero/1.0/";
default:
return "";
}
}
export function getLicenseName(license_type) {
switch (license_type) {
case "cc-by-4.0":
return "Attribution 4.0 International (CC BY 4.0)";
case "cc-by-sa-4.0":
return "Attribution-ShareAlike 4.0 International (CC BY-SA 4.0)";
case "cc-by-nc-4.0":
return "Attribution-NonCommercial 4.0 International (CC BY-NC 4.0)";
case "cc-by-nc-sa-4.0":
return "Attribution-NonCommercial-ShareAlike 4.0 International (CC BY-NC-SA 4.0)";
case "cc-by-nd-4.0":
return "Attribution-NoDerivatives 4.0 International (CC BY-ND 4.0)";
case "cc-by-nc-nd-4.0":
return "Attribution-NonCommercial-NoDerivatives 4.0 International (CC BY-NC-ND 4.0)";
case "CC0-1.0":
return "CC0 1.0 Universal (CC0 1.0) Public Domain Dedication";
default:
return "Unknown License";
}
} |
2e3e4fac94d526c86c5076414c4ba18c0868fef6 | 2,177 | ts | TypeScript | src/lib/fonts/lexText.ts | garbage-god/gb-studio | d462bd722be62d7a8320489a50d49d9c36242866 | [
"MIT"
] | null | null | null | src/lib/fonts/lexText.ts | garbage-god/gb-studio | d462bd722be62d7a8320489a50d49d9c36242866 | [
"MIT"
] | null | null | null | src/lib/fonts/lexText.ts | garbage-god/gb-studio | d462bd722be62d7a8320489a50d49d9c36242866 | [
"MIT"
] | 1 | 2022-02-27T02:42:47.000Z | 2022-02-27T02:42:47.000Z | type Token =
| {
type: "text";
value: string;
}
| {
type: "font";
fontId: string;
}
| {
type: "variable";
variableId: string;
}
| {
type: "char";
variableId: string;
}
| {
type: "speed";
speed: number;
};
export const lexText = (inputText: string): Token[] => {
const tokens: Token[] = [];
for (let i = 0; i < inputText.length; i++) {
// Check for font change
if (
inputText[i] === "!" &&
inputText[i + 1] === "F" &&
inputText[i + 2] === ":"
) {
const fontId = inputText.substring(i + 3, i + 40).replace(/!.*/, "");
i += fontId.length + 3;
tokens.push({
type: "font",
fontId,
});
continue;
}
// Check for variable
if (inputText[i] === "$") {
const variableMatch = inputText
.substring(i)
.match(/(\$L[0-9]\$|\$T[0-1]\$|\$V[0-9]\$|\$[0-9]+\$)/)?.[0];
if (variableMatch) {
i += variableMatch.length - 1;
tokens.push({
type: "variable",
variableId: variableMatch.replace(/\$/g, ""),
});
}
continue;
}
// Check for character variable
if (inputText[i] === "#") {
const variableMatch = inputText
.substring(i)
.match(/(#L[0-9]#|#T[0-1]#|#V[0-9]#|#[0-9]+#)/)?.[0];
if (variableMatch) {
i += variableMatch.length - 1;
tokens.push({
type: "char",
variableId: variableMatch.replace(/#/g, ""),
});
}
continue;
}
// Check for speed codes
if (
inputText[i] === "!" &&
inputText[i + 1] === "S" &&
inputText[i + 2].match(/[0-5]/) &&
inputText[i + 3] === "!"
) {
const speed = Number(inputText[i + 2]);
tokens.push({
type: "speed",
speed,
});
i += 3;
continue;
}
// Add as text token
const lastToken = tokens[tokens.length - 1];
if (lastToken?.type === "text") {
lastToken.value += inputText[i];
} else {
tokens.push({
type: "text",
value: inputText[i],
});
}
}
return tokens;
};
| 22.214286 | 75 | 0.446945 | 89 | 1 | 0 | 1 | 8 | 0 | 0 | 0 | 6 | 1 | 0 | 66 | 672 | 0.002976 | 0.011905 | 0 | 0.001488 | 0 | 0 | 0.6 | 0.217787 | type Token =
| {
type;
value;
}
| {
type;
fontId;
}
| {
type;
variableId;
}
| {
type;
variableId;
}
| {
type;
speed;
};
export const lexText = (inputText) => {
const tokens = [];
for (let i = 0; i < inputText.length; i++) {
// Check for font change
if (
inputText[i] === "!" &&
inputText[i + 1] === "F" &&
inputText[i + 2] === ":"
) {
const fontId = inputText.substring(i + 3, i + 40).replace(/!.*/, "");
i += fontId.length + 3;
tokens.push({
type: "font",
fontId,
});
continue;
}
// Check for variable
if (inputText[i] === "$") {
const variableMatch = inputText
.substring(i)
.match(/(\$L[0-9]\$|\$T[0-1]\$|\$V[0-9]\$|\$[0-9]+\$)/)?.[0];
if (variableMatch) {
i += variableMatch.length - 1;
tokens.push({
type: "variable",
variableId: variableMatch.replace(/\$/g, ""),
});
}
continue;
}
// Check for character variable
if (inputText[i] === "#") {
const variableMatch = inputText
.substring(i)
.match(/(#L[0-9]#|#T[0-1]#|#V[0-9]#|#[0-9]+#)/)?.[0];
if (variableMatch) {
i += variableMatch.length - 1;
tokens.push({
type: "char",
variableId: variableMatch.replace(/#/g, ""),
});
}
continue;
}
// Check for speed codes
if (
inputText[i] === "!" &&
inputText[i + 1] === "S" &&
inputText[i + 2].match(/[0-5]/) &&
inputText[i + 3] === "!"
) {
const speed = Number(inputText[i + 2]);
tokens.push({
type: "speed",
speed,
});
i += 3;
continue;
}
// Add as text token
const lastToken = tokens[tokens.length - 1];
if (lastToken?.type === "text") {
lastToken.value += inputText[i];
} else {
tokens.push({
type: "text",
value: inputText[i],
});
}
}
return tokens;
};
|
2eea3cdf17dad8f71b37165f9ddfdf85c5088bdf | 7,018 | ts | TypeScript | src/offset-polygon.ts | Stanko/offset-polygon | 4e92233e2187d0c67a03505ec077128b265a5365 | [
"MIT"
] | 2 | 2022-01-31T10:34:57.000Z | 2022-01-31T11:00:47.000Z | src/offset-polygon.ts | Stanko/offset-polygon | 4e92233e2187d0c67a03505ec077128b265a5365 | [
"MIT"
] | 1 | 2022-01-31T10:37:18.000Z | 2022-01-31T20:53:40.000Z | src/offset-polygon.ts | Stanko/offset-polygon | 4e92233e2187d0c67a03505ec077128b265a5365 | [
"MIT"
] | null | null | null | // TODO check these comments:
// Assuming that polygon vertices are in clockwise order
type Vector = {
x: number;
y: number;
};
type Edge = {
index: number;
inwardNormal: Vector;
outwardNormal: Vector;
vertex1: Vector;
vertex2: Vector;
};
type OffsetEdge = {
vertex1: Vector;
vertex2: Vector;
};
type Polygon = {
edges: Edge[];
offsetEdges?: OffsetEdge[];
maxX: number;
maxY: number;
minX: number;
minY: number;
vertices: Vector[];
};
const TWO_PI = Math.PI * 2;
// See http://paulbourke.net/geometry/pointlineplane/
function inwardEdgeNormal(vertex1: Vector, vertex2: Vector): Vector {
// Assuming that polygon vertices are in clockwise order
const dx = vertex2.x - vertex1.x;
const dy = vertex2.y - vertex1.y;
const edgeLength = Math.sqrt(dx * dx + dy * dy);
return {
x: -dy / edgeLength,
y: dx / edgeLength,
};
}
function outwardEdgeNormal(vertex1: Vector, vertex2: Vector): Vector {
var n = inwardEdgeNormal(vertex1, vertex2);
return {
x: -n.x,
y: -n.y,
};
}
function createPolygon(vertices: Vector[]): Polygon {
const edges: Edge[] = [];
let minX = vertices.length > 0 ? vertices[0].x : undefined;
let minY = vertices.length > 0 ? vertices[0].y : undefined;
let maxX = minX;
let maxY = minY;
for (let i = 0; i < vertices.length; i++) {
const vertex1 = vertices[i];
const vertex2 = vertices[(i + 1) % vertices.length];
const outwardNormal = outwardEdgeNormal(vertex1, vertex2);
const inwardNormal = inwardEdgeNormal(vertex1, vertex2);
const edge: Edge = {
vertex1,
vertex2,
index: i,
outwardNormal,
inwardNormal,
};
edges.push(edge);
const x = vertices[i].x;
const y = vertices[i].y;
minX = Math.min(x, minX);
minY = Math.min(y, minY);
maxX = Math.max(x, maxX);
maxY = Math.max(y, maxY);
}
const polygon: Polygon = {
vertices,
edges,
minX,
minY,
maxX,
maxY,
};
return polygon;
}
// based on http://local.wasp.uwa.edu.au/~pbourke/geometry/lineline2d/, edgeA => "line a", edgeB => "line b"
function edgesIntersection(edgeA: Edge | OffsetEdge, edgeB: Edge | OffsetEdge) {
const den =
(edgeB.vertex2.y - edgeB.vertex1.y) * (edgeA.vertex2.x - edgeA.vertex1.x) -
(edgeB.vertex2.x - edgeB.vertex1.x) * (edgeA.vertex2.y - edgeA.vertex1.y);
if (den == 0) {
return null; // lines are parallel or coincident
}
const ua =
((edgeB.vertex2.x - edgeB.vertex1.x) * (edgeA.vertex1.y - edgeB.vertex1.y) -
(edgeB.vertex2.y - edgeB.vertex1.y) *
(edgeA.vertex1.x - edgeB.vertex1.x)) /
den;
const ub =
((edgeA.vertex2.x - edgeA.vertex1.x) * (edgeA.vertex1.y - edgeB.vertex1.y) -
(edgeA.vertex2.y - edgeA.vertex1.y) *
(edgeA.vertex1.x - edgeB.vertex1.x)) /
den;
// Edges are not intersecting but the lines defined by them are
const isIntersectionOutside = ua < 0 || ub < 0 || ua > 1 || ub > 1;
return {
x: edgeA.vertex1.x + ua * (edgeA.vertex2.x - edgeA.vertex1.x),
y: edgeA.vertex1.y + ua * (edgeA.vertex2.y - edgeA.vertex1.y),
isIntersectionOutside,
};
}
function appendArc(
arcSegments: number,
vertices: Vector[],
center: Vector,
radius: number,
startVertex: Vector,
endVertex: Vector,
isPaddingBoundary: boolean
) {
var startAngle = Math.atan2(
startVertex.y - center.y,
startVertex.x - center.x
);
var endAngle = Math.atan2(endVertex.y - center.y, endVertex.x - center.x);
if (startAngle < 0) {
startAngle += TWO_PI;
}
if (endAngle < 0) {
endAngle += TWO_PI;
}
const angle =
startAngle > endAngle
? startAngle - endAngle
: startAngle + TWO_PI - endAngle;
const angleStep = (isPaddingBoundary ? -angle : TWO_PI - angle) / arcSegments;
vertices.push(startVertex);
for (let i = 1; i < arcSegments; ++i) {
const angle = startAngle + angleStep * i;
const vertex = {
x: center.x + Math.cos(angle) * radius,
y: center.y + Math.sin(angle) * radius,
};
vertices.push(vertex);
}
vertices.push(endVertex);
}
function createOffsetEdge(edge: Edge, dx: number, dy: number): OffsetEdge {
return {
vertex1: {
x: edge.vertex1.x + dx,
y: edge.vertex1.y + dy,
},
vertex2: {
x: edge.vertex2.x + dx,
y: edge.vertex2.y + dy,
},
};
}
function createMarginPolygon(
polygon: Polygon,
offset: number,
arcSegments: number
): Polygon {
const offsetEdges: OffsetEdge[] = [];
for (let i = 0; i < polygon.edges.length; i++) {
const edge = polygon.edges[i];
const dx = edge.outwardNormal.x * offset;
const dy = edge.outwardNormal.y * offset;
offsetEdges.push(createOffsetEdge(edge, dx, dy));
}
const vertices: Vector[] = [];
for (let i = 0; i < offsetEdges.length; i++) {
const thisEdge = offsetEdges[i];
const prevEdge =
offsetEdges[(i + offsetEdges.length - 1) % offsetEdges.length];
const vertex = edgesIntersection(prevEdge, thisEdge);
if (vertex && (!vertex.isIntersectionOutside || arcSegments < 1)) {
vertices.push({
x: vertex.x,
y: vertex.y,
});
} else {
const arcCenter = polygon.edges[i].vertex1;
appendArc(
arcSegments,
vertices,
arcCenter,
offset,
prevEdge.vertex2,
thisEdge.vertex1,
false
);
}
}
const marginPolygon = createPolygon(vertices);
marginPolygon.offsetEdges = offsetEdges;
return marginPolygon;
}
function createPaddingPolygon(
polygon: Polygon,
offset: number,
arcSegments: number
): Polygon {
const offsetEdges: OffsetEdge[] = [];
for (let i = 0; i < polygon.edges.length; i++) {
const edge = polygon.edges[i];
const dx = edge.inwardNormal.x * offset;
const dy = edge.inwardNormal.y * offset;
offsetEdges.push(createOffsetEdge(edge, dx, dy));
}
const vertices: Vector[] = [];
for (let i = 0; i < offsetEdges.length; i++) {
const thisEdge = offsetEdges[i];
const prevEdge =
offsetEdges[(i + offsetEdges.length - 1) % offsetEdges.length];
const vertex = edgesIntersection(prevEdge, thisEdge);
if (vertex && (!vertex.isIntersectionOutside || arcSegments < 1)) {
vertices.push({
x: vertex.x,
y: vertex.y,
});
} else {
const arcCenter = polygon.edges[i].vertex1;
appendArc(
arcSegments,
vertices,
arcCenter,
offset,
prevEdge.vertex2,
thisEdge.vertex1,
true
);
}
}
const paddingPolygon = createPolygon(vertices);
paddingPolygon.offsetEdges = offsetEdges;
return paddingPolygon;
}
export default function offsetPolygon(
vertices: Vector[],
offset: number,
arcSegments: number = 0
): Vector[] {
const polygon = createPolygon(vertices);
if (offset > 0) {
return createMarginPolygon(polygon, offset, arcSegments).vertices;
} else {
return createPaddingPolygon(polygon, -offset, arcSegments).vertices;
}
}
| 23.238411 | 108 | 0.623682 | 241 | 9 | 0 | 26 | 55 | 16 | 8 | 0 | 18 | 4 | 0 | 19.777778 | 2,159 | 0.016211 | 0.025475 | 0.007411 | 0.001853 | 0 | 0 | 0.169811 | 0.296086 | // TODO check these comments:
// Assuming that polygon vertices are in clockwise order
type Vector = {
x;
y;
};
type Edge = {
index;
inwardNormal;
outwardNormal;
vertex1;
vertex2;
};
type OffsetEdge = {
vertex1;
vertex2;
};
type Polygon = {
edges;
offsetEdges?;
maxX;
maxY;
minX;
minY;
vertices;
};
const TWO_PI = Math.PI * 2;
// See http://paulbourke.net/geometry/pointlineplane/
/* Example usages of 'inwardEdgeNormal' are shown below:
inwardEdgeNormal(vertex1, vertex2);
*/
function inwardEdgeNormal(vertex1, vertex2) {
// Assuming that polygon vertices are in clockwise order
const dx = vertex2.x - vertex1.x;
const dy = vertex2.y - vertex1.y;
const edgeLength = Math.sqrt(dx * dx + dy * dy);
return {
x: -dy / edgeLength,
y: dx / edgeLength,
};
}
/* Example usages of 'outwardEdgeNormal' are shown below:
outwardEdgeNormal(vertex1, vertex2);
*/
function outwardEdgeNormal(vertex1, vertex2) {
var n = inwardEdgeNormal(vertex1, vertex2);
return {
x: -n.x,
y: -n.y,
};
}
/* Example usages of 'createPolygon' are shown below:
createPolygon(vertices);
*/
function createPolygon(vertices) {
const edges = [];
let minX = vertices.length > 0 ? vertices[0].x : undefined;
let minY = vertices.length > 0 ? vertices[0].y : undefined;
let maxX = minX;
let maxY = minY;
for (let i = 0; i < vertices.length; i++) {
const vertex1 = vertices[i];
const vertex2 = vertices[(i + 1) % vertices.length];
const outwardNormal = outwardEdgeNormal(vertex1, vertex2);
const inwardNormal = inwardEdgeNormal(vertex1, vertex2);
const edge = {
vertex1,
vertex2,
index: i,
outwardNormal,
inwardNormal,
};
edges.push(edge);
const x = vertices[i].x;
const y = vertices[i].y;
minX = Math.min(x, minX);
minY = Math.min(y, minY);
maxX = Math.max(x, maxX);
maxY = Math.max(y, maxY);
}
const polygon = {
vertices,
edges,
minX,
minY,
maxX,
maxY,
};
return polygon;
}
// based on http://local.wasp.uwa.edu.au/~pbourke/geometry/lineline2d/, edgeA => "line a", edgeB => "line b"
/* Example usages of 'edgesIntersection' are shown below:
edgesIntersection(prevEdge, thisEdge);
*/
function edgesIntersection(edgeA, edgeB) {
const den =
(edgeB.vertex2.y - edgeB.vertex1.y) * (edgeA.vertex2.x - edgeA.vertex1.x) -
(edgeB.vertex2.x - edgeB.vertex1.x) * (edgeA.vertex2.y - edgeA.vertex1.y);
if (den == 0) {
return null; // lines are parallel or coincident
}
const ua =
((edgeB.vertex2.x - edgeB.vertex1.x) * (edgeA.vertex1.y - edgeB.vertex1.y) -
(edgeB.vertex2.y - edgeB.vertex1.y) *
(edgeA.vertex1.x - edgeB.vertex1.x)) /
den;
const ub =
((edgeA.vertex2.x - edgeA.vertex1.x) * (edgeA.vertex1.y - edgeB.vertex1.y) -
(edgeA.vertex2.y - edgeA.vertex1.y) *
(edgeA.vertex1.x - edgeB.vertex1.x)) /
den;
// Edges are not intersecting but the lines defined by them are
const isIntersectionOutside = ua < 0 || ub < 0 || ua > 1 || ub > 1;
return {
x: edgeA.vertex1.x + ua * (edgeA.vertex2.x - edgeA.vertex1.x),
y: edgeA.vertex1.y + ua * (edgeA.vertex2.y - edgeA.vertex1.y),
isIntersectionOutside,
};
}
/* Example usages of 'appendArc' are shown below:
appendArc(arcSegments, vertices, arcCenter, offset, prevEdge.vertex2, thisEdge.vertex1, false);
appendArc(arcSegments, vertices, arcCenter, offset, prevEdge.vertex2, thisEdge.vertex1, true);
*/
function appendArc(
arcSegments,
vertices,
center,
radius,
startVertex,
endVertex,
isPaddingBoundary
) {
var startAngle = Math.atan2(
startVertex.y - center.y,
startVertex.x - center.x
);
var endAngle = Math.atan2(endVertex.y - center.y, endVertex.x - center.x);
if (startAngle < 0) {
startAngle += TWO_PI;
}
if (endAngle < 0) {
endAngle += TWO_PI;
}
const angle =
startAngle > endAngle
? startAngle - endAngle
: startAngle + TWO_PI - endAngle;
const angleStep = (isPaddingBoundary ? -angle : TWO_PI - angle) / arcSegments;
vertices.push(startVertex);
for (let i = 1; i < arcSegments; ++i) {
const angle = startAngle + angleStep * i;
const vertex = {
x: center.x + Math.cos(angle) * radius,
y: center.y + Math.sin(angle) * radius,
};
vertices.push(vertex);
}
vertices.push(endVertex);
}
/* Example usages of 'createOffsetEdge' are shown below:
offsetEdges.push(createOffsetEdge(edge, dx, dy));
*/
function createOffsetEdge(edge, dx, dy) {
return {
vertex1: {
x: edge.vertex1.x + dx,
y: edge.vertex1.y + dy,
},
vertex2: {
x: edge.vertex2.x + dx,
y: edge.vertex2.y + dy,
},
};
}
/* Example usages of 'createMarginPolygon' are shown below:
createMarginPolygon(polygon, offset, arcSegments).vertices;
*/
function createMarginPolygon(
polygon,
offset,
arcSegments
) {
const offsetEdges = [];
for (let i = 0; i < polygon.edges.length; i++) {
const edge = polygon.edges[i];
const dx = edge.outwardNormal.x * offset;
const dy = edge.outwardNormal.y * offset;
offsetEdges.push(createOffsetEdge(edge, dx, dy));
}
const vertices = [];
for (let i = 0; i < offsetEdges.length; i++) {
const thisEdge = offsetEdges[i];
const prevEdge =
offsetEdges[(i + offsetEdges.length - 1) % offsetEdges.length];
const vertex = edgesIntersection(prevEdge, thisEdge);
if (vertex && (!vertex.isIntersectionOutside || arcSegments < 1)) {
vertices.push({
x: vertex.x,
y: vertex.y,
});
} else {
const arcCenter = polygon.edges[i].vertex1;
appendArc(
arcSegments,
vertices,
arcCenter,
offset,
prevEdge.vertex2,
thisEdge.vertex1,
false
);
}
}
const marginPolygon = createPolygon(vertices);
marginPolygon.offsetEdges = offsetEdges;
return marginPolygon;
}
/* Example usages of 'createPaddingPolygon' are shown below:
createPaddingPolygon(polygon, -offset, arcSegments).vertices;
*/
function createPaddingPolygon(
polygon,
offset,
arcSegments
) {
const offsetEdges = [];
for (let i = 0; i < polygon.edges.length; i++) {
const edge = polygon.edges[i];
const dx = edge.inwardNormal.x * offset;
const dy = edge.inwardNormal.y * offset;
offsetEdges.push(createOffsetEdge(edge, dx, dy));
}
const vertices = [];
for (let i = 0; i < offsetEdges.length; i++) {
const thisEdge = offsetEdges[i];
const prevEdge =
offsetEdges[(i + offsetEdges.length - 1) % offsetEdges.length];
const vertex = edgesIntersection(prevEdge, thisEdge);
if (vertex && (!vertex.isIntersectionOutside || arcSegments < 1)) {
vertices.push({
x: vertex.x,
y: vertex.y,
});
} else {
const arcCenter = polygon.edges[i].vertex1;
appendArc(
arcSegments,
vertices,
arcCenter,
offset,
prevEdge.vertex2,
thisEdge.vertex1,
true
);
}
}
const paddingPolygon = createPolygon(vertices);
paddingPolygon.offsetEdges = offsetEdges;
return paddingPolygon;
}
export default function offsetPolygon(
vertices,
offset,
arcSegments = 0
) {
const polygon = createPolygon(vertices);
if (offset > 0) {
return createMarginPolygon(polygon, offset, arcSegments).vertices;
} else {
return createPaddingPolygon(polygon, -offset, arcSegments).vertices;
}
}
|
fe48985f9ace65089aa5d0dd92573b69804e7a66 | 3,556 | ts | TypeScript | src/models/HostRule.ts | advanced-rest-client/core | 2efb946f786d8b46e7131c62e0011f6e090ddec3 | [
"Apache-2.0"
] | null | null | null | src/models/HostRule.ts | advanced-rest-client/core | 2efb946f786d8b46e7131c62e0011f6e090ddec3 | [
"Apache-2.0"
] | 1 | 2022-02-14T00:01:04.000Z | 2022-02-14T00:04:07.000Z | src/models/HostRule.ts | advanced-rest-client/core | 2efb946f786d8b46e7131c62e0011f6e090ddec3 | [
"Apache-2.0"
] | null | null | null | export const Kind = 'Core#HostRule';
/**
* API Client host rule definition.
*/
export interface IHostRule {
kind?: typeof Kind;
/**
* The from rule (may contain asterisks)
*/
from: string;
/**
* replacement value
*/
to: string;
/**
* if false the rule is ignored
*/
enabled?: boolean;
/**
* optional rule description
*/
comment?: string;
}
export class HostRule {
kind = Kind;
/**
* The from rule (may contain asterisks)
*/
from = '';
/**
* replacement value
*/
to = '';
/**
* if false the rule is ignored
*/
enabled?: boolean;
/**
* optional rule description
*/
comment?: string;
static fromValues(from: string, to: string ): HostRule {
const result = new HostRule({
kind: Kind,
from,
to,
enabled: true,
});
return result;
}
/**
* @param input The thing definition used to restore the state.
*/
constructor(input?: string | IHostRule) {
let init: IHostRule;
if (typeof input === 'string') {
init = JSON.parse(input);
} else if (typeof input === 'object') {
init = input;
} else {
init = {
kind: Kind,
from: '',
to: '',
};
}
this.new(init);
}
/**
* Creates a new thing clearing anything that is so far defined.
*
* Note, this throws an error when the server is not an API Client thing.
*/
new(init: IHostRule): void {
if (!HostRule.isHostRule(init)) {
throw new Error(`Not a HostRule.`);
}
const { from='', to='', enabled, comment } = init;
this.kind = Kind;
this.from = from;
this.to = to;
this.enabled = enabled;
this.comment = comment;
}
/**
* Checks whether the input is a definition of a host rule.
*/
static isHostRule(input: unknown): boolean {
const typed = input as IHostRule;
if (input && typed.kind && typed.kind === Kind) {
return true;
}
return false;
}
toJSON(): IHostRule {
const result: IHostRule = {
kind: Kind,
from : this.from,
to : this.to,
};
if (typeof this.enabled === 'boolean') {
result.enabled = this.enabled;
}
if (this.comment) {
result.comment = this.comment;
}
return result;
}
/**
* Applies `hosts` rules to the URL.
*
* @param value An URL to apply the rules to
* @param rules List of host rules. It is a list of objects containing `from` and `to` properties.
* @return Evaluated URL with hosts rules.
*/
static applyHosts(value: string, rules: HostRule[]): string {
if (!rules || !rules.length) {
return value;
}
for (let i = 0; i < rules.length; i++) {
const rule = rules[i];
const result = HostRule.evaluateRule(value, rule);
if (result) {
value = result;
}
}
return value;
}
/**
* Evaluates hosts rule and applies it to the `url`.
* @param {string} url The URL to evaluate
* @param {HostRule} rule The host rule definition
* @return {string} Processed url.
*/
static evaluateRule(url: string, rule: HostRule): string | undefined {
if (!rule || !rule.from || !rule.to) {
return;
}
const re = HostRule.createRuleRe(rule.from);
if (!re.test(url)) {
return;
}
return url.replace(re, rule.to);
}
/**
* @param input Rule body
* @return Regular expression for the rule.
*/
static createRuleRe(input: string): RegExp {
input = input.replace(/\*/g, '(.*)');
return new RegExp(input, 'gi');
}
}
| 21.682927 | 100 | 0.568898 | 98 | 8 | 0 | 10 | 10 | 10 | 4 | 0 | 17 | 2 | 4 | 8.375 | 973 | 0.018499 | 0.010277 | 0.010277 | 0.002055 | 0.004111 | 0 | 0.447368 | 0.250052 | export const Kind = 'Core#HostRule';
/**
* API Client host rule definition.
*/
export interface IHostRule {
kind?;
/**
* The from rule (may contain asterisks)
*/
from;
/**
* replacement value
*/
to;
/**
* if false the rule is ignored
*/
enabled?;
/**
* optional rule description
*/
comment?;
}
export class HostRule {
kind = Kind;
/**
* The from rule (may contain asterisks)
*/
from = '';
/**
* replacement value
*/
to = '';
/**
* if false the rule is ignored
*/
enabled?;
/**
* optional rule description
*/
comment?;
static fromValues(from, to ) {
const result = new HostRule({
kind: Kind,
from,
to,
enabled: true,
});
return result;
}
/**
* @param input The thing 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,
from: '',
to: '',
};
}
this.new(init);
}
/**
* Creates a new thing clearing anything that is so far defined.
*
* Note, this throws an error when the server is not an API Client thing.
*/
new(init) {
if (!HostRule.isHostRule(init)) {
throw new Error(`Not a HostRule.`);
}
const { from='', to='', enabled, comment } = init;
this.kind = Kind;
this.from = from;
this.to = to;
this.enabled = enabled;
this.comment = comment;
}
/**
* Checks whether the input is a definition of a host rule.
*/
static isHostRule(input) {
const typed = input as IHostRule;
if (input && typed.kind && typed.kind === Kind) {
return true;
}
return false;
}
toJSON() {
const result = {
kind: Kind,
from : this.from,
to : this.to,
};
if (typeof this.enabled === 'boolean') {
result.enabled = this.enabled;
}
if (this.comment) {
result.comment = this.comment;
}
return result;
}
/**
* Applies `hosts` rules to the URL.
*
* @param value An URL to apply the rules to
* @param rules List of host rules. It is a list of objects containing `from` and `to` properties.
* @return Evaluated URL with hosts rules.
*/
static applyHosts(value, rules) {
if (!rules || !rules.length) {
return value;
}
for (let i = 0; i < rules.length; i++) {
const rule = rules[i];
const result = HostRule.evaluateRule(value, rule);
if (result) {
value = result;
}
}
return value;
}
/**
* Evaluates hosts rule and applies it to the `url`.
* @param {string} url The URL to evaluate
* @param {HostRule} rule The host rule definition
* @return {string} Processed url.
*/
static evaluateRule(url, rule) {
if (!rule || !rule.from || !rule.to) {
return;
}
const re = HostRule.createRuleRe(rule.from);
if (!re.test(url)) {
return;
}
return url.replace(re, rule.to);
}
/**
* @param input Rule body
* @return Regular expression for the rule.
*/
static createRuleRe(input) {
input = input.replace(/\*/g, '(.*)');
return new RegExp(input, 'gi');
}
}
|
fed045b4c483f6e9f977e06d25653757940826d8 | 2,325 | ts | TypeScript | src/snippets.ts | hvdb/ado-template-helper | 99379ee7112d98739df9c68e5a1747482c60c7d5 | [
"MIT"
] | 1 | 2022-03-19T22:17:55.000Z | 2022-03-19T22:17:55.000Z | src/snippets.ts | hvdb/ado-template-helper | 99379ee7112d98739df9c68e5a1747482c60c7d5 | [
"MIT"
] | null | null | null | src/snippets.ts | hvdb/ado-template-helper | 99379ee7112d98739df9c68e5a1747482c60c7d5 | [
"MIT"
] | null | null | null | /**
*
*
* @param jsonData Template json data
* @returns the snippet
*/
export function createSnippet(jsonTemplateData: any, prefix: string): string {
if (jsonTemplateData.inputs) {
let snippet = `{\n`;
snippet += `"${jsonTemplateData.friendlyName}": {\n`;
snippet += `"prefix": "${prefix}${jsonTemplateData.name} - ${jsonTemplateData.type}",\n`;
snippet += `"body": [\n`;
snippet += `"- template: ${jsonTemplateData.id}",\n`;
snippet += `" parameters:",\n`;
let requiredIndex = 1;
//Sort on required
jsonTemplateData.inputs.sort((elem: { required: any; }) => elem.required ? -1 : 1);
jsonTemplateData.inputs.forEach((input: any) => {
snippet += createLine(input, requiredIndex);
if (input.required) {
requiredIndex++;
}
});
snippet += `"$${requiredIndex}"\n`;
snippet += `],\n`;
let description = escapeAllSpecialCaracters(jsonTemplateData.description);
snippet += `"description": "${description != '' ? description : ''}"\n`;
snippet += "}\n";
snippet += "}\n";
return snippet;
}
return '';
}
function createLine(input: any, index: number): string {
let line = `" ${input.required ? '' : '#'}${input.name}: `;
if (input.defaultValue && input.required) {
line += `$\{${index}:${escapeAllSpecialCaracters(input.defaultValue)}\} ${displayOptions(input)} # Required `;
} else {
line += input.required ? `$${index} ${displayOptions(input)} # Required ` : `${displayOptions(input)} # Optional `;
}
line += input.helpMarkDown ? ` # ${escapeAllSpecialCaracters(input.helpMarkDown)}",\n` : `",\n`;
return line;
}
function displayOptions(input: any): string {
if (input.options) {
let options = '# Options: ';
for (let keys = Object.keys(input.options), i = 0, end = keys.length; i < end; i++) {
options += `'${keys[i]}'`;
if (i < keys.length - 1) {
options += `, `;
}
}
return options;
}
return '';
}
function escapeAllSpecialCaracters(value: string): string {
return value ? value.toString().replace(/\n/g, '').replace(/\\/g, '/\\\/').replace(/"/g, '\\"') : '';
}
| 33.695652 | 123 | 0.545806 | 52 | 6 | 0 | 8 | 8 | 0 | 3 | 5 | 7 | 0 | 0 | 8.166667 | 601 | 0.023295 | 0.013311 | 0 | 0 | 0 | 0.227273 | 0.318182 | 0.264787 | /**
*
*
* @param jsonData Template json data
* @returns the snippet
*/
export function createSnippet(jsonTemplateData, prefix) {
if (jsonTemplateData.inputs) {
let snippet = `{\n`;
snippet += `"${jsonTemplateData.friendlyName}": {\n`;
snippet += `"prefix": "${prefix}${jsonTemplateData.name} - ${jsonTemplateData.type}",\n`;
snippet += `"body": [\n`;
snippet += `"- template: ${jsonTemplateData.id}",\n`;
snippet += `" parameters:",\n`;
let requiredIndex = 1;
//Sort on required
jsonTemplateData.inputs.sort((elem) => elem.required ? -1 : 1);
jsonTemplateData.inputs.forEach((input) => {
snippet += createLine(input, requiredIndex);
if (input.required) {
requiredIndex++;
}
});
snippet += `"$${requiredIndex}"\n`;
snippet += `],\n`;
let description = escapeAllSpecialCaracters(jsonTemplateData.description);
snippet += `"description": "${description != '' ? description : ''}"\n`;
snippet += "}\n";
snippet += "}\n";
return snippet;
}
return '';
}
/* Example usages of 'createLine' are shown below:
snippet += createLine(input, requiredIndex);
*/
function createLine(input, index) {
let line = `" ${input.required ? '' : '#'}${input.name}: `;
if (input.defaultValue && input.required) {
line += `$\{${index}:${escapeAllSpecialCaracters(input.defaultValue)}\} ${displayOptions(input)} # Required `;
} else {
line += input.required ? `$${index} ${displayOptions(input)} # Required ` : `${displayOptions(input)} # Optional `;
}
line += input.helpMarkDown ? ` # ${escapeAllSpecialCaracters(input.helpMarkDown)}",\n` : `",\n`;
return line;
}
/* Example usages of 'displayOptions' are shown below:
displayOptions(input);
*/
function displayOptions(input) {
if (input.options) {
let options = '# Options: ';
for (let keys = Object.keys(input.options), i = 0, end = keys.length; i < end; i++) {
options += `'${keys[i]}'`;
if (i < keys.length - 1) {
options += `, `;
}
}
return options;
}
return '';
}
/* Example usages of 'escapeAllSpecialCaracters' are shown below:
escapeAllSpecialCaracters(jsonTemplateData.description);
escapeAllSpecialCaracters(input.defaultValue);
escapeAllSpecialCaracters(input.helpMarkDown);
*/
function escapeAllSpecialCaracters(value) {
return value ? value.toString().replace(/\n/g, '').replace(/\\/g, '/\\\/').replace(/"/g, '\\"') : '';
}
|
881cdbe876ebe39e933e8e7d0b4b7855fc22d9ca | 4,848 | ts | TypeScript | packages/utils/src/number.ts | heiyehk/heiye | 425bbd56d841e08c0771ec05656c692d315aed4e | [
"MIT"
] | 2 | 2022-01-11T02:23:09.000Z | 2022-01-11T02:39:07.000Z | packages/utils/src/number.ts | heiyehk/hyjs | 425bbd56d841e08c0771ec05656c692d315aed4e | [
"MIT"
] | null | null | null | packages/utils/src/number.ts | heiyehk/hyjs | 425bbd56d841e08c0771ec05656c692d315aed4e | [
"MIT"
] | null | null | null | /**
* 阿拉伯数字翻译成中文的大写数字
* @param num
* @returns
*/
export const numberToChinese = (num: number | string) => {
const digital = ['零', '一', '二', '三', '四', '五', '六', '七', '八', '九', '十'];
const unit = ['', '十', '百', '仟', '萬', '億', '点', ''];
const splitNumber = String(num).replace(/(^0*)/g, '').split('.');
let index = 0;
let chineseNumber = '';
let len = splitNumber[0].length - 1;
for (; len >= 0; len--) {
switch (index) {
case 0:
chineseNumber = unit[7] + chineseNumber;
break;
case 4:
if (!new RegExp('0{4}//d{' + (splitNumber[0].length - len - 1) + '}$').test(splitNumber[0]))
chineseNumber = unit[4] + chineseNumber;
break;
case 8:
chineseNumber = unit[5] + chineseNumber;
unit[7] = unit[5];
index = 0;
break;
}
if (
index % 4 === 2 &&
splitNumber[0].charAt(len + 2) !== '0' &&
splitNumber[0].charAt(len + 1) == '0'
)
chineseNumber = digital[0] + chineseNumber;
if (splitNumber[0].charAt(len) !== '0')
chineseNumber = digital[Number(splitNumber[0].charAt(len))] + unit[index % 4] + chineseNumber;
index++;
}
if (splitNumber.length > 1) {
// 加上小数部分(如果有小数部分)
chineseNumber += unit[6];
for (let i = 0; i < splitNumber[1].length; i++)
chineseNumber += digital[Number(splitNumber[1].charAt(i))];
}
if (chineseNumber === '一十') chineseNumber = '十';
if (chineseNumber.match(/^一/) && chineseNumber.length === 3)
chineseNumber = chineseNumber.replace('一', '');
return chineseNumber;
};
/**
* 数字转大写金额
* @param num
* @returns
*/
export const convertCurrency = (money: number | string) => {
// 汉字的数字
const cnNums = ['零', '壹', '贰', '叁', '肆', '伍', '陆', '柒', '捌', '玖'];
// 基本单位
const cnIntRadice = ['', '拾', '佰', '仟'];
// 对应整数部分扩展单位
const cnIntUnits = ['', '万', '亿', '兆'];
// 对应小数部分单位
const cnDecUnits = ['角', '分', '毫', '厘'];
// 整数金额时后面跟的字符
const cnInteger = '整';
// 整型完以后的单位
const cnIntLast = '元';
// 最大处理的数字
// eslint-disable-next-line @typescript-eslint/no-loss-of-precision
const maxNum = 999999999999999.9999;
// 金额整数部分
let integerNum;
// 金额小数部分
let decimalNum;
// 输出的中文金额字符串
let chineseStr = '';
// 分离金额后用的数组,预定义
let parts;
if (!money) return '';
money = parseFloat(money as string);
if (money >= maxNum) {
// 超出最大处理数字
return '';
}
if (money == 0) {
chineseStr = cnNums[0] + cnIntLast + cnInteger;
return chineseStr;
}
// 转换为字符串
money = money.toString();
if (money.indexOf('.') == -1) {
integerNum = money;
decimalNum = '';
} else {
parts = money.split('.');
integerNum = parts[0];
decimalNum = parts[1].substr(0, 4);
}
// 获取整型部分转换
if (parseInt(integerNum, 10) > 0) {
let zeroCount = 0;
const IntLen = integerNum.length;
for (let i = 0; i < IntLen; i++) {
const n = integerNum.substr(i, 1);
const p = IntLen - i - 1;
const q = p / 4;
const m = p % 4;
if (n == '0') {
zeroCount++;
} else {
if (zeroCount > 0) {
chineseStr += cnNums[0];
}
// 归零
zeroCount = 0;
chineseStr += cnNums[parseInt(n)] + cnIntRadice[m];
}
if (m == 0 && zeroCount < 4) {
chineseStr += cnIntUnits[q];
}
}
chineseStr += cnIntLast;
}
// 小数部分
if (decimalNum != '') {
const decLen = decimalNum.length;
for (let i = 0; i < decLen; i++) {
const n = decimalNum.substr(i, 1);
if (n != '0') {
chineseStr += cnNums[Number(n)] + cnDecUnits[i];
}
}
}
if (chineseStr == '') {
chineseStr += cnNums[0] + cnIntLast + cnInteger;
} else if (decimalNum == '') {
chineseStr += cnInteger;
}
return chineseStr;
};
/**
* 指定范围内生成随机数字, 默认最小值是0
* @param min
* @default 0
* @param max
* @example
* ``` ts
randomNumber(100);
// 32
randomNumber(1, 3);
// 2
```
*/
export const randomNumber = (min = 0, max: number) => {
return Math.floor(Math.random() * (max - min + 1)) + min;
};
/**
* 千分位分隔
* @param value
* @example
* ``` ts
currency(987654321);
// '987,654,321.00'
currency(987654321, 1);
// '987,654,321.0'
currency(987654321, 0);
// '987,654,321'
```
*/
export const currency = (value: string | number, len = 2) => {
if (!value) return len ? `0.${new Array(len).fill(0).join('')}` : '0';
const newValue = Number(String(value).replace(/[^\d.-]/g, '')).toFixed(len) + '';
const left = newValue.split('.')[0].split('').reverse();
const right = newValue.split('.')[1];
let t = '';
for (let i = 0; i < left.length; i++) {
t += left[i] + ((i + 1) % 3 === 0 && i + 1 !== left.length ? ',' : '');
}
if (right) {
return t.split('').reverse().join('') + '.' + right;
}
return t.split('').reverse().join('');
};
| 25.515789 | 100 | 0.525371 | 128 | 4 | 0 | 6 | 37 | 0 | 0 | 0 | 8 | 0 | 1 | 30 | 1,801 | 0.005552 | 0.020544 | 0 | 0 | 0.000555 | 0 | 0.170213 | 0.249948 | /**
* 阿拉伯数字翻译成中文的大写数字
* @param num
* @returns
*/
export const numberToChinese = (num) => {
const digital = ['零', '一', '二', '三', '四', '五', '六', '七', '八', '九', '十'];
const unit = ['', '十', '百', '仟', '萬', '億', '点', ''];
const splitNumber = String(num).replace(/(^0*)/g, '').split('.');
let index = 0;
let chineseNumber = '';
let len = splitNumber[0].length - 1;
for (; len >= 0; len--) {
switch (index) {
case 0:
chineseNumber = unit[7] + chineseNumber;
break;
case 4:
if (!new RegExp('0{4}//d{' + (splitNumber[0].length - len - 1) + '}$').test(splitNumber[0]))
chineseNumber = unit[4] + chineseNumber;
break;
case 8:
chineseNumber = unit[5] + chineseNumber;
unit[7] = unit[5];
index = 0;
break;
}
if (
index % 4 === 2 &&
splitNumber[0].charAt(len + 2) !== '0' &&
splitNumber[0].charAt(len + 1) == '0'
)
chineseNumber = digital[0] + chineseNumber;
if (splitNumber[0].charAt(len) !== '0')
chineseNumber = digital[Number(splitNumber[0].charAt(len))] + unit[index % 4] + chineseNumber;
index++;
}
if (splitNumber.length > 1) {
// 加上小数部分(如果有小数部分)
chineseNumber += unit[6];
for (let i = 0; i < splitNumber[1].length; i++)
chineseNumber += digital[Number(splitNumber[1].charAt(i))];
}
if (chineseNumber === '一十') chineseNumber = '十';
if (chineseNumber.match(/^一/) && chineseNumber.length === 3)
chineseNumber = chineseNumber.replace('一', '');
return chineseNumber;
};
/**
* 数字转大写金额
* @param num
* @returns
*/
export const convertCurrency = (money) => {
// 汉字的数字
const cnNums = ['零', '壹', '贰', '叁', '肆', '伍', '陆', '柒', '捌', '玖'];
// 基本单位
const cnIntRadice = ['', '拾', '佰', '仟'];
// 对应整数部分扩展单位
const cnIntUnits = ['', '万', '亿', '兆'];
// 对应小数部分单位
const cnDecUnits = ['角', '分', '毫', '厘'];
// 整数金额时后面跟的字符
const cnInteger = '整';
// 整型完以后的单位
const cnIntLast = '元';
// 最大处理的数字
// eslint-disable-next-line @typescript-eslint/no-loss-of-precision
const maxNum = 999999999999999.9999;
// 金额整数部分
let integerNum;
// 金额小数部分
let decimalNum;
// 输出的中文金额字符串
let chineseStr = '';
// 分离金额后用的数组,预定义
let parts;
if (!money) return '';
money = parseFloat(money as string);
if (money >= maxNum) {
// 超出最大处理数字
return '';
}
if (money == 0) {
chineseStr = cnNums[0] + cnIntLast + cnInteger;
return chineseStr;
}
// 转换为字符串
money = money.toString();
if (money.indexOf('.') == -1) {
integerNum = money;
decimalNum = '';
} else {
parts = money.split('.');
integerNum = parts[0];
decimalNum = parts[1].substr(0, 4);
}
// 获取整型部分转换
if (parseInt(integerNum, 10) > 0) {
let zeroCount = 0;
const IntLen = integerNum.length;
for (let i = 0; i < IntLen; i++) {
const n = integerNum.substr(i, 1);
const p = IntLen - i - 1;
const q = p / 4;
const m = p % 4;
if (n == '0') {
zeroCount++;
} else {
if (zeroCount > 0) {
chineseStr += cnNums[0];
}
// 归零
zeroCount = 0;
chineseStr += cnNums[parseInt(n)] + cnIntRadice[m];
}
if (m == 0 && zeroCount < 4) {
chineseStr += cnIntUnits[q];
}
}
chineseStr += cnIntLast;
}
// 小数部分
if (decimalNum != '') {
const decLen = decimalNum.length;
for (let i = 0; i < decLen; i++) {
const n = decimalNum.substr(i, 1);
if (n != '0') {
chineseStr += cnNums[Number(n)] + cnDecUnits[i];
}
}
}
if (chineseStr == '') {
chineseStr += cnNums[0] + cnIntLast + cnInteger;
} else if (decimalNum == '') {
chineseStr += cnInteger;
}
return chineseStr;
};
/**
* 指定范围内生成随机数字, 默认最小值是0
* @param min
* @default 0
* @param max
* @example
* ``` ts
randomNumber(100);
// 32
randomNumber(1, 3);
// 2
```
*/
export const randomNumber = (min = 0, max) => {
return Math.floor(Math.random() * (max - min + 1)) + min;
};
/**
* 千分位分隔
* @param value
* @example
* ``` ts
currency(987654321);
// '987,654,321.00'
currency(987654321, 1);
// '987,654,321.0'
currency(987654321, 0);
// '987,654,321'
```
*/
export const currency = (value, len = 2) => {
if (!value) return len ? `0.${new Array(len).fill(0).join('')}` : '0';
const newValue = Number(String(value).replace(/[^\d.-]/g, '')).toFixed(len) + '';
const left = newValue.split('.')[0].split('').reverse();
const right = newValue.split('.')[1];
let t = '';
for (let i = 0; i < left.length; i++) {
t += left[i] + ((i + 1) % 3 === 0 && i + 1 !== left.length ? ',' : '');
}
if (right) {
return t.split('').reverse().join('') + '.' + right;
}
return t.split('').reverse().join('');
};
|
88616d2acf8d66a97538d1bb1d1d2e0761bd2463 | 3,539 | ts | TypeScript | src/index.ts | NickKelly1/nkp-age | 33e184d01e2e9c69f811931a3210d346cba05243 | [
"MIT"
] | null | null | null | src/index.ts | NickKelly1/nkp-age | 33e184d01e2e9c69f811931a3210d346cba05243 | [
"MIT"
] | 1 | 2022-01-05T19:11:04.000Z | 2022-01-05T22:40:42.000Z | src/index.ts | NickKelly1/nkp-age | 33e184d01e2e9c69f811931a3210d346cba05243 | [
"MIT"
] | null | null | null | export interface TimeDelta {
sign: '' | '+',
years: number,
months: number,
days: number,
hours: number,
minutes: number,
seconds: number,
}
export interface AgeOptions {
/**
* Comparison date
*/
now?: Date;
/**
* Precision
*/
levels?: number;
}
/**
* Get the ymdhms differences between two dates
*
* @param left + date value
* @param right - date value
* @returns difference between the two dates
*/
export function getTimeDelta(
left: Date,
right: Date,
): TimeDelta {
const {
secondsPerSecond: secondsPerSecond,
secondsPerMinute: secondsPerMinute,
secondsPerHour: secondsPerHour,
secondsPerDay: secondsPerDay,
secondsPerMonth: secondsPerMonth,
secondsPerYear: secondsPerYear,
} = getAge.defaults;
const leftMs = left.valueOf();
const rightMs = right.valueOf();
let delta = Math.abs(leftMs - rightMs) / 1000;
const years = Math.floor(delta / secondsPerYear);
delta -= years * secondsPerYear;
const months = Math.floor(delta / secondsPerMonth);
delta -= months * secondsPerMonth;
const days = Math.floor(delta / secondsPerDay);
delta -= days * secondsPerDay;
const hours = Math.floor(delta / secondsPerHour);
delta -= hours * secondsPerHour;
const minutes = Math.floor(delta / secondsPerMinute);
delta -= minutes * secondsPerMinute;
const seconds = Math.floor(delta / secondsPerSecond);
delta -= seconds * secondsPerSecond;
const timeDelta: TimeDelta = {
sign: leftMs < rightMs ? '+' : '',
years,
months,
days,
hours,
minutes,
seconds,
};
return timeDelta;
}
/**
* Get the approximate age of the given date from now
*
* @param birth date to find the age of
* @param options
* @returns approximate age of the date
*
* @example
* ```ts
* '2y3m4d'
* '2y4d1h'
* '3y2m1s'
* '17s'
* ```
*/
export function getAge(
birth: Date,
options?: AgeOptions
): string {
const now = options?.now ?? getAge.defaults.NOW();
const levels = options?.levels ?? getAge.defaults.LEVELS;
const delta = getTimeDelta(now, birth);
let str = delta.sign;
let cnt = 0;
if (levels < 0) {
throw new TypeError(`getAge(): "levels" must be >= 0. Given: ${levels}.`);
}
// years
if (delta.years) {
str += `${delta.years}y`;
cnt += 1;
}
// months
if (cnt >= levels) return str;
if (delta.months) {
str += `${delta.months}m`;
cnt += 1;
}
// days
if (cnt >= levels) return str;
if (delta.days) {
str += `${delta.days}d`;
cnt += 1;
}
// hours
if (cnt >= levels) return str;
if (delta.hours) {
str += `${delta.hours}h`;
cnt += 1;
}
// minutes
if (cnt >= levels) return str;
if (delta.minutes) {
str += `${delta.minutes}m`;
cnt += 1;
}
// seconds
if (cnt >= levels) return str;
if (delta.seconds) {
str += `${delta.seconds}s`;
cnt += 1;
}
// if there is no difference, show zero seconds...
if (cnt === 0) {
str += '0s';
}
return str;
}
/**
* defaults for usage with `@nkp/age` functions
*/
getAge.defaults = {
secondsPerSecond: 1,
secondsPerMinute: 1 * 60,
secondsPerHour : 1 * 60 * 60,
secondsPerDay : 1 * 60 * 60 * 24,
// on average 30.437 days in a month
secondsPerMonth : 1 * 60 * 60 * 24 * 30.437,
// SECONDS_PER_MONTH : 1 * 60 * 60 * 24 * 30,
// on average 365.24 days in a year
secondsPerYear : 1 * 60 * 60 * 24 * 365.24,
// SECONDS_PER_YEAR : 1 * 60 * 60 * 24 * 365,
NOW: (): Date => new Date(),
LEVELS: 3,
};
| 18.925134 | 78 | 0.60356 | 107 | 3 | 0 | 4 | 16 | 9 | 1 | 0 | 8 | 2 | 0 | 25 | 1,137 | 0.006157 | 0.014072 | 0.007916 | 0.001759 | 0 | 0 | 0.25 | 0.233264 | export interface TimeDelta {
sign,
years,
months,
days,
hours,
minutes,
seconds,
}
export interface AgeOptions {
/**
* Comparison date
*/
now?;
/**
* Precision
*/
levels?;
}
/**
* Get the ymdhms differences between two dates
*
* @param left + date value
* @param right - date value
* @returns difference between the two dates
*/
export /* Example usages of 'getTimeDelta' are shown below:
getTimeDelta(now, birth);
*/
function getTimeDelta(
left,
right,
) {
const {
secondsPerSecond: secondsPerSecond,
secondsPerMinute: secondsPerMinute,
secondsPerHour: secondsPerHour,
secondsPerDay: secondsPerDay,
secondsPerMonth: secondsPerMonth,
secondsPerYear: secondsPerYear,
} = getAge.defaults;
const leftMs = left.valueOf();
const rightMs = right.valueOf();
let delta = Math.abs(leftMs - rightMs) / 1000;
const years = Math.floor(delta / secondsPerYear);
delta -= years * secondsPerYear;
const months = Math.floor(delta / secondsPerMonth);
delta -= months * secondsPerMonth;
const days = Math.floor(delta / secondsPerDay);
delta -= days * secondsPerDay;
const hours = Math.floor(delta / secondsPerHour);
delta -= hours * secondsPerHour;
const minutes = Math.floor(delta / secondsPerMinute);
delta -= minutes * secondsPerMinute;
const seconds = Math.floor(delta / secondsPerSecond);
delta -= seconds * secondsPerSecond;
const timeDelta = {
sign: leftMs < rightMs ? '+' : '',
years,
months,
days,
hours,
minutes,
seconds,
};
return timeDelta;
}
/**
* Get the approximate age of the given date from now
*
* @param birth date to find the age of
* @param options
* @returns approximate age of the date
*
* @example
* ```ts
* '2y3m4d'
* '2y4d1h'
* '3y2m1s'
* '17s'
* ```
*/
export /* Example usages of 'getAge' are shown below:
getAge.defaults;
options?.now ?? getAge.defaults.NOW();
options?.levels ?? getAge.defaults.LEVELS;
*
* defaults for usage with `@nkp/age` functions
getAge.defaults = {
secondsPerSecond: 1,
secondsPerMinute: 1 * 60,
secondsPerHour: 1 * 60 * 60,
secondsPerDay: 1 * 60 * 60 * 24,
// on average 30.437 days in a month
secondsPerMonth: 1 * 60 * 60 * 24 * 30.437,
// SECONDS_PER_MONTH : 1 * 60 * 60 * 24 * 30,
// on average 365.24 days in a year
secondsPerYear: 1 * 60 * 60 * 24 * 365.24,
// SECONDS_PER_YEAR : 1 * 60 * 60 * 24 * 365,
NOW: () => new Date(),
LEVELS: 3,
};
*/
function getAge(
birth,
options?
) {
const now = options?.now ?? getAge.defaults.NOW();
const levels = options?.levels ?? getAge.defaults.LEVELS;
const delta = getTimeDelta(now, birth);
let str = delta.sign;
let cnt = 0;
if (levels < 0) {
throw new TypeError(`getAge(): "levels" must be >= 0. Given: ${levels}.`);
}
// years
if (delta.years) {
str += `${delta.years}y`;
cnt += 1;
}
// months
if (cnt >= levels) return str;
if (delta.months) {
str += `${delta.months}m`;
cnt += 1;
}
// days
if (cnt >= levels) return str;
if (delta.days) {
str += `${delta.days}d`;
cnt += 1;
}
// hours
if (cnt >= levels) return str;
if (delta.hours) {
str += `${delta.hours}h`;
cnt += 1;
}
// minutes
if (cnt >= levels) return str;
if (delta.minutes) {
str += `${delta.minutes}m`;
cnt += 1;
}
// seconds
if (cnt >= levels) return str;
if (delta.seconds) {
str += `${delta.seconds}s`;
cnt += 1;
}
// if there is no difference, show zero seconds...
if (cnt === 0) {
str += '0s';
}
return str;
}
/**
* defaults for usage with `@nkp/age` functions
*/
getAge.defaults = {
secondsPerSecond: 1,
secondsPerMinute: 1 * 60,
secondsPerHour : 1 * 60 * 60,
secondsPerDay : 1 * 60 * 60 * 24,
// on average 30.437 days in a month
secondsPerMonth : 1 * 60 * 60 * 24 * 30.437,
// SECONDS_PER_MONTH : 1 * 60 * 60 * 24 * 30,
// on average 365.24 days in a year
secondsPerYear : 1 * 60 * 60 * 24 * 365.24,
// SECONDS_PER_YEAR : 1 * 60 * 60 * 24 * 365,
NOW: () => new Date(),
LEVELS: 3,
};
|