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
|
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
3d0ad5954a5cc8c79023f19dfdaac7d28d1bcf53 | 1,536 | ts | TypeScript | src/core/lib/sortedArray.ts | KristofJannes/owebsync-js | 5614314e46596dc94f4703ed596370a72dcaab87 | [
"CC0-1.0"
] | 3 | 2022-02-08T04:50:02.000Z | 2022-02-18T22:29:22.000Z | src/core/lib/sortedArray.ts | KristofJannes/owebsync-js | 5614314e46596dc94f4703ed596370a72dcaab87 | [
"CC0-1.0"
] | null | null | null | src/core/lib/sortedArray.ts | KristofJannes/owebsync-js | 5614314e46596dc94f4703ed596370a72dcaab87 | [
"CC0-1.0"
] | 2 | 2022-02-08T05:04:44.000Z | 2022-03-31T08:03:09.000Z | /**
* Array which keeps the objects sorted on a given field/key within that object.
* Use the _upsert to add or update an item.
* Use _get to retrieve an item (in log time).
*/
export class SortedArray<
K extends string,
T extends Record<K, string>
> extends Array<T> {
private readonly _key: K;
public constructor(key: K, ...items: T[]) {
super(...items);
this._key = key;
}
public _has(key: T[K]): boolean {
const { found } = this._binarySearch(key);
return found;
}
public _get(key: T[K]): T | null {
const { index, found } = this._binarySearch(key);
if (found) {
return this[index];
}
return null;
}
public _upsert(item: T): void {
const { index, found } = this._binarySearch(item[this._key]);
if (found) {
this[index] = item;
} else {
this.splice(index, 0, item);
}
}
public _delete(key: T[K]): void {
const { index, found } = this._binarySearch(key);
if (found) {
this.splice(index, 1);
}
}
private _binarySearch(value: T[K]): { index: number; found: boolean } {
let start = 0;
let end = this.length - 1;
while (start <= end) {
const index = Math.floor((start + end) / 2);
if (value > this[index][this._key]) {
start = index + 1;
} else if (value < this[index][this._key]) {
end = index - 1;
} else {
return {
index: index,
found: true,
};
}
}
return {
index: start,
found: false,
};
}
}
| 22.588235 | 80 | 0.552734 | 56 | 6 | 0 | 7 | 7 | 1 | 1 | 0 | 7 | 1 | 0 | 6.333333 | 459 | 0.028322 | 0.015251 | 0.002179 | 0.002179 | 0 | 0 | 0.333333 | 0.289487 | /**
* Array which keeps the objects sorted on a given field/key within that object.
* Use the _upsert to add or update an item.
* Use _get to retrieve an item (in log time).
*/
export class SortedArray<
K extends string,
T extends Record<K, string>
> extends Array<T> {
private readonly _key;
public constructor(key, ...items) {
super(...items);
this._key = key;
}
public _has(key) {
const { found } = this._binarySearch(key);
return found;
}
public _get(key) {
const { index, found } = this._binarySearch(key);
if (found) {
return this[index];
}
return null;
}
public _upsert(item) {
const { index, found } = this._binarySearch(item[this._key]);
if (found) {
this[index] = item;
} else {
this.splice(index, 0, item);
}
}
public _delete(key) {
const { index, found } = this._binarySearch(key);
if (found) {
this.splice(index, 1);
}
}
private _binarySearch(value) {
let start = 0;
let end = this.length - 1;
while (start <= end) {
const index = Math.floor((start + end) / 2);
if (value > this[index][this._key]) {
start = index + 1;
} else if (value < this[index][this._key]) {
end = index - 1;
} else {
return {
index: index,
found: true,
};
}
}
return {
index: start,
found: false,
};
}
}
|
3d34dd6f559ba42cebc06a9182be39b29ef9d486 | 3,378 | ts | TypeScript | packages/web-koa/src/utils.ts | chriswjou/midway | b7a5c817d2316b93967367c34cff20a98b1ce4b7 | [
"MIT"
] | 1 | 2022-03-30T09:17:19.000Z | 2022-03-30T09:17:19.000Z | packages/web-koa/src/utils.ts | chriswjou/midway | b7a5c817d2316b93967367c34cff20a98b1ce4b7 | [
"MIT"
] | null | null | null | packages/web-koa/src/utils.ts | chriswjou/midway | b7a5c817d2316b93967367c34cff20a98b1ce4b7 | [
"MIT"
] | null | null | null | export function detectStatus(err) {
// detect status
let status = err.status || 500;
if (status < 200) {
// invalid status consider as 500, like urllib will return -1 status
status = 500;
}
return status;
}
export function accepts(ctx) {
if (acceptJSON(ctx)) return 'json';
return 'html';
}
function acceptJSON(ctx) {
if (ctx.path.endsWith('.json')) return true;
if (ctx.response.type && this.response.type.indexOf('json') >= 0) return true;
if (ctx.accepts('html', 'text', 'json') === 'json') return true;
return false;
}
export function sendToWormhole(stream): Promise<void> {
return new Promise<void>(resolve => {
if (typeof stream.resume !== 'function') {
return resolve();
}
// unpipe it
stream.unpipe && stream.unpipe();
// enable resume first
stream.resume();
if (stream._readableState && stream._readableState.ended) {
return resolve();
}
if (!stream.readable || stream.destroyed) {
return resolve();
}
function cleanup() {
stream.removeListener('end', onEnd);
stream.removeListener('close', onEnd);
stream.removeListener('error', onError);
}
function onEnd() {
cleanup();
resolve();
}
function onError() {
cleanup();
resolve();
}
stream.on('end', onEnd);
stream.on('close', onEnd);
stream.on('error', onError);
});
}
export function isProduction(app) {
return app.getEnv() !== 'local' && app.getEnv() !== 'unittest';
}
export const tpl = `
<!DOCTYPE html>
<html>
<head>
<title>Error - {{status}}</title>
<meta name="viewport" content="user-scalable=no, width=device-width, initial-scale=1.0, maximum-scale=1.0">
<style>
body {
padding: 50px 80px;
font: 14px "Helvetica Neue", Helvetica, sans-serif;
}
h1 {
font-size: 2em;
margin-bottom: 5px;
}
pre {
font-size: .8em;
}
</style>
</head>
<body>
<div id="error">
<h1>Error</h1>
<p>Looks like something broke!</p>
<p><h2>Stack</h2></p>
<pre>
<code>
{{stack}}
</code>
</pre>
<p><h2>Error Code</h2></p>
<pre>
<code>
{{errorCode}}
</code>
</pre>
</div>
</body>
</html>`;
const matchHtmlRegExp = /["'&<>]/;
/**
* Escape special characters in the given string of text.
*
* @param {string} string The string to escape for inserting into HTML
* @return {string}
* @public
*/
export function escapeHtml(string) {
const str = '' + string;
const match = matchHtmlRegExp.exec(str);
if (!match) {
return str;
}
let escape;
let html = '';
let index = 0;
let lastIndex = 0;
for (index = match.index; index < str.length; index++) {
switch (str.charCodeAt(index)) {
case 34: // "
escape = '"';
break;
case 38: // &
escape = '&';
break;
case 39: // '
escape = ''';
break;
case 60: // <
escape = '<';
break;
case 62: // >
escape = '>';
break;
default:
continue;
}
if (lastIndex !== index) {
html += str.substring(lastIndex, index);
}
lastIndex = index + 1;
html += escape;
}
return lastIndex !== index ? html + str.substring(lastIndex, index) : html;
}
| 20.723926 | 111 | 0.55151 | 129 | 10 | 0 | 7 | 9 | 0 | 3 | 0 | 2 | 0 | 1 | 11.1 | 991 | 0.017154 | 0.009082 | 0 | 0 | 0.001009 | 0 | 0.076923 | 0.240377 | export function detectStatus(err) {
// detect status
let status = err.status || 500;
if (status < 200) {
// invalid status consider as 500, like urllib will return -1 status
status = 500;
}
return status;
}
export /* Example usages of 'accepts' are shown below:
ctx.accepts('html', 'text', 'json') === 'json';
*/
function accepts(ctx) {
if (acceptJSON(ctx)) return 'json';
return 'html';
}
/* Example usages of 'acceptJSON' are shown below:
acceptJSON(ctx);
*/
function acceptJSON(ctx) {
if (ctx.path.endsWith('.json')) return true;
if (ctx.response.type && this.response.type.indexOf('json') >= 0) return true;
if (ctx.accepts('html', 'text', 'json') === 'json') return true;
return false;
}
export function sendToWormhole(stream) {
return new Promise<void>(resolve => {
if (typeof stream.resume !== 'function') {
return resolve();
}
// unpipe it
stream.unpipe && stream.unpipe();
// enable resume first
stream.resume();
if (stream._readableState && stream._readableState.ended) {
return resolve();
}
if (!stream.readable || stream.destroyed) {
return resolve();
}
/* Example usages of 'cleanup' are shown below:
cleanup();
*/
function cleanup() {
stream.removeListener('end', onEnd);
stream.removeListener('close', onEnd);
stream.removeListener('error', onError);
}
/* Example usages of 'onEnd' are shown below:
stream.removeListener('end', onEnd);
stream.removeListener('close', onEnd);
stream.on('end', onEnd);
stream.on('close', onEnd);
*/
function onEnd() {
cleanup();
resolve();
}
/* Example usages of 'onError' are shown below:
stream.removeListener('error', onError);
stream.on('error', onError);
*/
function onError() {
cleanup();
resolve();
}
stream.on('end', onEnd);
stream.on('close', onEnd);
stream.on('error', onError);
});
}
export function isProduction(app) {
return app.getEnv() !== 'local' && app.getEnv() !== 'unittest';
}
export const tpl = `
<!DOCTYPE html>
<html>
<head>
<title>Error - {{status}}</title>
<meta name="viewport" content="user-scalable=no, width=device-width, initial-scale=1.0, maximum-scale=1.0">
<style>
body {
padding: 50px 80px;
font: 14px "Helvetica Neue", Helvetica, sans-serif;
}
h1 {
font-size: 2em;
margin-bottom: 5px;
}
pre {
font-size: .8em;
}
</style>
</head>
<body>
<div id="error">
<h1>Error</h1>
<p>Looks like something broke!</p>
<p><h2>Stack</h2></p>
<pre>
<code>
{{stack}}
</code>
</pre>
<p><h2>Error Code</h2></p>
<pre>
<code>
{{errorCode}}
</code>
</pre>
</div>
</body>
</html>`;
const matchHtmlRegExp = /["'&<>]/;
/**
* Escape special characters in the given string of text.
*
* @param {string} string The string to escape for inserting into HTML
* @return {string}
* @public
*/
export function escapeHtml(string) {
const str = '' + string;
const match = matchHtmlRegExp.exec(str);
if (!match) {
return str;
}
let escape;
let html = '';
let index = 0;
let lastIndex = 0;
for (index = match.index; index < str.length; index++) {
switch (str.charCodeAt(index)) {
case 34: // "
escape = '"';
break;
case 38: // &
escape = '&';
break;
case 39: // '
escape = ''';
break;
case 60: // <
escape = '<';
break;
case 62: // >
escape = '>';
break;
default:
continue;
}
if (lastIndex !== index) {
html += str.substring(lastIndex, index);
}
lastIndex = index + 1;
html += escape;
}
return lastIndex !== index ? html + str.substring(lastIndex, index) : html;
}
|
c8affc96e6a86078c132ae284df0f88effac6158 | 3,897 | ts | TypeScript | src/util/Color.ts | Varunda/honu | 4dcb7e042c8f934a96df0b6b1987b3651864b0b3 | [
"MIT"
] | 1 | 2022-02-15T23:48:28.000Z | 2022-02-15T23:48:28.000Z | src/util/Color.ts | Varunda/honu | 4dcb7e042c8f934a96df0b6b1987b3651864b0b3 | [
"MIT"
] | null | null | null | src/util/Color.ts | Varunda/honu | 4dcb7e042c8f934a96df0b6b1987b3651864b0b3 | [
"MIT"
] | 1 | 2022-02-17T18:49:25.000Z | 2022-02-17T18:49:25.000Z |
export class RGB {
public red: number = 0;
public green: number = 0;
public blue: number = 0;
}
export default class ColorUtils {
public static VS: string = "#cf17cf";
public static NC: string = "#3f7fff";
public static TR: string = "#ea5e5e";
public static NS: string = "#cbcbcb";
public static getFactionColor(factionID: number): string {
if (factionID == 1) {
return ColorUtils.VS;
} else if (factionID == 2) {
return ColorUtils.NC;
} else if (factionID == 3) {
return ColorUtils.TR;
} else if (factionID == 4) {
return ColorUtils.NS;
}
return "";
}
/**
* Create a single random color
*/
public static randomColorSingle(): string {
return ColorUtils.randomColor(Math.random(), 1, 0);
}
/**
* Create a series of random colors
* @param hue
* @param total
*/
public static randomColors(hue: number, total: number): string[] {
return Array.from(Array(total)).map((_, index) => ColorUtils.randomColor(hue, total, index));
}
/**
* Create a random pastel color
* @param hue
* @param total
* @param index
*/
public static randomColor(hue: number, total: number, index: number): string {
const diff: number = 0.618033988749895;
//let hue: number = Math.random();
hue += index / total;
hue += diff;
hue %= 1;
let sat: number = 0.5;
let val: number = 0.95;
let r: number = 0;
let g: number = 0;
let b: number = 0;
let i = ~~(hue * 6);
let f = hue * 6 - i;
let p = val * (1 - sat);
let q = val * (1 - f * sat);
let t = val * (1 - (1 - f) * sat);
switch (i % 6) {
case 0: r = val; g = t; b = p; break;
case 1: r = q; g = val; b = p; break;
case 2: r = p; g = val; b = t; break;
case 3: r = p; g = q; b = val; break;
case 4: r = t; g = p; b = val; break;
case 5: r = val; g = p; b = q; break;
}
return `rgba(${~~(r * 256)}, ${~~(g * 256)}, ${~~(b * 256)}, 1)`;
}
/**
* Create a gradient between 2 colors, using HSV for the transform, instead of RGB
* @param fade What percentage of the gradient the resulting value will be
* @param c1
* @param c2
* @param c3
*/
public static colorGradient(fade: number, c1: RGB, c2: RGB, c3?: RGB): RGB {
let color1: RGB = c1;
let color2: RGB = c2;
// Do we have 3 colors for the gradient? Need to adjust the params.
if (c3) {
fade = fade * 2;
// Find which interval to use and adjust the fade percentage
if (fade >= 1) {
fade -= 1;
color1 = c2;
color2 = c3;
}
}
const diffRed: number = color2.red - color1.red;
const diffGreen: number = color2.green - color1.green;
const diffBlue: number = color2.blue - color1.blue;
const gradient: RGB = new RGB();
gradient.red = parseInt(Math.floor(color1.red + (diffRed * fade)).toString(), 10);
gradient.green = parseInt(Math.floor(color1.green + (diffGreen * fade)).toString(), 10);
gradient.blue = parseInt(Math.floor(color1.blue + (diffBlue * fade)).toString(), 10);
return gradient;
}
/**
* Convert a RGB value into a CSS string
* @param rgb
*/
public static rgbToString(rgb: RGB): string {
return `rgb(${rgb.red}, ${rgb.green}, ${rgb.blue})`;
}
/**
* Get a random RGB color
*/
public static randomRGB(): RGB {
return {
red: Math.floor(Math.random() * (235 - 52 + 1) + 52),
green: Math.floor(Math.random() * (235 - 52 + 1) + 52),
blue: Math.floor(Math.random() * (235 - 52 + 1) + 52)
};
}
}
| 28.445255 | 101 | 0.52117 | 85 | 8 | 0 | 13 | 17 | 7 | 1 | 0 | 28 | 2 | 0 | 7.5 | 1,195 | 0.017573 | 0.014226 | 0.005858 | 0.001674 | 0 | 0 | 0.622222 | 0.259795 |
export class RGB {
public red = 0;
public green = 0;
public blue = 0;
}
export default class ColorUtils {
public static VS = "#cf17cf";
public static NC = "#3f7fff";
public static TR = "#ea5e5e";
public static NS = "#cbcbcb";
public static getFactionColor(factionID) {
if (factionID == 1) {
return ColorUtils.VS;
} else if (factionID == 2) {
return ColorUtils.NC;
} else if (factionID == 3) {
return ColorUtils.TR;
} else if (factionID == 4) {
return ColorUtils.NS;
}
return "";
}
/**
* Create a single random color
*/
public static randomColorSingle() {
return ColorUtils.randomColor(Math.random(), 1, 0);
}
/**
* Create a series of random colors
* @param hue
* @param total
*/
public static randomColors(hue, total) {
return Array.from(Array(total)).map((_, index) => ColorUtils.randomColor(hue, total, index));
}
/**
* Create a random pastel color
* @param hue
* @param total
* @param index
*/
public static randomColor(hue, total, index) {
const diff = 0.618033988749895;
//let hue: number = Math.random();
hue += index / total;
hue += diff;
hue %= 1;
let sat = 0.5;
let val = 0.95;
let r = 0;
let g = 0;
let b = 0;
let i = ~~(hue * 6);
let f = hue * 6 - i;
let p = val * (1 - sat);
let q = val * (1 - f * sat);
let t = val * (1 - (1 - f) * sat);
switch (i % 6) {
case 0: r = val; g = t; b = p; break;
case 1: r = q; g = val; b = p; break;
case 2: r = p; g = val; b = t; break;
case 3: r = p; g = q; b = val; break;
case 4: r = t; g = p; b = val; break;
case 5: r = val; g = p; b = q; break;
}
return `rgba(${~~(r * 256)}, ${~~(g * 256)}, ${~~(b * 256)}, 1)`;
}
/**
* Create a gradient between 2 colors, using HSV for the transform, instead of RGB
* @param fade What percentage of the gradient the resulting value will be
* @param c1
* @param c2
* @param c3
*/
public static colorGradient(fade, c1, c2, c3?) {
let color1 = c1;
let color2 = c2;
// Do we have 3 colors for the gradient? Need to adjust the params.
if (c3) {
fade = fade * 2;
// Find which interval to use and adjust the fade percentage
if (fade >= 1) {
fade -= 1;
color1 = c2;
color2 = c3;
}
}
const diffRed = color2.red - color1.red;
const diffGreen = color2.green - color1.green;
const diffBlue = color2.blue - color1.blue;
const gradient = new RGB();
gradient.red = parseInt(Math.floor(color1.red + (diffRed * fade)).toString(), 10);
gradient.green = parseInt(Math.floor(color1.green + (diffGreen * fade)).toString(), 10);
gradient.blue = parseInt(Math.floor(color1.blue + (diffBlue * fade)).toString(), 10);
return gradient;
}
/**
* Convert a RGB value into a CSS string
* @param rgb
*/
public static rgbToString(rgb) {
return `rgb(${rgb.red}, ${rgb.green}, ${rgb.blue})`;
}
/**
* Get a random RGB color
*/
public static randomRGB() {
return {
red: Math.floor(Math.random() * (235 - 52 + 1) + 52),
green: Math.floor(Math.random() * (235 - 52 + 1) + 52),
blue: Math.floor(Math.random() * (235 - 52 + 1) + 52)
};
}
}
|
c8c0eb3cd54ad278f0d858d396c8e71c98b9926b | 2,286 | ts | TypeScript | src/handpose/util.ts | BTTHuyen/Human_library | ac44363382a10a753f3e99dfb18fd75ff6eafbec | [
"MIT"
] | null | null | null | src/handpose/util.ts | BTTHuyen/Human_library | ac44363382a10a753f3e99dfb18fd75ff6eafbec | [
"MIT"
] | null | null | null | src/handpose/util.ts | BTTHuyen/Human_library | ac44363382a10a753f3e99dfb18fd75ff6eafbec | [
"MIT"
] | 1 | 2022-01-05T23:18:23.000Z | 2022-01-05T23:18:23.000Z | export function normalizeRadians(angle) {
return angle - 2 * Math.PI * Math.floor((angle + Math.PI) / (2 * Math.PI));
}
export function computeRotation(point1, point2) {
const radians = Math.PI / 2 - Math.atan2(-(point2[1] - point1[1]), point2[0] - point1[0]);
return normalizeRadians(radians);
}
export const buildTranslationMatrix = (x, y) => [[1, 0, x], [0, 1, y], [0, 0, 1]];
export function dot(v1, v2) {
let product = 0;
for (let i = 0; i < v1.length; i++) {
product += v1[i] * v2[i];
}
return product;
}
export function getColumnFrom2DArr(arr, columnIndex) {
const column: Array<number> = [];
for (let i = 0; i < arr.length; i++) {
column.push(arr[i][columnIndex]);
}
return column;
}
export function multiplyTransformMatrices(mat1, mat2) {
const product: Array<number[]> = [];
const size = mat1.length;
for (let row = 0; row < size; row++) {
product.push([]);
for (let col = 0; col < size; col++) {
product[row].push(dot(mat1[row], getColumnFrom2DArr(mat2, col)));
}
}
return product;
}
export function buildRotationMatrix(rotation, center) {
const cosA = Math.cos(rotation);
const sinA = Math.sin(rotation);
const rotationMatrix = [[cosA, -sinA, 0], [sinA, cosA, 0], [0, 0, 1]];
const translationMatrix = buildTranslationMatrix(center[0], center[1]);
const translationTimesRotation = multiplyTransformMatrices(translationMatrix, rotationMatrix);
const negativeTranslationMatrix = buildTranslationMatrix(-center[0], -center[1]);
return multiplyTransformMatrices(translationTimesRotation, negativeTranslationMatrix);
}
export function invertTransformMatrix(matrix) {
const rotationComponent = [[matrix[0][0], matrix[1][0]], [matrix[0][1], matrix[1][1]]];
const translationComponent = [matrix[0][2], matrix[1][2]];
const invertedTranslation = [
-dot(rotationComponent[0], translationComponent),
-dot(rotationComponent[1], translationComponent),
];
return [
rotationComponent[0].concat(invertedTranslation[0]),
rotationComponent[1].concat(invertedTranslation[1]),
[0, 0, 1],
];
}
export function rotatePoint(homogeneousCoordinate, rotationMatrix) {
return [
dot(homogeneousCoordinate, rotationMatrix[0]),
dot(homogeneousCoordinate, rotationMatrix[1]),
];
}
| 32.657143 | 96 | 0.681977 | 61 | 9 | 0 | 16 | 19 | 0 | 5 | 0 | 2 | 0 | 0 | 5 | 689 | 0.036284 | 0.027576 | 0 | 0 | 0 | 0 | 0.045455 | 0.346276 | export /* Example usages of 'normalizeRadians' are shown below:
normalizeRadians(radians);
*/
function normalizeRadians(angle) {
return angle - 2 * Math.PI * Math.floor((angle + Math.PI) / (2 * Math.PI));
}
export function computeRotation(point1, point2) {
const radians = Math.PI / 2 - Math.atan2(-(point2[1] - point1[1]), point2[0] - point1[0]);
return normalizeRadians(radians);
}
export /* Example usages of 'buildTranslationMatrix' are shown below:
buildTranslationMatrix(center[0], center[1]);
buildTranslationMatrix(-center[0], -center[1]);
*/
const buildTranslationMatrix = (x, y) => [[1, 0, x], [0, 1, y], [0, 0, 1]];
export /* Example usages of 'dot' are shown below:
product[row].push(dot(mat1[row], getColumnFrom2DArr(mat2, col)));
-dot(rotationComponent[0], translationComponent);
-dot(rotationComponent[1], translationComponent);
dot(homogeneousCoordinate, rotationMatrix[0]);
dot(homogeneousCoordinate, rotationMatrix[1]);
*/
function dot(v1, v2) {
let product = 0;
for (let i = 0; i < v1.length; i++) {
product += v1[i] * v2[i];
}
return product;
}
export /* Example usages of 'getColumnFrom2DArr' are shown below:
product[row].push(dot(mat1[row], getColumnFrom2DArr(mat2, col)));
*/
function getColumnFrom2DArr(arr, columnIndex) {
const column = [];
for (let i = 0; i < arr.length; i++) {
column.push(arr[i][columnIndex]);
}
return column;
}
export /* Example usages of 'multiplyTransformMatrices' are shown below:
multiplyTransformMatrices(translationMatrix, rotationMatrix);
multiplyTransformMatrices(translationTimesRotation, negativeTranslationMatrix);
*/
function multiplyTransformMatrices(mat1, mat2) {
const product = [];
const size = mat1.length;
for (let row = 0; row < size; row++) {
product.push([]);
for (let col = 0; col < size; col++) {
product[row].push(dot(mat1[row], getColumnFrom2DArr(mat2, col)));
}
}
return product;
}
export function buildRotationMatrix(rotation, center) {
const cosA = Math.cos(rotation);
const sinA = Math.sin(rotation);
const rotationMatrix = [[cosA, -sinA, 0], [sinA, cosA, 0], [0, 0, 1]];
const translationMatrix = buildTranslationMatrix(center[0], center[1]);
const translationTimesRotation = multiplyTransformMatrices(translationMatrix, rotationMatrix);
const negativeTranslationMatrix = buildTranslationMatrix(-center[0], -center[1]);
return multiplyTransformMatrices(translationTimesRotation, negativeTranslationMatrix);
}
export function invertTransformMatrix(matrix) {
const rotationComponent = [[matrix[0][0], matrix[1][0]], [matrix[0][1], matrix[1][1]]];
const translationComponent = [matrix[0][2], matrix[1][2]];
const invertedTranslation = [
-dot(rotationComponent[0], translationComponent),
-dot(rotationComponent[1], translationComponent),
];
return [
rotationComponent[0].concat(invertedTranslation[0]),
rotationComponent[1].concat(invertedTranslation[1]),
[0, 0, 1],
];
}
export function rotatePoint(homogeneousCoordinate, rotationMatrix) {
return [
dot(homogeneousCoordinate, rotationMatrix[0]),
dot(homogeneousCoordinate, rotationMatrix[1]),
];
}
|
c8f3f819bd5039c1d8f889b19249a668d44713b4 | 1,694 | ts | TypeScript | problemset/find-peak-element/index.ts | OUDUIDUI/leet-code | 50e61ce16d1c419ccefc075ae9ead721cdd1cdbb | [
"MIT"
] | 6 | 2022-01-17T03:19:56.000Z | 2022-01-17T05:45:39.000Z | problemset/find-peak-element/index.ts | OUDUIDUI/leet-code | 50e61ce16d1c419ccefc075ae9ead721cdd1cdbb | [
"MIT"
] | null | null | null | problemset/find-peak-element/index.ts | OUDUIDUI/leet-code | 50e61ce16d1c419ccefc075ae9ead721cdd1cdbb | [
"MIT"
] | null | null | null | /**
* 找到最大值
* desc 时间复杂度 O(N) 空间复杂度 O(1)
* @param nums
*/
export function findPeakElement(nums: number[]): number {
let idx = 0
for (let i = 1; i < nums.length; i++) {
if (nums[i] > nums[idx])
idx = i
}
return idx
}
/**
* 迭代爬坡
* desc 时间复杂度 O(N) 空间复杂度 O(1)
* @param nums
*/
export function findPeakElement2(nums: number[]): number {
const len = nums.length
let idx = (Math.random() * len) >> 0 // 从随机点出发
// 如果不是在峰值,进行行走
while (!(compare(idx - 1, idx) < 0 && compare(idx, idx + 1) > 0)) {
idx
= compare(idx, idx + 1) < 0 ? idx + 1 /* 向右走 */ : idx - 1 /* 向左走 */
}
return idx
// 比较两个点大小
function compare(i: number, j: number): -1 | 0 | 1 {
const num1 = get(i)
const num2 = get(j)
if (num1 === num2) return 0
return num1 > num2 ? 1 : -1
}
// 取值,考虑边缘情况
function get(i: number): number {
return i === -1 || i === len ? -Infinity : nums[i]
}
}
/**
* 迭代爬坡
* desc 时间复杂度 O(logN) 空间复杂度 O(1)
* @param nums
*/
export function findPeakElement3(nums: number[]): number {
const len = nums.length
let left = 0
let right = len - 1
let ans = -1
while (left <= right) {
const mid = (left + right) >> 1
if (compare(mid - 1, mid) < 0 && compare(mid, mid + 1) > 0) {
ans = mid
break
}
if (compare(mid, mid + 1) < 0)
left = mid + 1
else
right = mid - 1
}
return ans
// 比较两个点大小
function compare(i: number, j: number): -1 | 0 | 1 {
const num1 = get(i)
const num2 = get(j)
if (num1 === num2) return 0
return num1 > num2 ? 1 : -1
}
// 取值,考虑边缘情况
function get(i: number): number {
return i === -1 || i === len ? -Infinity : nums[i]
}
}
| 19.697674 | 73 | 0.528926 | 53 | 7 | 0 | 9 | 13 | 0 | 2 | 0 | 14 | 0 | 0 | 8.142857 | 691 | 0.023155 | 0.018813 | 0 | 0 | 0 | 0 | 0.482759 | 0.285589 | /**
* 找到最大值
* desc 时间复杂度 O(N) 空间复杂度 O(1)
* @param nums
*/
export function findPeakElement(nums) {
let idx = 0
for (let i = 1; i < nums.length; i++) {
if (nums[i] > nums[idx])
idx = i
}
return idx
}
/**
* 迭代爬坡
* desc 时间复杂度 O(N) 空间复杂度 O(1)
* @param nums
*/
export function findPeakElement2(nums) {
const len = nums.length
let idx = (Math.random() * len) >> 0 // 从随机点出发
// 如果不是在峰值,进行行走
while (!(compare(idx - 1, idx) < 0 && compare(idx, idx + 1) > 0)) {
idx
= compare(idx, idx + 1) < 0 ? idx + 1 /* 向右走 */ : idx - 1 /* 向左走 */
}
return idx
// 比较两个点大小
/* Example usages of 'compare' are shown below:
compare(idx - 1, idx) < 0 && compare(idx, idx + 1) > 0;
idx
= compare(idx, idx + 1) < 0 ? idx + 1 向右走 : idx - 1 向左走 ;
compare(mid - 1, mid) < 0 && compare(mid, mid + 1) > 0;
compare(mid, mid + 1) < 0;
*/
/* Example usages of 'compare' are shown below:
compare(idx - 1, idx) < 0 && compare(idx, idx + 1) > 0;
idx
= compare(idx, idx + 1) < 0 ? idx + 1 向右走 : idx - 1 向左走 ;
compare(mid - 1, mid) < 0 && compare(mid, mid + 1) > 0;
compare(mid, mid + 1) < 0;
*/
function compare(i, j) {
const num1 = get(i)
const num2 = get(j)
if (num1 === num2) return 0
return num1 > num2 ? 1 : -1
}
// 取值,考虑边缘情况
/* Example usages of 'get' are shown below:
get(i);
get(j);
*/
/* Example usages of 'get' are shown below:
get(i);
get(j);
*/
function get(i) {
return i === -1 || i === len ? -Infinity : nums[i]
}
}
/**
* 迭代爬坡
* desc 时间复杂度 O(logN) 空间复杂度 O(1)
* @param nums
*/
export function findPeakElement3(nums) {
const len = nums.length
let left = 0
let right = len - 1
let ans = -1
while (left <= right) {
const mid = (left + right) >> 1
if (compare(mid - 1, mid) < 0 && compare(mid, mid + 1) > 0) {
ans = mid
break
}
if (compare(mid, mid + 1) < 0)
left = mid + 1
else
right = mid - 1
}
return ans
// 比较两个点大小
/* Example usages of 'compare' are shown below:
compare(idx - 1, idx) < 0 && compare(idx, idx + 1) > 0;
idx
= compare(idx, idx + 1) < 0 ? idx + 1 向右走 : idx - 1 向左走 ;
compare(mid - 1, mid) < 0 && compare(mid, mid + 1) > 0;
compare(mid, mid + 1) < 0;
*/
/* Example usages of 'compare' are shown below:
compare(idx - 1, idx) < 0 && compare(idx, idx + 1) > 0;
idx
= compare(idx, idx + 1) < 0 ? idx + 1 向右走 : idx - 1 向左走 ;
compare(mid - 1, mid) < 0 && compare(mid, mid + 1) > 0;
compare(mid, mid + 1) < 0;
*/
function compare(i, j) {
const num1 = get(i)
const num2 = get(j)
if (num1 === num2) return 0
return num1 > num2 ? 1 : -1
}
// 取值,考虑边缘情况
/* Example usages of 'get' are shown below:
get(i);
get(j);
*/
/* Example usages of 'get' are shown below:
get(i);
get(j);
*/
function get(i) {
return i === -1 || i === len ? -Infinity : nums[i]
}
}
|
051d0ef9c28097d13fc7970423edf487fcbf8dee | 1,749 | ts | TypeScript | src/app/utils/formatters.ts | ffalt/jamberry | 24ea838b11c84b6805d698d4c8c7a0aae12fd7f9 | [
"MIT"
] | null | null | null | src/app/utils/formatters.ts | ffalt/jamberry | 24ea838b11c84b6805d698d4c8c7a0aae12fd7f9 | [
"MIT"
] | 1 | 2022-03-24T15:33:52.000Z | 2022-03-24T15:33:52.000Z | src/app/utils/formatters.ts | ffalt/jamberry | 24ea838b11c84b6805d698d4c8c7a0aae12fd7f9 | [
"MIT"
] | null | null | null | export function padTime(val: number): string {
return (val <= 9) ? `0${val.toString()}` : val.toString();
}
export function splitTime(value: number): { days: number; hours: number; minutes: number; seconds: number } {
const duration = {
days: 0,
hours: 0,
minutes: 0,
seconds: 0
};
let delta = value;
duration.days = Math.floor(delta / 86400);
delta -= duration.days * 86400;
// calculate (and subtract) whole hours
duration.hours = Math.floor(delta / 3600) % 24;
delta -= duration.hours * 3600;
// calculate (and subtract) whole minutes
duration.minutes = Math.floor(delta / 60) % 60;
delta -= duration.minutes * 60;
// what's left is seconds
duration.seconds = Math.round(delta % 60);
return duration;
}
export function formatDuration(val: number): string {
const time = splitTime(val / 1000);
const duration: Array<string> = [];
if (time.days > 0) {
duration.push(`${time.days.toString() }d `);
}
if (time.hours > 0) {
if (duration.length > 0) {
duration.push(`${padTime(time.hours) }:`);
} else {
duration.push(`${time.hours.toString() }:`);
}
}
duration.push(padTime(time.minutes));
duration.push(`:${ padTime(time.seconds)}`);
return duration.join('');
}
export function formatBitrate(value?: number | string | undefined): string {
if (value === undefined || value === null) {
return '';
}
return `${Number(value).toString() } Kbps`;
}
export function formatFileSize(value?: number | string | undefined): string {
if (value === undefined) {
return '';
}
let val = Number(value);
let i = -1;
const byteUnits = [' kB', ' MB', ' GB', ' TB', 'PB', 'EB', 'ZB', 'YB'];
do {
val = val / 1024;
i++;
} while (val > 1024);
return Math.max(val, 0.1).toFixed(1) + byteUnits[i];
}
| 26.907692 | 109 | 0.63179 | 56 | 5 | 0 | 5 | 7 | 0 | 2 | 0 | 16 | 0 | 0 | 9.2 | 637 | 0.015699 | 0.010989 | 0 | 0 | 0 | 0 | 0.941176 | 0.241981 | export /* Example usages of 'padTime' are shown below:
padTime(time.hours);
duration.push(padTime(time.minutes));
padTime(time.seconds);
*/
function padTime(val) {
return (val <= 9) ? `0${val.toString()}` : val.toString();
}
export /* Example usages of 'splitTime' are shown below:
splitTime(val / 1000);
*/
function splitTime(value) {
const duration = {
days: 0,
hours: 0,
minutes: 0,
seconds: 0
};
let delta = value;
duration.days = Math.floor(delta / 86400);
delta -= duration.days * 86400;
// calculate (and subtract) whole hours
duration.hours = Math.floor(delta / 3600) % 24;
delta -= duration.hours * 3600;
// calculate (and subtract) whole minutes
duration.minutes = Math.floor(delta / 60) % 60;
delta -= duration.minutes * 60;
// what's left is seconds
duration.seconds = Math.round(delta % 60);
return duration;
}
export function formatDuration(val) {
const time = splitTime(val / 1000);
const duration = [];
if (time.days > 0) {
duration.push(`${time.days.toString() }d `);
}
if (time.hours > 0) {
if (duration.length > 0) {
duration.push(`${padTime(time.hours) }:`);
} else {
duration.push(`${time.hours.toString() }:`);
}
}
duration.push(padTime(time.minutes));
duration.push(`:${ padTime(time.seconds)}`);
return duration.join('');
}
export function formatBitrate(value?) {
if (value === undefined || value === null) {
return '';
}
return `${Number(value).toString() } Kbps`;
}
export function formatFileSize(value?) {
if (value === undefined) {
return '';
}
let val = Number(value);
let i = -1;
const byteUnits = [' kB', ' MB', ' GB', ' TB', 'PB', 'EB', 'ZB', 'YB'];
do {
val = val / 1024;
i++;
} while (val > 1024);
return Math.max(val, 0.1).toFixed(1) + byteUnits[i];
}
|
0520ac177d3a7da240f8ed552658405fae18bae8 | 5,701 | tsx | TypeScript | mixins/method.tsx | Abel-Liao/Front-end-Component | 1762bc7b6b6fe0a3b3dd61fba9b2946e0c960af4 | [
"MIT"
] | 2 | 2022-02-25T06:30:12.000Z | 2022-02-25T06:30:14.000Z | mixins/method.tsx | Abel-Liao/Front-end-Component | 1762bc7b6b6fe0a3b3dd61fba9b2946e0c960af4 | [
"MIT"
] | 1 | 2022-02-25T06:41:29.000Z | 2022-02-25T06:50:44.000Z | mixins/method.tsx | Abel-Liao/Front-end-Component | 1762bc7b6b6fe0a3b3dd61fba9b2946e0c960af4 | [
"MIT"
] | 1 | 2022-02-25T05:48:55.000Z | 2022-02-25T05:48:55.000Z | /**
* @todo Delete duplicate data from array,No deep traversal
* @param {Array} dataArray
* @returns {Array}
*/
export const removeDuplicate: Function = (
dataArray: Array<any> = []
): Array<any> => {
if (Object.prototype.toString.call(dataArray) !== "[object Array]") {
throw new Error("removeDuplicate`s parameter must be an Array");
}
if (dataArray.length > 1) {
let provisionalityArray: Array<any> = [dataArray[0]];
const Length = dataArray.length;
for (let i = 0; i < Length; i++) {
// let haveData: boolean = false;
// for (let j = 0; j < provisionalityArray.length; j++) {
// if (dataArray[i] === provisionalityArray[j]) {
// haveData = false;
// break;
// } else {
// // Determine the null
// if (
// typeof dataArray[i] === "number" &&
// typeof provisionalityArray[j] === "number" &&
// dataArray[i].toString() === "NaN" &&
// dataArray[i].toString() === provisionalityArray[j].toString()
// ) {
// haveData = false;
// break;
// }
// haveData = true;
// }
// }
// if (haveData) {
// provisionalityArray.push(dataArray[i]);
// }
if (!provisionalityArray.includes(dataArray[i])) {
provisionalityArray.push(dataArray[i]);
}
}
return provisionalityArray;
}
return dataArray;
};
/**
* @todo Flattening an array
* @param {Array} dataArray
* @returns {Array}
*/
export const flatteningArray: Function = (
dataArray: Array<any>
): Array<any> => {
if (Object.prototype.toString.call(dataArray) !== "[object Array]") {
throw new Error("removeDuplicate`s parameter must be an Array");
}
let provisionalityArray: Array<any> = [];
const Length = dataArray.length;
for (let i = 0; i < Length; i++) {
if (Object.prototype.toString.call(dataArray[i]) === "[object Array]") {
provisionalityArray = [
...provisionalityArray,
...flatteningArray(dataArray[i]),
];
} else {
provisionalityArray.push(dataArray[i]);
}
}
return provisionalityArray;
};
/**
* @todo Check whether two arrays are the same
* @param {Array} arrayOne
* @param {Array} arrayTwo
* @param {Boolean} [deepness=false] whether to enable depth traversal
* @returns {Boolean}
*/
export const equalArray: Function = (
arrayOne: Array<any> = [],
arrayTwo: Array<any> = [],
deepness: boolean = false
): boolean => {
if (
Object.prototype.toString.call(arrayOne) !== "[object Array]" ||
Object.prototype.toString.call(arrayTwo) !== "[object Array]"
) {
throw new Error("equalArray`s parameter must be Array");
}
let isEqual: boolean = false;
if (arrayOne.length !== arrayTwo.length) {
return isEqual;
}
if (arrayOne.length > 0 && arrayOne.length === arrayTwo.length) {
const Length = arrayOne.length;
for (let i = 0; i < Length; i++) {
if (
deepness &&
Object.prototype.toString.call(arrayOne[i]) === "[object Array]"
) {
isEqual = equalArray(arrayOne[i], arrayTwo[i]);
if (!isEqual) {
break;
}
} else if (
deepness &&
Object.prototype.toString.call(arrayOne[i]) === "[object Object]"
) {
isEqual = equalObject(arrayOne[i], arrayTwo[i]);
if (!isEqual) {
break;
}
} else {
if (arrayOne[i] !== arrayTwo[i]) {
if (
typeof arrayOne[i] === "number" &&
typeof arrayTwo[i] === "number" &&
arrayOne[i].toString() === "NaN" &&
arrayOne[i].toString() === arrayTwo[i].toString()
) {
isEqual = true;
} else {
isEqual = false;
break;
}
} else {
isEqual = true;
}
}
}
}
return isEqual;
};
/**
* @todo Check whether two objects are equal
* @param {Object} ObjOne
* @param {Object} objTwo
* @param {Boolean} [deepness=false] whether to enable depth traversal
* @returns {Boolean}
*/
export const equalObject: Function = (
ObjOne: any,
objTwo: any,
deepness: boolean = false
): boolean => {
if (
Object.prototype.toString.call(ObjOne) !== "[object Object]" ||
Object.prototype.toString.call(objTwo) !== "[object Object]"
) {
throw new Error("equalObject`s parameter must be Object");
}
let isEqual = false;
if (JSON.stringify(ObjOne) === "{}" || JSON.stringify(objTwo) === "{}") {
throw new Error("The parameter has an empty Object");
}
if (ObjOne === objTwo) {
isEqual = true;
return isEqual;
}
if (
Object.getOwnPropertyNames(ObjOne).length !==
Object.getOwnPropertyNames(objTwo).length
) {
return isEqual;
}
for (let key in ObjOne) {
if (
deepness &&
Object.prototype.toString.call(ObjOne[key]) === "[object Array]"
) {
isEqual = equalArray(ObjOne[key], objTwo[key]);
if (!isEqual) {
break;
}
} else if (
deepness &&
Object.prototype.toString.call(ObjOne[key]) === "[object Object]"
) {
isEqual = equalObject(ObjOne[key], objTwo[key]);
if (!isEqual) {
break;
}
} else {
if (ObjOne[key] !== objTwo[key]) {
if (
typeof ObjOne[key] === "number" &&
typeof objTwo[key] === "number" &&
ObjOne[key].toString() === "NaN" &&
ObjOne[key].toString() === objTwo[key].toString()
) {
isEqual = true;
} else {
isEqual = false;
break;
}
} else {
isEqual = true;
}
}
}
return isEqual;
};
| 27.946078 | 76 | 0.550079 | 155 | 4 | 0 | 8 | 14 | 0 | 3 | 14 | 5 | 0 | 4 | 33.75 | 1,557 | 0.007707 | 0.008992 | 0 | 0 | 0.002569 | 0.538462 | 0.192308 | 0.209127 | /**
* @todo Delete duplicate data from array,No deep traversal
* @param {Array} dataArray
* @returns {Array}
*/
export const removeDuplicate = (
dataArray = []
) => {
if (Object.prototype.toString.call(dataArray) !== "[object Array]") {
throw new Error("removeDuplicate`s parameter must be an Array");
}
if (dataArray.length > 1) {
let provisionalityArray = [dataArray[0]];
const Length = dataArray.length;
for (let i = 0; i < Length; i++) {
// let haveData: boolean = false;
// for (let j = 0; j < provisionalityArray.length; j++) {
// if (dataArray[i] === provisionalityArray[j]) {
// haveData = false;
// break;
// } else {
// // Determine the null
// if (
// typeof dataArray[i] === "number" &&
// typeof provisionalityArray[j] === "number" &&
// dataArray[i].toString() === "NaN" &&
// dataArray[i].toString() === provisionalityArray[j].toString()
// ) {
// haveData = false;
// break;
// }
// haveData = true;
// }
// }
// if (haveData) {
// provisionalityArray.push(dataArray[i]);
// }
if (!provisionalityArray.includes(dataArray[i])) {
provisionalityArray.push(dataArray[i]);
}
}
return provisionalityArray;
}
return dataArray;
};
/**
* @todo Flattening an array
* @param {Array} dataArray
* @returns {Array}
*/
export /* Example usages of 'flatteningArray' are shown below:
flatteningArray(dataArray[i]);
*/
const flatteningArray = (
dataArray
) => {
if (Object.prototype.toString.call(dataArray) !== "[object Array]") {
throw new Error("removeDuplicate`s parameter must be an Array");
}
let provisionalityArray = [];
const Length = dataArray.length;
for (let i = 0; i < Length; i++) {
if (Object.prototype.toString.call(dataArray[i]) === "[object Array]") {
provisionalityArray = [
...provisionalityArray,
...flatteningArray(dataArray[i]),
];
} else {
provisionalityArray.push(dataArray[i]);
}
}
return provisionalityArray;
};
/**
* @todo Check whether two arrays are the same
* @param {Array} arrayOne
* @param {Array} arrayTwo
* @param {Boolean} [deepness=false] whether to enable depth traversal
* @returns {Boolean}
*/
export /* Example usages of 'equalArray' are shown below:
isEqual = equalArray(arrayOne[i], arrayTwo[i]);
isEqual = equalArray(ObjOne[key], objTwo[key]);
*/
const equalArray = (
arrayOne = [],
arrayTwo = [],
deepness = false
) => {
if (
Object.prototype.toString.call(arrayOne) !== "[object Array]" ||
Object.prototype.toString.call(arrayTwo) !== "[object Array]"
) {
throw new Error("equalArray`s parameter must be Array");
}
let isEqual = false;
if (arrayOne.length !== arrayTwo.length) {
return isEqual;
}
if (arrayOne.length > 0 && arrayOne.length === arrayTwo.length) {
const Length = arrayOne.length;
for (let i = 0; i < Length; i++) {
if (
deepness &&
Object.prototype.toString.call(arrayOne[i]) === "[object Array]"
) {
isEqual = equalArray(arrayOne[i], arrayTwo[i]);
if (!isEqual) {
break;
}
} else if (
deepness &&
Object.prototype.toString.call(arrayOne[i]) === "[object Object]"
) {
isEqual = equalObject(arrayOne[i], arrayTwo[i]);
if (!isEqual) {
break;
}
} else {
if (arrayOne[i] !== arrayTwo[i]) {
if (
typeof arrayOne[i] === "number" &&
typeof arrayTwo[i] === "number" &&
arrayOne[i].toString() === "NaN" &&
arrayOne[i].toString() === arrayTwo[i].toString()
) {
isEqual = true;
} else {
isEqual = false;
break;
}
} else {
isEqual = true;
}
}
}
}
return isEqual;
};
/**
* @todo Check whether two objects are equal
* @param {Object} ObjOne
* @param {Object} objTwo
* @param {Boolean} [deepness=false] whether to enable depth traversal
* @returns {Boolean}
*/
export /* Example usages of 'equalObject' are shown below:
isEqual = equalObject(arrayOne[i], arrayTwo[i]);
isEqual = equalObject(ObjOne[key], objTwo[key]);
*/
const equalObject = (
ObjOne,
objTwo,
deepness = false
) => {
if (
Object.prototype.toString.call(ObjOne) !== "[object Object]" ||
Object.prototype.toString.call(objTwo) !== "[object Object]"
) {
throw new Error("equalObject`s parameter must be Object");
}
let isEqual = false;
if (JSON.stringify(ObjOne) === "{}" || JSON.stringify(objTwo) === "{}") {
throw new Error("The parameter has an empty Object");
}
if (ObjOne === objTwo) {
isEqual = true;
return isEqual;
}
if (
Object.getOwnPropertyNames(ObjOne).length !==
Object.getOwnPropertyNames(objTwo).length
) {
return isEqual;
}
for (let key in ObjOne) {
if (
deepness &&
Object.prototype.toString.call(ObjOne[key]) === "[object Array]"
) {
isEqual = equalArray(ObjOne[key], objTwo[key]);
if (!isEqual) {
break;
}
} else if (
deepness &&
Object.prototype.toString.call(ObjOne[key]) === "[object Object]"
) {
isEqual = equalObject(ObjOne[key], objTwo[key]);
if (!isEqual) {
break;
}
} else {
if (ObjOne[key] !== objTwo[key]) {
if (
typeof ObjOne[key] === "number" &&
typeof objTwo[key] === "number" &&
ObjOne[key].toString() === "NaN" &&
ObjOne[key].toString() === objTwo[key].toString()
) {
isEqual = true;
} else {
isEqual = false;
break;
}
} else {
isEqual = true;
}
}
}
return isEqual;
};
|
0543f4f2b9cde1baf6a4d3e67f630175d9c7dcae | 3,109 | ts | TypeScript | challenges/day19.ts | Ldoppea/advent-of-code-2020-typescript | 608c15619b9cae3bbc65d2d5d42455710d517221 | [
"MIT"
] | null | null | null | challenges/day19.ts | Ldoppea/advent-of-code-2020-typescript | 608c15619b9cae3bbc65d2d5d42455710d517221 | [
"MIT"
] | null | null | null | challenges/day19.ts | Ldoppea/advent-of-code-2020-typescript | 608c15619b9cae3bbc65d2d5d42455710d517221 | [
"MIT"
] | 1 | 2022-01-28T17:21:42.000Z | 2022-01-28T17:21:42.000Z | interface Rule {
ruleRaw: string,
ruleIndex: number,
ruleString: string,
ruleRegex: string
}
const getRulesAndData = (input: string[]) => {
let rules = input.filter(line => line !== '' && line.includes(':'));
let data = input.filter(line => line !== '' && !line.includes(':'));
return {
rules,
data
}
}
export function parseRules(rules: string[]): Rule[] {
return rules.map(rule => {
const [ruleIndex, ruleString] = rule.split(': ');
return {
ruleRaw: rule,
ruleIndex: parseInt(ruleIndex),
ruleString,
ruleRegex: ''
}
});
}
export function transformRuleToRegex(rule: Rule, rules: Rule[]): string {
const ruleString = rule.ruleString;
// Part 2 handle loop
if (rule.ruleIndex === 8 && rule.ruleString.includes('8')) {
// f(x) = x | x f(x) means a succession of 1 or more 'x'
// ex: x
// ex: xx
// ex: xxx
// ex: xxxx
const correspondingRule = rules.find(rule => rule.ruleIndex === 42)!;
const regex = '(' + transformRuleToRegex(correspondingRule, rules) + ')';
return `${regex}+`;
} else if (rule.ruleIndex === 11 && rule.ruleString.includes('11')) {
// f(x, y) = xy | x f(xy) y means a succession of 1 or more 'x' then 1 or more 'y' but with same number of each
// ex: xy
// ex: xxyy
// ex: xxxyyy
// ex: xxxxyyyy
const correspondingRule1 = rules.find(rule => rule.ruleIndex === 42)!;
const regex1 = '(' + transformRuleToRegex(correspondingRule1, rules) + ')';
const correspondingRule2 = rules.find(rule => rule.ruleIndex === 31)!;
const regex2 = '(' + transformRuleToRegex(correspondingRule2, rules) + ')';
const case1 = `(${regex1}{1}${regex2}{1})`;
const case2 = `(${regex1}{2}${regex2}{2})`;
const case3 = `(${regex1}{3}${regex2}{3})`;
const case4 = `(${regex1}{4}${regex2}{4})`;
return `((${case1})|(${case2})|(${case3})|(${case4}))`;
}
// Part 1
else {
const regex = ruleString
.split(' | ')
.map(rulePart => {
const partRegex = rulePart
.split(' ')
.map(ruleIndex => {
const correspondingRule = rules.find(rule => rule.ruleIndex === parseInt(ruleIndex))!;
if(correspondingRule.ruleString.includes('"')) {
return correspondingRule.ruleString.replace(/\"/gi, '');
} else {
return '(' + transformRuleToRegex(correspondingRule, rules) + ')'
}
})
.join('')
return '(' + partRegex + ')';
})
.join('|');
return regex;
}
}
export function getRule0ToRegex(rules: Rule[]): string {
const rule0 = rules.find(rule => rule.ruleIndex === 0)!;
const regex = transformRuleToRegex(rule0, rules)
return regex;
}
export function getNumberOfMatchingLines(input: string[]): number {
const { rules, data } = getRulesAndData(input)
const regexStr = '^' + getRule0ToRegex(parseRules(rules)) + '$';
const regex = RegExp(regexStr);
const matchingLines = data.filter(line => {
return regex.test(line);
});
return matchingLines.length
} | 28.009009 | 115 | 0.580251 | 77 | 16 | 0 | 17 | 24 | 4 | 4 | 0 | 10 | 1 | 0 | 5.875 | 899 | 0.036707 | 0.026696 | 0.004449 | 0.001112 | 0 | 0 | 0.163934 | 0.345783 | interface Rule {
ruleRaw,
ruleIndex,
ruleString,
ruleRegex
}
/* Example usages of 'getRulesAndData' are shown below:
getRulesAndData(input);
*/
const getRulesAndData = (input) => {
let rules = input.filter(line => line !== '' && line.includes(':'));
let data = input.filter(line => line !== '' && !line.includes(':'));
return {
rules,
data
}
}
export /* Example usages of 'parseRules' are shown below:
'^' + getRule0ToRegex(parseRules(rules)) + '$';
*/
function parseRules(rules) {
return rules.map(rule => {
const [ruleIndex, ruleString] = rule.split(': ');
return {
ruleRaw: rule,
ruleIndex: parseInt(ruleIndex),
ruleString,
ruleRegex: ''
}
});
}
export /* Example usages of 'transformRuleToRegex' are shown below:
'(' + transformRuleToRegex(correspondingRule, rules) + ')';
'(' + transformRuleToRegex(correspondingRule1, rules) + ')';
'(' + transformRuleToRegex(correspondingRule2, rules) + ')';
transformRuleToRegex(rule0, rules);
*/
function transformRuleToRegex(rule, rules) {
const ruleString = rule.ruleString;
// Part 2 handle loop
if (rule.ruleIndex === 8 && rule.ruleString.includes('8')) {
// f(x) = x | x f(x) means a succession of 1 or more 'x'
// ex: x
// ex: xx
// ex: xxx
// ex: xxxx
const correspondingRule = rules.find(rule => rule.ruleIndex === 42)!;
const regex = '(' + transformRuleToRegex(correspondingRule, rules) + ')';
return `${regex}+`;
} else if (rule.ruleIndex === 11 && rule.ruleString.includes('11')) {
// f(x, y) = xy | x f(xy) y means a succession of 1 or more 'x' then 1 or more 'y' but with same number of each
// ex: xy
// ex: xxyy
// ex: xxxyyy
// ex: xxxxyyyy
const correspondingRule1 = rules.find(rule => rule.ruleIndex === 42)!;
const regex1 = '(' + transformRuleToRegex(correspondingRule1, rules) + ')';
const correspondingRule2 = rules.find(rule => rule.ruleIndex === 31)!;
const regex2 = '(' + transformRuleToRegex(correspondingRule2, rules) + ')';
const case1 = `(${regex1}{1}${regex2}{1})`;
const case2 = `(${regex1}{2}${regex2}{2})`;
const case3 = `(${regex1}{3}${regex2}{3})`;
const case4 = `(${regex1}{4}${regex2}{4})`;
return `((${case1})|(${case2})|(${case3})|(${case4}))`;
}
// Part 1
else {
const regex = ruleString
.split(' | ')
.map(rulePart => {
const partRegex = rulePart
.split(' ')
.map(ruleIndex => {
const correspondingRule = rules.find(rule => rule.ruleIndex === parseInt(ruleIndex))!;
if(correspondingRule.ruleString.includes('"')) {
return correspondingRule.ruleString.replace(/\"/gi, '');
} else {
return '(' + transformRuleToRegex(correspondingRule, rules) + ')'
}
})
.join('')
return '(' + partRegex + ')';
})
.join('|');
return regex;
}
}
export /* Example usages of 'getRule0ToRegex' are shown below:
'^' + getRule0ToRegex(parseRules(rules)) + '$';
*/
function getRule0ToRegex(rules) {
const rule0 = rules.find(rule => rule.ruleIndex === 0)!;
const regex = transformRuleToRegex(rule0, rules)
return regex;
}
export function getNumberOfMatchingLines(input) {
const { rules, data } = getRulesAndData(input)
const regexStr = '^' + getRule0ToRegex(parseRules(rules)) + '$';
const regex = RegExp(regexStr);
const matchingLines = data.filter(line => {
return regex.test(line);
});
return matchingLines.length
} |
054e796140154545560367bed1e8eb6b71a0c9c6 | 3,422 | ts | TypeScript | src/app/routes/apply-form/services/apply-form-model.ts | ou1260207429/10-10 | 10aea64cb8e5d8a6a1eba3d56a4ea635450e3e13 | [
"MIT"
] | null | null | null | src/app/routes/apply-form/services/apply-form-model.ts | ou1260207429/10-10 | 10aea64cb8e5d8a6a1eba3d56a4ea635450e3e13 | [
"MIT"
] | 1 | 2022-03-02T05:53:26.000Z | 2022-03-02T05:53:26.000Z | src/app/routes/apply-form/services/apply-form-model.ts | ou1260207429/10-10 | 10aea64cb8e5d8a6a1eba3d56a4ea635450e3e13 | [
"MIT"
] | null | null | null | export class ApplyFormModel {
public formData: any; // 表单数据
// 建设单位
public constructOrgs: any;
// 设计单位
public designOrgs: any;
// 施工单位
public buildOrgs: any;
// 监理单位
public supervisoryOrgs: any;
// 审图单位
public drawingOrgs: any;
// 检测单位
public testingOrgs: any;
// 分包单位
public subcontractors: any;
// 审图编号列表
public drawingNumberArray: any;
constructor() {
this.initFormData();
}
// 初始化数据
initFormData() {
this.setFormData(null);
}
setFormData(data) {
if (data == null) {
this.formData = {};
// 申请表单数据
this.formData.applyFormRequestDTO = {};
// 申请表单扩展数据
this.formData.applyFormExpandRequestDTO = {};
// 申报表单附件数据
this.formData.applyFormAttachmentRequestDTOs = [];
// 申请表单公司单位数据
this.formData.applyFormCompanyRequestDTOs = [];
// 单体建筑数据
this.formData.monomerArchitectureRequestDTOs = [];
// 储罐数据
this.formData.storageTankRequestDTOs = [];
// 堆场数据
this.formData.yardRequestDTOs = [];
// 建筑保温数据
this.formData.heatPreservationRequestDTOs = [];
// 土建工程数据
this.formData.civilEngineeringRequestDTOs = [];
// 消防设施数据
this.formData.fireFacilitiesRequestDTOs = [];
// 室内装修工程数据
this.formData.decorationRequestDTOs = [];
// 单位意见数据
this.formData.orgOpinionRequestDTOs = [];
// 审图编号列表
this.drawingNumberArray = [];
} else {
this.formData = data;
if (data.drawingNumber != null && data.drawingNumber !== '') {
this.drawingNumberArray = data.drawingNumber.split(',');
} else {
this.drawingNumberArray = [];
}
}
// 建设单位
this.constructOrgs = this.getOrgList(1);
if (this.constructOrgs.length == 0) {
this.constructOrgs.push({});
}
// 设计单位
this.designOrgs = this.getOrgList(2);
// 施工单位
this.buildOrgs = this.getOrgList(3);
// 监理单位
this.supervisoryOrgs = this.getOrgList(4);
// 审图单位
this.drawingOrgs = this.getOrgList(5);
// 检测单位
this.testingOrgs = this.getOrgList(6);
// 分包单位
this.subcontractors = this.getOrgList(7);
}
// 获取单位列表:1-建设单位,2-设计单位,3-施工单位,4-审图单位,5-检测单位,6分包单位
getOrgList(orgType) {
let orgs;
orgs = [];
if (this.formData != null && this.formData.applyFormCompanyRequestDTOs != null) {
this.formData.applyFormCompanyRequestDTOs.forEach(element => {
if (element.orgType == orgType) {
orgs.push(element);
}
});
}
return orgs;
}
getDrawingNumber() {
let drawingNum = ',';
if (this.drawingNumberArray.length > 0) {
this.drawingNumberArray.forEach(value => {
if (value != null && value != '') {
drawingNum = drawingNum + value;
}
});
}
if (drawingNum == ',') {
drawingNum = '';
} else {
drawingNum = drawingNum.substring(1);
}
return drawingNum;
}
} | 26.527132 | 89 | 0.510228 | 80 | 7 | 0 | 4 | 2 | 9 | 3 | 9 | 0 | 1 | 0 | 9.285714 | 909 | 0.012101 | 0.0022 | 0.009901 | 0.0011 | 0 | 0.409091 | 0 | 0.20157 | export class ApplyFormModel {
public formData; // 表单数据
// 建设单位
public constructOrgs;
// 设计单位
public designOrgs;
// 施工单位
public buildOrgs;
// 监理单位
public supervisoryOrgs;
// 审图单位
public drawingOrgs;
// 检测单位
public testingOrgs;
// 分包单位
public subcontractors;
// 审图编号列表
public drawingNumberArray;
constructor() {
this.initFormData();
}
// 初始化数据
initFormData() {
this.setFormData(null);
}
setFormData(data) {
if (data == null) {
this.formData = {};
// 申请表单数据
this.formData.applyFormRequestDTO = {};
// 申请表单扩展数据
this.formData.applyFormExpandRequestDTO = {};
// 申报表单附件数据
this.formData.applyFormAttachmentRequestDTOs = [];
// 申请表单公司单位数据
this.formData.applyFormCompanyRequestDTOs = [];
// 单体建筑数据
this.formData.monomerArchitectureRequestDTOs = [];
// 储罐数据
this.formData.storageTankRequestDTOs = [];
// 堆场数据
this.formData.yardRequestDTOs = [];
// 建筑保温数据
this.formData.heatPreservationRequestDTOs = [];
// 土建工程数据
this.formData.civilEngineeringRequestDTOs = [];
// 消防设施数据
this.formData.fireFacilitiesRequestDTOs = [];
// 室内装修工程数据
this.formData.decorationRequestDTOs = [];
// 单位意见数据
this.formData.orgOpinionRequestDTOs = [];
// 审图编号列表
this.drawingNumberArray = [];
} else {
this.formData = data;
if (data.drawingNumber != null && data.drawingNumber !== '') {
this.drawingNumberArray = data.drawingNumber.split(',');
} else {
this.drawingNumberArray = [];
}
}
// 建设单位
this.constructOrgs = this.getOrgList(1);
if (this.constructOrgs.length == 0) {
this.constructOrgs.push({});
}
// 设计单位
this.designOrgs = this.getOrgList(2);
// 施工单位
this.buildOrgs = this.getOrgList(3);
// 监理单位
this.supervisoryOrgs = this.getOrgList(4);
// 审图单位
this.drawingOrgs = this.getOrgList(5);
// 检测单位
this.testingOrgs = this.getOrgList(6);
// 分包单位
this.subcontractors = this.getOrgList(7);
}
// 获取单位列表:1-建设单位,2-设计单位,3-施工单位,4-审图单位,5-检测单位,6分包单位
getOrgList(orgType) {
let orgs;
orgs = [];
if (this.formData != null && this.formData.applyFormCompanyRequestDTOs != null) {
this.formData.applyFormCompanyRequestDTOs.forEach(element => {
if (element.orgType == orgType) {
orgs.push(element);
}
});
}
return orgs;
}
getDrawingNumber() {
let drawingNum = ',';
if (this.drawingNumberArray.length > 0) {
this.drawingNumberArray.forEach(value => {
if (value != null && value != '') {
drawingNum = drawingNum + value;
}
});
}
if (drawingNum == ',') {
drawingNum = '';
} else {
drawingNum = drawingNum.substring(1);
}
return drawingNum;
}
} |
05d2004b5f5aef518ef5dd67e7bd951d5b068248 | 2,879 | ts | TypeScript | src/camelcase.util.ts | butopen/pg2ts | bdbf954f7d5b293cc4528a08ca2eb479f56ea979 | [
"MIT"
] | 1 | 2022-01-20T18:31:24.000Z | 2022-01-20T18:31:24.000Z | src/camelcase.util.ts | butopen/pg2ts | bdbf954f7d5b293cc4528a08ca2eb479f56ea979 | [
"MIT"
] | null | null | null | src/camelcase.util.ts | butopen/pg2ts | bdbf954f7d5b293cc4528a08ca2eb479f56ea979 | [
"MIT"
] | null | null | null | const preserveCamelCase = (string, locale) => {
let isLastCharLower = false;
let isLastCharUpper = false;
let isLastLastCharUpper = false;
for (let i = 0; i < string.length; i++) {
const character = string[i];
if (isLastCharLower && /[\p{Lu}]/u.test(character)) {
string = string.slice(0, i) + '-' + string.slice(i);
isLastCharLower = false;
isLastLastCharUpper = isLastCharUpper;
isLastCharUpper = true;
i++;
} else if (isLastCharUpper && isLastLastCharUpper && /[\p{Ll}]/u.test(character)) {
string = string.slice(0, i - 1) + '-' + string.slice(i - 1);
isLastLastCharUpper = isLastCharUpper;
isLastCharUpper = false;
isLastCharLower = true;
} else {
isLastCharLower = character.toLocaleLowerCase(locale) === character && character.toLocaleUpperCase(locale) !== character;
isLastLastCharUpper = isLastCharUpper;
isLastCharUpper = character.toLocaleUpperCase(locale) === character && character.toLocaleLowerCase(locale) !== character;
}
}
return string;
};
const preserveConsecutiveUppercase = input => {
return input.replace(/^[\p{Lu}](?![\p{Lu}])/gu, m1 => m1.toLowerCase());
};
const postProcess = (input, options) => {
return input.replace(/[_.\- ]+([\p{Alpha}\p{N}_]|$)/gu, (_, p1) => p1.toLocaleUpperCase(options.locale))
.replace(/\d+([\p{Alpha}\p{N}_]|$)/gu, m => m.toLocaleUpperCase(options.locale));
};
export const camelCase = (input: string, options ?: { pascalCase?: boolean, preserveConsecutiveUppercase?: boolean, locale?: string }) => {
if (!(typeof input === 'string' || Array.isArray(input))) {
throw new TypeError('Expected the input to be `string | string[]`');
}
options = {
pascalCase: false,
preserveConsecutiveUppercase: false,
...options
};
if (Array.isArray(input)) {
input = input.map(x => x.trim())
.filter(x => x.length)
.join('-');
} else {
input = input.trim();
}
if (input.length === 0) {
return '';
}
if (input.length === 1) {
return options.pascalCase ? input.toLocaleUpperCase(options.locale) : input.toLocaleLowerCase(options.locale);
}
const hasUpperCase = input !== input.toLocaleLowerCase(options.locale);
if (hasUpperCase) {
input = preserveCamelCase(input, options.locale);
}
input = input.replace(/^[_.\- ]+/, '');
if (options.preserveConsecutiveUppercase) {
input = preserveConsecutiveUppercase(input);
} else {
input = input.toLocaleLowerCase();
}
if (options.pascalCase) {
input = input.charAt(0).toLocaleUpperCase(options.locale) + input.slice(1);
}
return postProcess(input, options);
};
| 33.476744 | 139 | 0.593956 | 69 | 9 | 0 | 13 | 10 | 0 | 3 | 0 | 4 | 0 | 1 | 7.333333 | 745 | 0.02953 | 0.013423 | 0 | 0 | 0.001342 | 0 | 0.125 | 0.283406 | /* Example usages of 'preserveCamelCase' are shown below:
input = preserveCamelCase(input, options.locale);
*/
const preserveCamelCase = (string, locale) => {
let isLastCharLower = false;
let isLastCharUpper = false;
let isLastLastCharUpper = false;
for (let i = 0; i < string.length; i++) {
const character = string[i];
if (isLastCharLower && /[\p{Lu}]/u.test(character)) {
string = string.slice(0, i) + '-' + string.slice(i);
isLastCharLower = false;
isLastLastCharUpper = isLastCharUpper;
isLastCharUpper = true;
i++;
} else if (isLastCharUpper && isLastLastCharUpper && /[\p{Ll}]/u.test(character)) {
string = string.slice(0, i - 1) + '-' + string.slice(i - 1);
isLastLastCharUpper = isLastCharUpper;
isLastCharUpper = false;
isLastCharLower = true;
} else {
isLastCharLower = character.toLocaleLowerCase(locale) === character && character.toLocaleUpperCase(locale) !== character;
isLastLastCharUpper = isLastCharUpper;
isLastCharUpper = character.toLocaleUpperCase(locale) === character && character.toLocaleLowerCase(locale) !== character;
}
}
return string;
};
/* Example usages of 'preserveConsecutiveUppercase' are shown below:
;
options.preserveConsecutiveUppercase;
input = preserveConsecutiveUppercase(input);
*/
const preserveConsecutiveUppercase = input => {
return input.replace(/^[\p{Lu}](?![\p{Lu}])/gu, m1 => m1.toLowerCase());
};
/* Example usages of 'postProcess' are shown below:
postProcess(input, options);
*/
const postProcess = (input, options) => {
return input.replace(/[_.\- ]+([\p{Alpha}\p{N}_]|$)/gu, (_, p1) => p1.toLocaleUpperCase(options.locale))
.replace(/\d+([\p{Alpha}\p{N}_]|$)/gu, m => m.toLocaleUpperCase(options.locale));
};
export const camelCase = (input, options ?) => {
if (!(typeof input === 'string' || Array.isArray(input))) {
throw new TypeError('Expected the input to be `string | string[]`');
}
options = {
pascalCase: false,
preserveConsecutiveUppercase: false,
...options
};
if (Array.isArray(input)) {
input = input.map(x => x.trim())
.filter(x => x.length)
.join('-');
} else {
input = input.trim();
}
if (input.length === 0) {
return '';
}
if (input.length === 1) {
return options.pascalCase ? input.toLocaleUpperCase(options.locale) : input.toLocaleLowerCase(options.locale);
}
const hasUpperCase = input !== input.toLocaleLowerCase(options.locale);
if (hasUpperCase) {
input = preserveCamelCase(input, options.locale);
}
input = input.replace(/^[_.\- ]+/, '');
if (options.preserveConsecutiveUppercase) {
input = preserveConsecutiveUppercase(input);
} else {
input = input.toLocaleLowerCase();
}
if (options.pascalCase) {
input = input.charAt(0).toLocaleUpperCase(options.locale) + input.slice(1);
}
return postProcess(input, options);
};
|
6c720cf9896446d51c2fbf27c0bd5b96c8e2a900 | 2,115 | ts | TypeScript | src/app/models/ontology-discipline.model.ts | os-climate/sostrades-webgui | 029dc7f13850997fb756991e98c2b6d4d837de51 | [
"MIT",
"Apache-2.0",
"BSD-3-Clause"
] | 1 | 2022-03-16T08:25:41.000Z | 2022-03-16T08:25:41.000Z | src/app/models/ontology-discipline.model.ts | os-climate/sostrades-webgui | 029dc7f13850997fb756991e98c2b6d4d837de51 | [
"MIT",
"Apache-2.0",
"BSD-3-Clause"
] | null | null | null | src/app/models/ontology-discipline.model.ts | os-climate/sostrades-webgui | 029dc7f13850997fb756991e98c2b6d4d837de51 | [
"MIT",
"Apache-2.0",
"BSD-3-Clause"
] | null | null | null | export class OntologyDiscipline {
constructor(
public id: string,
public label: string,
public delivered: string,
public implemented: string,
public maturity: string,
public source: string,
public className: string,
public validator: string,
public validated: string,
public uri: string,
public icon: string
) { }
public static Create(jsonData: any): OntologyDiscipline {
const result: OntologyDiscipline = new OntologyDiscipline(
jsonData[OntologyParameterAttributes.ID],
jsonData[OntologyParameterAttributes.LABEL],
jsonData[OntologyParameterAttributes.DELIVERED],
jsonData[OntologyParameterAttributes.IMPLEMENTED],
jsonData[OntologyParameterAttributes.MATURITY],
jsonData[OntologyParameterAttributes.SOURCE],
jsonData[OntologyParameterAttributes.CLASSNAME],
jsonData[OntologyParameterAttributes.VALIDATOR],
jsonData[OntologyParameterAttributes.VALIDATED],
jsonData[OntologyParameterAttributes.URI],
jsonData[OntologyParameterAttributes.ICON]);
return result;
}
public static getKeyLabel(key: string): string {
const keyLabelDict = {
id: 'ID',
delivered: 'Delivered',
implemented: 'Implemented',
label: 'Discipline Name',
maturity: 'Maturity',
source: 'Source',
className: 'Discipline Class Name',
uri: 'Ontology URI',
validator: 'Validator',
validated: 'Validated'
};
if (key in keyLabelDict) {
return keyLabelDict[key];
} else {
return key;
}
}
public toString = (): string => {
const strings: string[] = [];
if (this.id !== null && this.id !== undefined) {
strings.push(`${this.id}`);
}
// TO BE IMPLEMENTED IF NEEDED
return strings.join('\n');
}
}
export enum OntologyParameterAttributes {
ID = 'id',
DELIVERED = 'delivered',
IMPLEMENTED = 'implemented',
LABEL = 'label',
MATURITY = 'modelType',
SOURCE = 'originSource',
CLASSNAME = 'pythonClass',
URI = 'uri',
VALIDATOR = 'validator',
VALIDATED = 'validated',
ICON = 'icon'
}
| 26.772152 | 62 | 0.667612 | 69 | 4 | 0 | 13 | 3 | 1 | 0 | 1 | 15 | 1 | 0 | 8.75 | 494 | 0.034413 | 0.006073 | 0.002024 | 0.002024 | 0 | 0.047619 | 0.714286 | 0.272012 | export class OntologyDiscipline {
constructor(
public id,
public label,
public delivered,
public implemented,
public maturity,
public source,
public className,
public validator,
public validated,
public uri,
public icon
) { }
public static Create(jsonData) {
const result = new OntologyDiscipline(
jsonData[OntologyParameterAttributes.ID],
jsonData[OntologyParameterAttributes.LABEL],
jsonData[OntologyParameterAttributes.DELIVERED],
jsonData[OntologyParameterAttributes.IMPLEMENTED],
jsonData[OntologyParameterAttributes.MATURITY],
jsonData[OntologyParameterAttributes.SOURCE],
jsonData[OntologyParameterAttributes.CLASSNAME],
jsonData[OntologyParameterAttributes.VALIDATOR],
jsonData[OntologyParameterAttributes.VALIDATED],
jsonData[OntologyParameterAttributes.URI],
jsonData[OntologyParameterAttributes.ICON]);
return result;
}
public static getKeyLabel(key) {
const keyLabelDict = {
id: 'ID',
delivered: 'Delivered',
implemented: 'Implemented',
label: 'Discipline Name',
maturity: 'Maturity',
source: 'Source',
className: 'Discipline Class Name',
uri: 'Ontology URI',
validator: 'Validator',
validated: 'Validated'
};
if (key in keyLabelDict) {
return keyLabelDict[key];
} else {
return key;
}
}
public toString = () => {
const strings = [];
if (this.id !== null && this.id !== undefined) {
strings.push(`${this.id}`);
}
// TO BE IMPLEMENTED IF NEEDED
return strings.join('\n');
}
}
export enum OntologyParameterAttributes {
ID = 'id',
DELIVERED = 'delivered',
IMPLEMENTED = 'implemented',
LABEL = 'label',
MATURITY = 'modelType',
SOURCE = 'originSource',
CLASSNAME = 'pythonClass',
URI = 'uri',
VALIDATOR = 'validator',
VALIDATED = 'validated',
ICON = 'icon'
}
|
6c89764637b32504301d3c389bb64f06f3266911 | 2,167 | ts | TypeScript | frontend/src/container/CreateAlertChannels/config.ts | pal-sig/signoz | be01bc9b82aae1834a1be26aaa06e988cf3ac890 | [
"MIT"
] | null | null | null | frontend/src/container/CreateAlertChannels/config.ts | pal-sig/signoz | be01bc9b82aae1834a1be26aaa06e988cf3ac890 | [
"MIT"
] | 1 | 2022-02-08T17:35:02.000Z | 2022-02-08T17:35:02.000Z | frontend/src/container/CreateAlertChannels/config.ts | pal-sig/signoz | be01bc9b82aae1834a1be26aaa06e988cf3ac890 | [
"MIT"
] | null | null | null | export interface Channel {
send_resolved?: boolean;
name: string;
filter?: Partial<Array<LabelFilterStatement>>;
}
export interface SlackChannel extends Channel {
api_url?: string;
channel?: string;
title?: string;
text?: string;
}
export interface WebhookChannel extends Channel {
api_url?: string;
// basic auth
username?: string;
password?: string;
}
// PagerChannel configures alert manager to send
// events to pagerduty
export interface PagerChannel extends Channel {
// ref: https://prometheus.io/docs/alerting/latest/configuration/#pagerduty_config
routing_key?: string;
// displays source of the event in pager duty
client?: string;
client_url?: string;
// A description of the incident
description?: string;
// Severity of the incident
severity?: string;
// The part or component of the affected system that is broken
component?: string;
// A cluster or grouping of sources
group?: string;
// The class/type of the event.
class?: string;
details?: string;
detailsArray?: Record<string, string>;
}
export const ValidatePagerChannel = (p: PagerChannel): string => {
if (!p) {
return 'Received unexpected input for this channel, please contact your administrator ';
}
if (!p.name || p.name === '') {
return 'Name is mandatory for creating a channel';
}
if (!p.routing_key || p.routing_key === '') {
return 'Routing Key is mandatory for creating pagerduty channel';
}
// validate details json
try {
JSON.parse(p.details || '{}');
} catch (e) {
return 'failed to parse additional information, please enter a valid json';
}
return '';
};
export type ChannelType = 'slack' | 'email' | 'webhook' | 'pagerduty';
export const SlackType: ChannelType = 'slack';
export const WebhookType: ChannelType = 'webhook';
export const PagerType: ChannelType = 'pagerduty';
// LabelFilterStatement will be used for preparing filter conditions / matchers
export interface LabelFilterStatement {
// ref: https://prometheus.io/docs/alerting/latest/configuration/#matcher
// label name
name: string;
// comparators supported by promql are =, !=, =~, or !~. =
comparator: string;
// filter value
value: string;
}
| 25.797619 | 90 | 0.716659 | 54 | 1 | 0 | 1 | 4 | 23 | 0 | 0 | 24 | 6 | 0 | 15 | 616 | 0.003247 | 0.006494 | 0.037338 | 0.00974 | 0 | 0 | 0.827586 | 0.213523 | export interface Channel {
send_resolved?;
name;
filter?;
}
export interface SlackChannel extends Channel {
api_url?;
channel?;
title?;
text?;
}
export interface WebhookChannel extends Channel {
api_url?;
// basic auth
username?;
password?;
}
// PagerChannel configures alert manager to send
// events to pagerduty
export interface PagerChannel extends Channel {
// ref: https://prometheus.io/docs/alerting/latest/configuration/#pagerduty_config
routing_key?;
// displays source of the event in pager duty
client?;
client_url?;
// A description of the incident
description?;
// Severity of the incident
severity?;
// The part or component of the affected system that is broken
component?;
// A cluster or grouping of sources
group?;
// The class/type of the event.
class?;
details?;
detailsArray?;
}
export const ValidatePagerChannel = (p) => {
if (!p) {
return 'Received unexpected input for this channel, please contact your administrator ';
}
if (!p.name || p.name === '') {
return 'Name is mandatory for creating a channel';
}
if (!p.routing_key || p.routing_key === '') {
return 'Routing Key is mandatory for creating pagerduty channel';
}
// validate details json
try {
JSON.parse(p.details || '{}');
} catch (e) {
return 'failed to parse additional information, please enter a valid json';
}
return '';
};
export type ChannelType = 'slack' | 'email' | 'webhook' | 'pagerduty';
export const SlackType = 'slack';
export const WebhookType = 'webhook';
export const PagerType = 'pagerduty';
// LabelFilterStatement will be used for preparing filter conditions / matchers
export interface LabelFilterStatement {
// ref: https://prometheus.io/docs/alerting/latest/configuration/#matcher
// label name
name;
// comparators supported by promql are =, !=, =~, or !~. =
comparator;
// filter value
value;
}
|
6ccc9934eb3767b11ef340ae1335eddfb40936f3 | 1,377 | ts | TypeScript | src/util/utils.ts | LaicZhang/weather-visualization-front-2 | 9da7be792bad7c86e05c47160d5de4ea452fd327 | [
"MIT"
] | 1 | 2022-03-21T01:38:31.000Z | 2022-03-21T01:38:31.000Z | src/util/utils.ts | LaicZhang/weather-visualization-front-2 | 9da7be792bad7c86e05c47160d5de4ea452fd327 | [
"MIT"
] | null | null | null | src/util/utils.ts | LaicZhang/weather-visualization-front-2 | 9da7be792bad7c86e05c47160d5de4ea452fd327 | [
"MIT"
] | null | null | null | /**
* 工具函数封装
*/
export default {
formateDate(date: any, rule = 'yyyy-MM-dd hh:mm:ss'): string {
let fmt: string = rule
if (/(y+)/.test(fmt))
fmt = fmt.replace(RegExp.$1, date.getFullYear())
const o: any = {
// 'y+': date.getFullYear(),
'M+': date.getMonth() + 1,
'd+': date.getDate(),
'h+': date.getHours(),
'm+': date.getMinutes(),
's+': date.getSeconds(),
}
for (const k in o) {
if (new RegExp(`(${k})`).test(fmt)) {
const val = `${o[k]}`
fmt = fmt.replace(RegExp.$1, RegExp.$1.length === 1 ? val : (`00${val}`).substr(val.length))
}
}
return fmt
},
generateRoute(menuList: any) {
const routes: any[] = []
interface ListItem {
name?: string
path?: string
component?: string
children?: any
meta?: any
}
const deepList = (list: any[]) => {
while (list.length) {
const item = list.pop()
if (item.action) {
const temp: ListItem = {
name: item.component,
path: item.path,
meta: {
title: item.menuName,
},
component: item.component,
}
routes.push(temp)
}
if (item.children && !item.action)
deepList(item.children)
}
}
deepList(menuList)
return routes
},
}
| 24.157895 | 100 | 0.485839 | 51 | 3 | 0 | 4 | 7 | 5 | 1 | 7 | 5 | 1 | 0 | 20.333333 | 384 | 0.018229 | 0.018229 | 0.013021 | 0.002604 | 0 | 0.368421 | 0.263158 | 0.270577 | /**
* 工具函数封装
*/
export default {
formateDate(date, rule = 'yyyy-MM-dd hh:mm:ss') {
let fmt = rule
if (/(y+)/.test(fmt))
fmt = fmt.replace(RegExp.$1, date.getFullYear())
const o = {
// 'y+': date.getFullYear(),
'M+': date.getMonth() + 1,
'd+': date.getDate(),
'h+': date.getHours(),
'm+': date.getMinutes(),
's+': date.getSeconds(),
}
for (const k in o) {
if (new RegExp(`(${k})`).test(fmt)) {
const val = `${o[k]}`
fmt = fmt.replace(RegExp.$1, RegExp.$1.length === 1 ? val : (`00${val}`).substr(val.length))
}
}
return fmt
},
generateRoute(menuList) {
const routes = []
interface ListItem {
name?
path?
component?
children?
meta?
}
/* Example usages of 'deepList' are shown below:
deepList(item.children);
deepList(menuList);
*/
const deepList = (list) => {
while (list.length) {
const item = list.pop()
if (item.action) {
const temp = {
name: item.component,
path: item.path,
meta: {
title: item.menuName,
},
component: item.component,
}
routes.push(temp)
}
if (item.children && !item.action)
deepList(item.children)
}
}
deepList(menuList)
return routes
},
}
|
dd422a4acd1879678cd887e096b646d629183ca4 | 5,915 | ts | TypeScript | src/app/helpers/md5.ts | ifuyun/ifuyun.com | c8f8cd8609b05a8e27103b3f247380e0bc5d723e | [
"MIT"
] | 1 | 2022-02-18T21:19:33.000Z | 2022-02-18T21:19:33.000Z | src/app/helpers/md5.ts | ifuyun/ifuyun.com | c8f8cd8609b05a8e27103b3f247380e0bc5d723e | [
"MIT"
] | null | null | null | src/app/helpers/md5.ts | ifuyun/ifuyun.com | c8f8cd8609b05a8e27103b3f247380e0bc5d723e | [
"MIT"
] | null | null | null | // @ts-nocheck
/* 三方库为cmd包,因此直接实现一个原始简化版本 */
export default function md5(a: string): string {
function b(a, b) {
return a << b | a >>> 32 - b;
}
function c(a, b) {
var c, d, e, f, g;
return e = 2147483648 & a,
f = 2147483648 & b,
c = 1073741824 & a,
d = 1073741824 & b,
g = (1073741823 & a) + (1073741823 & b),
c & d ? 2147483648 ^ g ^ e ^ f : c | d ? 1073741824 & g ? 3221225472 ^ g ^ e ^ f : 1073741824 ^ g ^ e ^ f : g ^ e ^ f;
}
function d(a, b, c) {
return a & b | ~a & c;
}
function e(a, b, c) {
return a & c | b & ~c;
}
function f(a, b, c) {
return a ^ b ^ c;
}
function g(a, b, c) {
return b ^ (a | ~c);
}
function h(a, e, f, g, h, i, j) {
return a = c(a, c(c(d(e, f, g), h), j)),
c(b(a, i), e);
}
function i(a, d, f, g, h, i, j) {
return a = c(a, c(c(e(d, f, g), h), j)),
c(b(a, i), d);
}
function j(a, d, e, g, h, i, j) {
return a = c(a, c(c(f(d, e, g), h), j)),
c(b(a, i), d);
}
function k(a, d, e, f, h, i, j) {
return a = c(a, c(c(g(d, e, f), h), j)),
c(b(a, i), d);
}
function l(a) {
for (var b, c = a.length, d = c + 8, e = (d - d % 64) / 64, f = 16 * (e + 1), g = new Array(f - 1), h = 0, i = 0; c > i;) {
b = (i - i % 4) / 4;
h = i % 4 * 8;
g[b] = g[b] | a.charCodeAt(i) << h;
i++;
}
b = (i - i % 4) / 4;
h = i % 4 * 8;
g[b] = g[b] | 128 << h;
g[f - 2] = c << 3;
g[f - 1] = c >>> 29;
return g;
}
function m(a) {
var b, c, d = '', e = '';
for (c = 0; 3 >= c; c++) {
b = a >>> 8 * c & 255;
e = '0' + b.toString(16);
d += e.substr(e.length - 2, 2);
}
return d;
}
function n(a) {
a = a.replace(/\r\n/g, '\n');
for (var b = '', c = 0; c < a.length; c++) {
var d = a.charCodeAt(c);
128 > d ? b += String.fromCharCode(d) : d > 127 && 2048 > d ? (b += String.fromCharCode(d >> 6 | 192),
b += String.fromCharCode(63 & d | 128)) : (b += String.fromCharCode(d >> 12 | 224),
b += String.fromCharCode(d >> 6 & 63 | 128),
b += String.fromCharCode(63 & d | 128));
}
return b;
}
var o, p, q, r, s, t, u, v, w, x = [], y = 7, z = 12, A = 17, B = 22, C = 5, D = 9, E = 14, F = 20, G = 4, H = 11,
I = 16, J = 23, K = 6, L = 10, M = 15, N = 21;
for (a = n(a),
x = l(a),
t = 1732584193,
u = 4023233417,
v = 2562383102,
w = 271733878,
o = 0; o < x.length; o += 16)
p = t,
q = u,
r = v,
s = w,
t = h(t, u, v, w, x[o], y, 3614090360),
w = h(w, t, u, v, x[o + 1], z, 3905402710),
v = h(v, w, t, u, x[o + 2], A, 606105819),
u = h(u, v, w, t, x[o + 3], B, 3250441966),
t = h(t, u, v, w, x[o + 4], y, 4118548399),
w = h(w, t, u, v, x[o + 5], z, 1200080426),
v = h(v, w, t, u, x[o + 6], A, 2821735955),
u = h(u, v, w, t, x[o + 7], B, 4249261313),
t = h(t, u, v, w, x[o + 8], y, 1770035416),
w = h(w, t, u, v, x[o + 9], z, 2336552879),
v = h(v, w, t, u, x[o + 10], A, 4294925233),
u = h(u, v, w, t, x[o + 11], B, 2304563134),
t = h(t, u, v, w, x[o + 12], y, 1804603682),
w = h(w, t, u, v, x[o + 13], z, 4254626195),
v = h(v, w, t, u, x[o + 14], A, 2792965006),
u = h(u, v, w, t, x[o + 15], B, 1236535329),
t = i(t, u, v, w, x[o + 1], C, 4129170786),
w = i(w, t, u, v, x[o + 6], D, 3225465664),
v = i(v, w, t, u, x[o + 11], E, 643717713),
u = i(u, v, w, t, x[o], F, 3921069994),
t = i(t, u, v, w, x[o + 5], C, 3593408605),
w = i(w, t, u, v, x[o + 10], D, 38016083),
v = i(v, w, t, u, x[o + 15], E, 3634488961),
u = i(u, v, w, t, x[o + 4], F, 3889429448),
t = i(t, u, v, w, x[o + 9], C, 568446438),
w = i(w, t, u, v, x[o + 14], D, 3275163606),
v = i(v, w, t, u, x[o + 3], E, 4107603335),
u = i(u, v, w, t, x[o + 8], F, 1163531501),
t = i(t, u, v, w, x[o + 13], C, 2850285829),
w = i(w, t, u, v, x[o + 2], D, 4243563512),
v = i(v, w, t, u, x[o + 7], E, 1735328473),
u = i(u, v, w, t, x[o + 12], F, 2368359562),
t = j(t, u, v, w, x[o + 5], G, 4294588738),
w = j(w, t, u, v, x[o + 8], H, 2272392833),
v = j(v, w, t, u, x[o + 11], I, 1839030562),
u = j(u, v, w, t, x[o + 14], J, 4259657740),
t = j(t, u, v, w, x[o + 1], G, 2763975236),
w = j(w, t, u, v, x[o + 4], H, 1272893353),
v = j(v, w, t, u, x[o + 7], I, 4139469664),
u = j(u, v, w, t, x[o + 10], J, 3200236656),
t = j(t, u, v, w, x[o + 13], G, 681279174),
w = j(w, t, u, v, x[o], H, 3936430074),
v = j(v, w, t, u, x[o + 3], I, 3572445317),
u = j(u, v, w, t, x[o + 6], J, 76029189),
t = j(t, u, v, w, x[o + 9], G, 3654602809),
w = j(w, t, u, v, x[o + 12], H, 3873151461),
v = j(v, w, t, u, x[o + 15], I, 530742520),
u = j(u, v, w, t, x[o + 2], J, 3299628645),
t = k(t, u, v, w, x[o], K, 4096336452),
w = k(w, t, u, v, x[o + 7], L, 1126891415),
v = k(v, w, t, u, x[o + 14], M, 2878612391),
u = k(u, v, w, t, x[o + 5], N, 4237533241),
t = k(t, u, v, w, x[o + 12], K, 1700485571),
w = k(w, t, u, v, x[o + 3], L, 2399980690),
v = k(v, w, t, u, x[o + 10], M, 4293915773),
u = k(u, v, w, t, x[o + 1], N, 2240044497),
t = k(t, u, v, w, x[o + 8], K, 1873313359),
w = k(w, t, u, v, x[o + 15], L, 4264355552),
v = k(v, w, t, u, x[o + 6], M, 2734768916),
u = k(u, v, w, t, x[o + 13], N, 1309151649),
t = k(t, u, v, w, x[o + 4], K, 4149444226),
w = k(w, t, u, v, x[o + 11], L, 3174756917),
v = k(v, w, t, u, x[o + 2], M, 718787259),
u = k(u, v, w, t, x[o + 9], N, 3951481745),
t = c(t, p),
u = c(u, q),
v = c(v, r),
w = c(w, s);
var O = m(t) + m(u) + m(v) + m(w);
return O.toLowerCase();
}
| 33.8 | 127 | 0.398478 | 159 | 14 | 0 | 48 | 47 | 0 | 13 | 0 | 2 | 0 | 0 | 14.642857 | 3,543 | 0.017499 | 0.013266 | 0 | 0 | 0 | 0 | 0.018349 | 0.25766 | // @ts-nocheck
/* 三方库为cmd包,因此直接实现一个原始简化版本 */
export default function md5(a) {
/* Example usages of 'b' are shown below:
;
a << b | a >>> 32 - b;
e = 2147483648 & a,
f = 2147483648 & b,
c = 1073741824 & a,
d = 1073741824 & b,
g = (1073741823 & a) + (1073741823 & b),
c & d ? 2147483648 ^ g ^ e ^ f : c | d ? 1073741824 & g ? 3221225472 ^ g ^ e ^ f : 1073741824 ^ g ^ e ^ f : g ^ e ^ f;
1073741823 & b;
a & b | ~a & c;
a & c | b & ~c;
a ^ b ^ c;
b ^ (a | ~c);
a = c(a, c(c(d(e, f, g), h), j)),
c(b(a, i), e);
a = c(a, c(c(e(d, f, g), h), j)),
c(b(a, i), d);
a = c(a, c(c(f(d, e, g), h), j)),
c(b(a, i), d);
a = c(a, c(c(g(d, e, f), h), j)),
c(b(a, i), d);
var b;
b = (i - i % 4) / 4;
g[b] = g[b] | a.charCodeAt(i) << h;
g[b] = g[b] | 128 << h;
b = a >>> 8 * c & 255;
e = '0' + b.toString(16);
var b = '';
128 > d ? b += String.fromCharCode(d) : d > 127 && 2048 > d ? (b += String.fromCharCode(d >> 6 | 192),
b += String.fromCharCode(63 & d | 128)) : (b += String.fromCharCode(d >> 12 | 224),
b += String.fromCharCode(d >> 6 & 63 | 128),
b += String.fromCharCode(63 & d | 128));
b += String.fromCharCode(d >> 6 | 192),
b += String.fromCharCode(63 & d | 128);
b += String.fromCharCode(d >> 12 | 224),
b += String.fromCharCode(d >> 6 & 63 | 128),
b += String.fromCharCode(63 & d | 128);
return b;
*/
function b(a, b) {
return a << b | a >>> 32 - b;
}
/* Example usages of 'c' are shown below:
var c;
e = 2147483648 & a,
f = 2147483648 & b,
c = 1073741824 & a,
d = 1073741824 & b,
g = (1073741823 & a) + (1073741823 & b),
c & d ? 2147483648 ^ g ^ e ^ f : c | d ? 1073741824 & g ? 3221225472 ^ g ^ e ^ f : 1073741824 ^ g ^ e ^ f : g ^ e ^ f;
;
a & b | ~a & c;
a & c | b & ~c;
a ^ b ^ c;
a | ~c;
a = c(a, c(c(d(e, f, g), h), j)),
c(b(a, i), e);
a = c(a, c(c(e(d, f, g), h), j)),
c(b(a, i), d);
a = c(a, c(c(f(d, e, g), h), j)),
c(b(a, i), d);
a = c(a, c(c(g(d, e, f), h), j)),
c(b(a, i), d);
var c = a.length;
c + 8;
c > i;
g[f - 2] = c << 3;
g[f - 1] = c >>> 29;
c = 0;
3 >= c;
c++;
b = a >>> 8 * c & 255;
var c = 0;
c < a.length;
a.charCodeAt(c);
p = t,
q = u,
r = v,
s = w,
t = h(t, u, v, w, x[o], y, 3614090360),
w = h(w, t, u, v, x[o + 1], z, 3905402710),
v = h(v, w, t, u, x[o + 2], A, 606105819),
u = h(u, v, w, t, x[o + 3], B, 3250441966),
t = h(t, u, v, w, x[o + 4], y, 4118548399),
w = h(w, t, u, v, x[o + 5], z, 1200080426),
v = h(v, w, t, u, x[o + 6], A, 2821735955),
u = h(u, v, w, t, x[o + 7], B, 4249261313),
t = h(t, u, v, w, x[o + 8], y, 1770035416),
w = h(w, t, u, v, x[o + 9], z, 2336552879),
v = h(v, w, t, u, x[o + 10], A, 4294925233),
u = h(u, v, w, t, x[o + 11], B, 2304563134),
t = h(t, u, v, w, x[o + 12], y, 1804603682),
w = h(w, t, u, v, x[o + 13], z, 4254626195),
v = h(v, w, t, u, x[o + 14], A, 2792965006),
u = h(u, v, w, t, x[o + 15], B, 1236535329),
t = i(t, u, v, w, x[o + 1], C, 4129170786),
w = i(w, t, u, v, x[o + 6], D, 3225465664),
v = i(v, w, t, u, x[o + 11], E, 643717713),
u = i(u, v, w, t, x[o], F, 3921069994),
t = i(t, u, v, w, x[o + 5], C, 3593408605),
w = i(w, t, u, v, x[o + 10], D, 38016083),
v = i(v, w, t, u, x[o + 15], E, 3634488961),
u = i(u, v, w, t, x[o + 4], F, 3889429448),
t = i(t, u, v, w, x[o + 9], C, 568446438),
w = i(w, t, u, v, x[o + 14], D, 3275163606),
v = i(v, w, t, u, x[o + 3], E, 4107603335),
u = i(u, v, w, t, x[o + 8], F, 1163531501),
t = i(t, u, v, w, x[o + 13], C, 2850285829),
w = i(w, t, u, v, x[o + 2], D, 4243563512),
v = i(v, w, t, u, x[o + 7], E, 1735328473),
u = i(u, v, w, t, x[o + 12], F, 2368359562),
t = j(t, u, v, w, x[o + 5], G, 4294588738),
w = j(w, t, u, v, x[o + 8], H, 2272392833),
v = j(v, w, t, u, x[o + 11], I, 1839030562),
u = j(u, v, w, t, x[o + 14], J, 4259657740),
t = j(t, u, v, w, x[o + 1], G, 2763975236),
w = j(w, t, u, v, x[o + 4], H, 1272893353),
v = j(v, w, t, u, x[o + 7], I, 4139469664),
u = j(u, v, w, t, x[o + 10], J, 3200236656),
t = j(t, u, v, w, x[o + 13], G, 681279174),
w = j(w, t, u, v, x[o], H, 3936430074),
v = j(v, w, t, u, x[o + 3], I, 3572445317),
u = j(u, v, w, t, x[o + 6], J, 76029189),
t = j(t, u, v, w, x[o + 9], G, 3654602809),
w = j(w, t, u, v, x[o + 12], H, 3873151461),
v = j(v, w, t, u, x[o + 15], I, 530742520),
u = j(u, v, w, t, x[o + 2], J, 3299628645),
t = k(t, u, v, w, x[o], K, 4096336452),
w = k(w, t, u, v, x[o + 7], L, 1126891415),
v = k(v, w, t, u, x[o + 14], M, 2878612391),
u = k(u, v, w, t, x[o + 5], N, 4237533241),
t = k(t, u, v, w, x[o + 12], K, 1700485571),
w = k(w, t, u, v, x[o + 3], L, 2399980690),
v = k(v, w, t, u, x[o + 10], M, 4293915773),
u = k(u, v, w, t, x[o + 1], N, 2240044497),
t = k(t, u, v, w, x[o + 8], K, 1873313359),
w = k(w, t, u, v, x[o + 15], L, 4264355552),
v = k(v, w, t, u, x[o + 6], M, 2734768916),
u = k(u, v, w, t, x[o + 13], N, 1309151649),
t = k(t, u, v, w, x[o + 4], K, 4149444226),
w = k(w, t, u, v, x[o + 11], L, 3174756917),
v = k(v, w, t, u, x[o + 2], M, 718787259),
u = k(u, v, w, t, x[o + 9], N, 3951481745),
t = c(t, p),
u = c(u, q),
v = c(v, r),
w = c(w, s);
*/
function c(a, b) {
var c, d, e, f, g;
return e = 2147483648 & a,
f = 2147483648 & b,
c = 1073741824 & a,
d = 1073741824 & b,
g = (1073741823 & a) + (1073741823 & b),
c & d ? 2147483648 ^ g ^ e ^ f : c | d ? 1073741824 & g ? 3221225472 ^ g ^ e ^ f : 1073741824 ^ g ^ e ^ f : g ^ e ^ f;
}
/* Example usages of 'd' are shown below:
var d;
e = 2147483648 & a,
f = 2147483648 & b,
c = 1073741824 & a,
d = 1073741824 & b,
g = (1073741823 & a) + (1073741823 & b),
c & d ? 2147483648 ^ g ^ e ^ f : c | d ? 1073741824 & g ? 3221225472 ^ g ^ e ^ f : 1073741824 ^ g ^ e ^ f : g ^ e ^ f;
a = c(a, c(c(d(e, f, g), h), j)),
c(b(a, i), e);
;
a = c(a, c(c(e(d, f, g), h), j)),
c(b(a, i), d);
a = c(a, c(c(f(d, e, g), h), j)),
c(b(a, i), d);
a = c(a, c(c(g(d, e, f), h), j)),
c(b(a, i), d);
var d = c + 8;
d - d % 64;
var d = '';
d += e.substr(e.length - 2, 2);
return d;
var d = a.charCodeAt(c);
128 > d ? b += String.fromCharCode(d) : d > 127 && 2048 > d ? (b += String.fromCharCode(d >> 6 | 192),
b += String.fromCharCode(63 & d | 128)) : (b += String.fromCharCode(d >> 12 | 224),
b += String.fromCharCode(d >> 6 & 63 | 128),
b += String.fromCharCode(63 & d | 128));
b += String.fromCharCode(d >> 6 | 192),
b += String.fromCharCode(63 & d | 128);
b += String.fromCharCode(d >> 12 | 224),
b += String.fromCharCode(d >> 6 & 63 | 128),
b += String.fromCharCode(63 & d | 128);
*/
function d(a, b, c) {
return a & b | ~a & c;
}
/* Example usages of 'e' are shown below:
var e;
e = 2147483648 & a,
f = 2147483648 & b,
c = 1073741824 & a,
d = 1073741824 & b,
g = (1073741823 & a) + (1073741823 & b),
c & d ? 2147483648 ^ g ^ e ^ f : c | d ? 1073741824 & g ? 3221225472 ^ g ^ e ^ f : 1073741824 ^ g ^ e ^ f : g ^ e ^ f;
;
a = c(a, c(c(d(e, f, g), h), j)),
c(b(a, i), e);
a = c(a, c(c(e(d, f, g), h), j)),
c(b(a, i), d);
a = c(a, c(c(f(d, e, g), h), j)),
c(b(a, i), d);
a = c(a, c(c(g(d, e, f), h), j)),
c(b(a, i), d);
var e = (d - d % 64) / 64;
e + 1;
var e = '';
e = '0' + b.toString(16);
d += e.substr(e.length - 2, 2);
*/
function e(a, b, c) {
return a & c | b & ~c;
}
/* Example usages of 'f' are shown below:
var f;
e = 2147483648 & a,
f = 2147483648 & b,
c = 1073741824 & a,
d = 1073741824 & b,
g = (1073741823 & a) + (1073741823 & b),
c & d ? 2147483648 ^ g ^ e ^ f : c | d ? 1073741824 & g ? 3221225472 ^ g ^ e ^ f : 1073741824 ^ g ^ e ^ f : g ^ e ^ f;
;
a = c(a, c(c(d(e, f, g), h), j)),
c(b(a, i), e);
a = c(a, c(c(e(d, f, g), h), j)),
c(b(a, i), d);
a = c(a, c(c(f(d, e, g), h), j)),
c(b(a, i), d);
a = c(a, c(c(g(d, e, f), h), j)),
c(b(a, i), d);
var f = 16 * (e + 1);
new Array(f - 1);
g[f - 2] = c << 3;
g[f - 1] = c >>> 29;
*/
function f(a, b, c) {
return a ^ b ^ c;
}
/* Example usages of 'g' are shown below:
var g;
e = 2147483648 & a,
f = 2147483648 & b,
c = 1073741824 & a,
d = 1073741824 & b,
g = (1073741823 & a) + (1073741823 & b),
c & d ? 2147483648 ^ g ^ e ^ f : c | d ? 1073741824 & g ? 3221225472 ^ g ^ e ^ f : 1073741824 ^ g ^ e ^ f : g ^ e ^ f;
;
a = c(a, c(c(d(e, f, g), h), j)),
c(b(a, i), e);
a = c(a, c(c(e(d, f, g), h), j)),
c(b(a, i), d);
a = c(a, c(c(f(d, e, g), h), j)),
c(b(a, i), d);
a = c(a, c(c(g(d, e, f), h), j)),
c(b(a, i), d);
var g = new Array(f - 1);
g[b] = g[b] | a.charCodeAt(i) << h;
g[b] = g[b] | 128 << h;
g[f - 2] = c << 3;
g[f - 1] = c >>> 29;
return g;
*/
function g(a, b, c) {
return b ^ (a | ~c);
}
/* Example usages of 'h' are shown below:
;
a = c(a, c(c(d(e, f, g), h), j)),
c(b(a, i), e);
a = c(a, c(c(e(d, f, g), h), j)),
c(b(a, i), d);
a = c(a, c(c(f(d, e, g), h), j)),
c(b(a, i), d);
a = c(a, c(c(g(d, e, f), h), j)),
c(b(a, i), d);
var h = 0;
h = i % 4 * 8;
g[b] = g[b] | a.charCodeAt(i) << h;
g[b] = g[b] | 128 << h;
p = t,
q = u,
r = v,
s = w,
t = h(t, u, v, w, x[o], y, 3614090360),
w = h(w, t, u, v, x[o + 1], z, 3905402710),
v = h(v, w, t, u, x[o + 2], A, 606105819),
u = h(u, v, w, t, x[o + 3], B, 3250441966),
t = h(t, u, v, w, x[o + 4], y, 4118548399),
w = h(w, t, u, v, x[o + 5], z, 1200080426),
v = h(v, w, t, u, x[o + 6], A, 2821735955),
u = h(u, v, w, t, x[o + 7], B, 4249261313),
t = h(t, u, v, w, x[o + 8], y, 1770035416),
w = h(w, t, u, v, x[o + 9], z, 2336552879),
v = h(v, w, t, u, x[o + 10], A, 4294925233),
u = h(u, v, w, t, x[o + 11], B, 2304563134),
t = h(t, u, v, w, x[o + 12], y, 1804603682),
w = h(w, t, u, v, x[o + 13], z, 4254626195),
v = h(v, w, t, u, x[o + 14], A, 2792965006),
u = h(u, v, w, t, x[o + 15], B, 1236535329),
t = i(t, u, v, w, x[o + 1], C, 4129170786),
w = i(w, t, u, v, x[o + 6], D, 3225465664),
v = i(v, w, t, u, x[o + 11], E, 643717713),
u = i(u, v, w, t, x[o], F, 3921069994),
t = i(t, u, v, w, x[o + 5], C, 3593408605),
w = i(w, t, u, v, x[o + 10], D, 38016083),
v = i(v, w, t, u, x[o + 15], E, 3634488961),
u = i(u, v, w, t, x[o + 4], F, 3889429448),
t = i(t, u, v, w, x[o + 9], C, 568446438),
w = i(w, t, u, v, x[o + 14], D, 3275163606),
v = i(v, w, t, u, x[o + 3], E, 4107603335),
u = i(u, v, w, t, x[o + 8], F, 1163531501),
t = i(t, u, v, w, x[o + 13], C, 2850285829),
w = i(w, t, u, v, x[o + 2], D, 4243563512),
v = i(v, w, t, u, x[o + 7], E, 1735328473),
u = i(u, v, w, t, x[o + 12], F, 2368359562),
t = j(t, u, v, w, x[o + 5], G, 4294588738),
w = j(w, t, u, v, x[o + 8], H, 2272392833),
v = j(v, w, t, u, x[o + 11], I, 1839030562),
u = j(u, v, w, t, x[o + 14], J, 4259657740),
t = j(t, u, v, w, x[o + 1], G, 2763975236),
w = j(w, t, u, v, x[o + 4], H, 1272893353),
v = j(v, w, t, u, x[o + 7], I, 4139469664),
u = j(u, v, w, t, x[o + 10], J, 3200236656),
t = j(t, u, v, w, x[o + 13], G, 681279174),
w = j(w, t, u, v, x[o], H, 3936430074),
v = j(v, w, t, u, x[o + 3], I, 3572445317),
u = j(u, v, w, t, x[o + 6], J, 76029189),
t = j(t, u, v, w, x[o + 9], G, 3654602809),
w = j(w, t, u, v, x[o + 12], H, 3873151461),
v = j(v, w, t, u, x[o + 15], I, 530742520),
u = j(u, v, w, t, x[o + 2], J, 3299628645),
t = k(t, u, v, w, x[o], K, 4096336452),
w = k(w, t, u, v, x[o + 7], L, 1126891415),
v = k(v, w, t, u, x[o + 14], M, 2878612391),
u = k(u, v, w, t, x[o + 5], N, 4237533241),
t = k(t, u, v, w, x[o + 12], K, 1700485571),
w = k(w, t, u, v, x[o + 3], L, 2399980690),
v = k(v, w, t, u, x[o + 10], M, 4293915773),
u = k(u, v, w, t, x[o + 1], N, 2240044497),
t = k(t, u, v, w, x[o + 8], K, 1873313359),
w = k(w, t, u, v, x[o + 15], L, 4264355552),
v = k(v, w, t, u, x[o + 6], M, 2734768916),
u = k(u, v, w, t, x[o + 13], N, 1309151649),
t = k(t, u, v, w, x[o + 4], K, 4149444226),
w = k(w, t, u, v, x[o + 11], L, 3174756917),
v = k(v, w, t, u, x[o + 2], M, 718787259),
u = k(u, v, w, t, x[o + 9], N, 3951481745),
t = c(t, p),
u = c(u, q),
v = c(v, r),
w = c(w, s);
*/
function h(a, e, f, g, h, i, j) {
return a = c(a, c(c(d(e, f, g), h), j)),
c(b(a, i), e);
}
/* Example usages of 'i' are shown below:
;
a = c(a, c(c(d(e, f, g), h), j)),
c(b(a, i), e);
a = c(a, c(c(e(d, f, g), h), j)),
c(b(a, i), d);
a = c(a, c(c(f(d, e, g), h), j)),
c(b(a, i), d);
a = c(a, c(c(g(d, e, f), h), j)),
c(b(a, i), d);
var i = 0;
c > i;
i - i % 4;
h = i % 4 * 8;
g[b] = g[b] | a.charCodeAt(i) << h;
i++;
p = t,
q = u,
r = v,
s = w,
t = h(t, u, v, w, x[o], y, 3614090360),
w = h(w, t, u, v, x[o + 1], z, 3905402710),
v = h(v, w, t, u, x[o + 2], A, 606105819),
u = h(u, v, w, t, x[o + 3], B, 3250441966),
t = h(t, u, v, w, x[o + 4], y, 4118548399),
w = h(w, t, u, v, x[o + 5], z, 1200080426),
v = h(v, w, t, u, x[o + 6], A, 2821735955),
u = h(u, v, w, t, x[o + 7], B, 4249261313),
t = h(t, u, v, w, x[o + 8], y, 1770035416),
w = h(w, t, u, v, x[o + 9], z, 2336552879),
v = h(v, w, t, u, x[o + 10], A, 4294925233),
u = h(u, v, w, t, x[o + 11], B, 2304563134),
t = h(t, u, v, w, x[o + 12], y, 1804603682),
w = h(w, t, u, v, x[o + 13], z, 4254626195),
v = h(v, w, t, u, x[o + 14], A, 2792965006),
u = h(u, v, w, t, x[o + 15], B, 1236535329),
t = i(t, u, v, w, x[o + 1], C, 4129170786),
w = i(w, t, u, v, x[o + 6], D, 3225465664),
v = i(v, w, t, u, x[o + 11], E, 643717713),
u = i(u, v, w, t, x[o], F, 3921069994),
t = i(t, u, v, w, x[o + 5], C, 3593408605),
w = i(w, t, u, v, x[o + 10], D, 38016083),
v = i(v, w, t, u, x[o + 15], E, 3634488961),
u = i(u, v, w, t, x[o + 4], F, 3889429448),
t = i(t, u, v, w, x[o + 9], C, 568446438),
w = i(w, t, u, v, x[o + 14], D, 3275163606),
v = i(v, w, t, u, x[o + 3], E, 4107603335),
u = i(u, v, w, t, x[o + 8], F, 1163531501),
t = i(t, u, v, w, x[o + 13], C, 2850285829),
w = i(w, t, u, v, x[o + 2], D, 4243563512),
v = i(v, w, t, u, x[o + 7], E, 1735328473),
u = i(u, v, w, t, x[o + 12], F, 2368359562),
t = j(t, u, v, w, x[o + 5], G, 4294588738),
w = j(w, t, u, v, x[o + 8], H, 2272392833),
v = j(v, w, t, u, x[o + 11], I, 1839030562),
u = j(u, v, w, t, x[o + 14], J, 4259657740),
t = j(t, u, v, w, x[o + 1], G, 2763975236),
w = j(w, t, u, v, x[o + 4], H, 1272893353),
v = j(v, w, t, u, x[o + 7], I, 4139469664),
u = j(u, v, w, t, x[o + 10], J, 3200236656),
t = j(t, u, v, w, x[o + 13], G, 681279174),
w = j(w, t, u, v, x[o], H, 3936430074),
v = j(v, w, t, u, x[o + 3], I, 3572445317),
u = j(u, v, w, t, x[o + 6], J, 76029189),
t = j(t, u, v, w, x[o + 9], G, 3654602809),
w = j(w, t, u, v, x[o + 12], H, 3873151461),
v = j(v, w, t, u, x[o + 15], I, 530742520),
u = j(u, v, w, t, x[o + 2], J, 3299628645),
t = k(t, u, v, w, x[o], K, 4096336452),
w = k(w, t, u, v, x[o + 7], L, 1126891415),
v = k(v, w, t, u, x[o + 14], M, 2878612391),
u = k(u, v, w, t, x[o + 5], N, 4237533241),
t = k(t, u, v, w, x[o + 12], K, 1700485571),
w = k(w, t, u, v, x[o + 3], L, 2399980690),
v = k(v, w, t, u, x[o + 10], M, 4293915773),
u = k(u, v, w, t, x[o + 1], N, 2240044497),
t = k(t, u, v, w, x[o + 8], K, 1873313359),
w = k(w, t, u, v, x[o + 15], L, 4264355552),
v = k(v, w, t, u, x[o + 6], M, 2734768916),
u = k(u, v, w, t, x[o + 13], N, 1309151649),
t = k(t, u, v, w, x[o + 4], K, 4149444226),
w = k(w, t, u, v, x[o + 11], L, 3174756917),
v = k(v, w, t, u, x[o + 2], M, 718787259),
u = k(u, v, w, t, x[o + 9], N, 3951481745),
t = c(t, p),
u = c(u, q),
v = c(v, r),
w = c(w, s);
*/
function i(a, d, f, g, h, i, j) {
return a = c(a, c(c(e(d, f, g), h), j)),
c(b(a, i), d);
}
/* Example usages of 'j' are shown below:
;
a = c(a, c(c(d(e, f, g), h), j)),
c(b(a, i), e);
a = c(a, c(c(e(d, f, g), h), j)),
c(b(a, i), d);
a = c(a, c(c(f(d, e, g), h), j)),
c(b(a, i), d);
a = c(a, c(c(g(d, e, f), h), j)),
c(b(a, i), d);
p = t,
q = u,
r = v,
s = w,
t = h(t, u, v, w, x[o], y, 3614090360),
w = h(w, t, u, v, x[o + 1], z, 3905402710),
v = h(v, w, t, u, x[o + 2], A, 606105819),
u = h(u, v, w, t, x[o + 3], B, 3250441966),
t = h(t, u, v, w, x[o + 4], y, 4118548399),
w = h(w, t, u, v, x[o + 5], z, 1200080426),
v = h(v, w, t, u, x[o + 6], A, 2821735955),
u = h(u, v, w, t, x[o + 7], B, 4249261313),
t = h(t, u, v, w, x[o + 8], y, 1770035416),
w = h(w, t, u, v, x[o + 9], z, 2336552879),
v = h(v, w, t, u, x[o + 10], A, 4294925233),
u = h(u, v, w, t, x[o + 11], B, 2304563134),
t = h(t, u, v, w, x[o + 12], y, 1804603682),
w = h(w, t, u, v, x[o + 13], z, 4254626195),
v = h(v, w, t, u, x[o + 14], A, 2792965006),
u = h(u, v, w, t, x[o + 15], B, 1236535329),
t = i(t, u, v, w, x[o + 1], C, 4129170786),
w = i(w, t, u, v, x[o + 6], D, 3225465664),
v = i(v, w, t, u, x[o + 11], E, 643717713),
u = i(u, v, w, t, x[o], F, 3921069994),
t = i(t, u, v, w, x[o + 5], C, 3593408605),
w = i(w, t, u, v, x[o + 10], D, 38016083),
v = i(v, w, t, u, x[o + 15], E, 3634488961),
u = i(u, v, w, t, x[o + 4], F, 3889429448),
t = i(t, u, v, w, x[o + 9], C, 568446438),
w = i(w, t, u, v, x[o + 14], D, 3275163606),
v = i(v, w, t, u, x[o + 3], E, 4107603335),
u = i(u, v, w, t, x[o + 8], F, 1163531501),
t = i(t, u, v, w, x[o + 13], C, 2850285829),
w = i(w, t, u, v, x[o + 2], D, 4243563512),
v = i(v, w, t, u, x[o + 7], E, 1735328473),
u = i(u, v, w, t, x[o + 12], F, 2368359562),
t = j(t, u, v, w, x[o + 5], G, 4294588738),
w = j(w, t, u, v, x[o + 8], H, 2272392833),
v = j(v, w, t, u, x[o + 11], I, 1839030562),
u = j(u, v, w, t, x[o + 14], J, 4259657740),
t = j(t, u, v, w, x[o + 1], G, 2763975236),
w = j(w, t, u, v, x[o + 4], H, 1272893353),
v = j(v, w, t, u, x[o + 7], I, 4139469664),
u = j(u, v, w, t, x[o + 10], J, 3200236656),
t = j(t, u, v, w, x[o + 13], G, 681279174),
w = j(w, t, u, v, x[o], H, 3936430074),
v = j(v, w, t, u, x[o + 3], I, 3572445317),
u = j(u, v, w, t, x[o + 6], J, 76029189),
t = j(t, u, v, w, x[o + 9], G, 3654602809),
w = j(w, t, u, v, x[o + 12], H, 3873151461),
v = j(v, w, t, u, x[o + 15], I, 530742520),
u = j(u, v, w, t, x[o + 2], J, 3299628645),
t = k(t, u, v, w, x[o], K, 4096336452),
w = k(w, t, u, v, x[o + 7], L, 1126891415),
v = k(v, w, t, u, x[o + 14], M, 2878612391),
u = k(u, v, w, t, x[o + 5], N, 4237533241),
t = k(t, u, v, w, x[o + 12], K, 1700485571),
w = k(w, t, u, v, x[o + 3], L, 2399980690),
v = k(v, w, t, u, x[o + 10], M, 4293915773),
u = k(u, v, w, t, x[o + 1], N, 2240044497),
t = k(t, u, v, w, x[o + 8], K, 1873313359),
w = k(w, t, u, v, x[o + 15], L, 4264355552),
v = k(v, w, t, u, x[o + 6], M, 2734768916),
u = k(u, v, w, t, x[o + 13], N, 1309151649),
t = k(t, u, v, w, x[o + 4], K, 4149444226),
w = k(w, t, u, v, x[o + 11], L, 3174756917),
v = k(v, w, t, u, x[o + 2], M, 718787259),
u = k(u, v, w, t, x[o + 9], N, 3951481745),
t = c(t, p),
u = c(u, q),
v = c(v, r),
w = c(w, s);
*/
function j(a, d, e, g, h, i, j) {
return a = c(a, c(c(f(d, e, g), h), j)),
c(b(a, i), d);
}
/* Example usages of 'k' are shown below:
p = t,
q = u,
r = v,
s = w,
t = h(t, u, v, w, x[o], y, 3614090360),
w = h(w, t, u, v, x[o + 1], z, 3905402710),
v = h(v, w, t, u, x[o + 2], A, 606105819),
u = h(u, v, w, t, x[o + 3], B, 3250441966),
t = h(t, u, v, w, x[o + 4], y, 4118548399),
w = h(w, t, u, v, x[o + 5], z, 1200080426),
v = h(v, w, t, u, x[o + 6], A, 2821735955),
u = h(u, v, w, t, x[o + 7], B, 4249261313),
t = h(t, u, v, w, x[o + 8], y, 1770035416),
w = h(w, t, u, v, x[o + 9], z, 2336552879),
v = h(v, w, t, u, x[o + 10], A, 4294925233),
u = h(u, v, w, t, x[o + 11], B, 2304563134),
t = h(t, u, v, w, x[o + 12], y, 1804603682),
w = h(w, t, u, v, x[o + 13], z, 4254626195),
v = h(v, w, t, u, x[o + 14], A, 2792965006),
u = h(u, v, w, t, x[o + 15], B, 1236535329),
t = i(t, u, v, w, x[o + 1], C, 4129170786),
w = i(w, t, u, v, x[o + 6], D, 3225465664),
v = i(v, w, t, u, x[o + 11], E, 643717713),
u = i(u, v, w, t, x[o], F, 3921069994),
t = i(t, u, v, w, x[o + 5], C, 3593408605),
w = i(w, t, u, v, x[o + 10], D, 38016083),
v = i(v, w, t, u, x[o + 15], E, 3634488961),
u = i(u, v, w, t, x[o + 4], F, 3889429448),
t = i(t, u, v, w, x[o + 9], C, 568446438),
w = i(w, t, u, v, x[o + 14], D, 3275163606),
v = i(v, w, t, u, x[o + 3], E, 4107603335),
u = i(u, v, w, t, x[o + 8], F, 1163531501),
t = i(t, u, v, w, x[o + 13], C, 2850285829),
w = i(w, t, u, v, x[o + 2], D, 4243563512),
v = i(v, w, t, u, x[o + 7], E, 1735328473),
u = i(u, v, w, t, x[o + 12], F, 2368359562),
t = j(t, u, v, w, x[o + 5], G, 4294588738),
w = j(w, t, u, v, x[o + 8], H, 2272392833),
v = j(v, w, t, u, x[o + 11], I, 1839030562),
u = j(u, v, w, t, x[o + 14], J, 4259657740),
t = j(t, u, v, w, x[o + 1], G, 2763975236),
w = j(w, t, u, v, x[o + 4], H, 1272893353),
v = j(v, w, t, u, x[o + 7], I, 4139469664),
u = j(u, v, w, t, x[o + 10], J, 3200236656),
t = j(t, u, v, w, x[o + 13], G, 681279174),
w = j(w, t, u, v, x[o], H, 3936430074),
v = j(v, w, t, u, x[o + 3], I, 3572445317),
u = j(u, v, w, t, x[o + 6], J, 76029189),
t = j(t, u, v, w, x[o + 9], G, 3654602809),
w = j(w, t, u, v, x[o + 12], H, 3873151461),
v = j(v, w, t, u, x[o + 15], I, 530742520),
u = j(u, v, w, t, x[o + 2], J, 3299628645),
t = k(t, u, v, w, x[o], K, 4096336452),
w = k(w, t, u, v, x[o + 7], L, 1126891415),
v = k(v, w, t, u, x[o + 14], M, 2878612391),
u = k(u, v, w, t, x[o + 5], N, 4237533241),
t = k(t, u, v, w, x[o + 12], K, 1700485571),
w = k(w, t, u, v, x[o + 3], L, 2399980690),
v = k(v, w, t, u, x[o + 10], M, 4293915773),
u = k(u, v, w, t, x[o + 1], N, 2240044497),
t = k(t, u, v, w, x[o + 8], K, 1873313359),
w = k(w, t, u, v, x[o + 15], L, 4264355552),
v = k(v, w, t, u, x[o + 6], M, 2734768916),
u = k(u, v, w, t, x[o + 13], N, 1309151649),
t = k(t, u, v, w, x[o + 4], K, 4149444226),
w = k(w, t, u, v, x[o + 11], L, 3174756917),
v = k(v, w, t, u, x[o + 2], M, 718787259),
u = k(u, v, w, t, x[o + 9], N, 3951481745),
t = c(t, p),
u = c(u, q),
v = c(v, r),
w = c(w, s);
*/
function k(a, d, e, f, h, i, j) {
return a = c(a, c(c(g(d, e, f), h), j)),
c(b(a, i), d);
}
/* Example usages of 'l' are shown below:
a = n(a),
x = l(a),
t = 1732584193,
u = 4023233417,
v = 2562383102,
w = 271733878,
o = 0;
*/
function l(a) {
for (var b, c = a.length, d = c + 8, e = (d - d % 64) / 64, f = 16 * (e + 1), g = new Array(f - 1), h = 0, i = 0; c > i;) {
b = (i - i % 4) / 4;
h = i % 4 * 8;
g[b] = g[b] | a.charCodeAt(i) << h;
i++;
}
b = (i - i % 4) / 4;
h = i % 4 * 8;
g[b] = g[b] | 128 << h;
g[f - 2] = c << 3;
g[f - 1] = c >>> 29;
return g;
}
/* Example usages of 'm' are shown below:
m(t) + m(u) + m(v) + m(w);
*/
function m(a) {
var b, c, d = '', e = '';
for (c = 0; 3 >= c; c++) {
b = a >>> 8 * c & 255;
e = '0' + b.toString(16);
d += e.substr(e.length - 2, 2);
}
return d;
}
/* Example usages of 'n' are shown below:
a = n(a),
x = l(a),
t = 1732584193,
u = 4023233417,
v = 2562383102,
w = 271733878,
o = 0;
*/
function n(a) {
a = a.replace(/\r\n/g, '\n');
for (var b = '', c = 0; c < a.length; c++) {
var d = a.charCodeAt(c);
128 > d ? b += String.fromCharCode(d) : d > 127 && 2048 > d ? (b += String.fromCharCode(d >> 6 | 192),
b += String.fromCharCode(63 & d | 128)) : (b += String.fromCharCode(d >> 12 | 224),
b += String.fromCharCode(d >> 6 & 63 | 128),
b += String.fromCharCode(63 & d | 128));
}
return b;
}
var o, p, q, r, s, t, u, v, w, x = [], y = 7, z = 12, A = 17, B = 22, C = 5, D = 9, E = 14, F = 20, G = 4, H = 11,
I = 16, J = 23, K = 6, L = 10, M = 15, N = 21;
for (a = n(a),
x = l(a),
t = 1732584193,
u = 4023233417,
v = 2562383102,
w = 271733878,
o = 0; o < x.length; o += 16)
p = t,
q = u,
r = v,
s = w,
t = h(t, u, v, w, x[o], y, 3614090360),
w = h(w, t, u, v, x[o + 1], z, 3905402710),
v = h(v, w, t, u, x[o + 2], A, 606105819),
u = h(u, v, w, t, x[o + 3], B, 3250441966),
t = h(t, u, v, w, x[o + 4], y, 4118548399),
w = h(w, t, u, v, x[o + 5], z, 1200080426),
v = h(v, w, t, u, x[o + 6], A, 2821735955),
u = h(u, v, w, t, x[o + 7], B, 4249261313),
t = h(t, u, v, w, x[o + 8], y, 1770035416),
w = h(w, t, u, v, x[o + 9], z, 2336552879),
v = h(v, w, t, u, x[o + 10], A, 4294925233),
u = h(u, v, w, t, x[o + 11], B, 2304563134),
t = h(t, u, v, w, x[o + 12], y, 1804603682),
w = h(w, t, u, v, x[o + 13], z, 4254626195),
v = h(v, w, t, u, x[o + 14], A, 2792965006),
u = h(u, v, w, t, x[o + 15], B, 1236535329),
t = i(t, u, v, w, x[o + 1], C, 4129170786),
w = i(w, t, u, v, x[o + 6], D, 3225465664),
v = i(v, w, t, u, x[o + 11], E, 643717713),
u = i(u, v, w, t, x[o], F, 3921069994),
t = i(t, u, v, w, x[o + 5], C, 3593408605),
w = i(w, t, u, v, x[o + 10], D, 38016083),
v = i(v, w, t, u, x[o + 15], E, 3634488961),
u = i(u, v, w, t, x[o + 4], F, 3889429448),
t = i(t, u, v, w, x[o + 9], C, 568446438),
w = i(w, t, u, v, x[o + 14], D, 3275163606),
v = i(v, w, t, u, x[o + 3], E, 4107603335),
u = i(u, v, w, t, x[o + 8], F, 1163531501),
t = i(t, u, v, w, x[o + 13], C, 2850285829),
w = i(w, t, u, v, x[o + 2], D, 4243563512),
v = i(v, w, t, u, x[o + 7], E, 1735328473),
u = i(u, v, w, t, x[o + 12], F, 2368359562),
t = j(t, u, v, w, x[o + 5], G, 4294588738),
w = j(w, t, u, v, x[o + 8], H, 2272392833),
v = j(v, w, t, u, x[o + 11], I, 1839030562),
u = j(u, v, w, t, x[o + 14], J, 4259657740),
t = j(t, u, v, w, x[o + 1], G, 2763975236),
w = j(w, t, u, v, x[o + 4], H, 1272893353),
v = j(v, w, t, u, x[o + 7], I, 4139469664),
u = j(u, v, w, t, x[o + 10], J, 3200236656),
t = j(t, u, v, w, x[o + 13], G, 681279174),
w = j(w, t, u, v, x[o], H, 3936430074),
v = j(v, w, t, u, x[o + 3], I, 3572445317),
u = j(u, v, w, t, x[o + 6], J, 76029189),
t = j(t, u, v, w, x[o + 9], G, 3654602809),
w = j(w, t, u, v, x[o + 12], H, 3873151461),
v = j(v, w, t, u, x[o + 15], I, 530742520),
u = j(u, v, w, t, x[o + 2], J, 3299628645),
t = k(t, u, v, w, x[o], K, 4096336452),
w = k(w, t, u, v, x[o + 7], L, 1126891415),
v = k(v, w, t, u, x[o + 14], M, 2878612391),
u = k(u, v, w, t, x[o + 5], N, 4237533241),
t = k(t, u, v, w, x[o + 12], K, 1700485571),
w = k(w, t, u, v, x[o + 3], L, 2399980690),
v = k(v, w, t, u, x[o + 10], M, 4293915773),
u = k(u, v, w, t, x[o + 1], N, 2240044497),
t = k(t, u, v, w, x[o + 8], K, 1873313359),
w = k(w, t, u, v, x[o + 15], L, 4264355552),
v = k(v, w, t, u, x[o + 6], M, 2734768916),
u = k(u, v, w, t, x[o + 13], N, 1309151649),
t = k(t, u, v, w, x[o + 4], K, 4149444226),
w = k(w, t, u, v, x[o + 11], L, 3174756917),
v = k(v, w, t, u, x[o + 2], M, 718787259),
u = k(u, v, w, t, x[o + 9], N, 3951481745),
t = c(t, p),
u = c(u, q),
v = c(v, r),
w = c(w, s);
var O = m(t) + m(u) + m(v) + m(w);
return O.toLowerCase();
}
|
dd6928f0547b8d3bb85910dc39172417f95d1588 | 2,232 | ts | TypeScript | libs/amyr-ts-lib/src/lib/libs/tsmt/datastructures/utils/quick-select.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/datastructures/utils/quick-select.ts | theAlgorithmist/AMYR | db4141d7e545b94a5c98fc5430a065e2ba229e75 | [
"Apache-2.0"
] | null | null | null | libs/amyr-ts-lib/src/lib/libs/tsmt/datastructures/utils/quick-select.ts | theAlgorithmist/AMYR | db4141d7e545b94a5c98fc5430a065e2ba229e75 | [
"Apache-2.0"
] | null | null | null | /**
* Copyright 2021 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.
*/
/**
* Typescript implementation of the Javascript quick-select, https://www.npmjs.com/package/quickselect
*
* @author Jim Armstrong
*
* @version 1.0
*/
export function quickSelect<T>(
arr: Array<T>,
k: number,
left: number,
right: number,
compare: (a: T, b: T) => number): void
{
while (right > left)
{
if (right - left > 600)
{
const n: number = right - left + 1;
const m: number = k - left + 1;
const z: number = Math.log(n);
const s: number = 0.5 * Math.exp(2 * z / 3);
const sd: number = 0.5 * Math.sqrt(z * s * (n - s) / n) * (m - n / 2 < 0 ? -1 : 1);
const newLeft: number = Math.max(left, Math.floor(k - m * s / n + sd));
const newRight: number = Math.min(right, Math.floor(k + (n - m) * s / n + sd));
quickSelect(arr, k, newLeft, newRight, compare);
}
const t: T = arr[k];
let i: number = left;
let j: number = right;
swap(arr, left, k);
if (compare(arr[right], t) > 0) {
swap(arr, left, right);
}
while (i < j)
{
swap(arr, i, j);
i++;
j--;
while (compare(arr[i], t) < 0) {
i++;
}
while (compare(arr[j], t) > 0) {
j--;
}
}
if (compare(arr[left], t) === 0)
{
swap(arr, left, j);
}
else
{
j++;
swap(arr, j, right);
}
if (j <= k) {
left = j + 1;
}
if (k <= j) {
right = j - 1;
}
}
}
function swap<T>(arr: Array<T>, i: number, j: number): void
{
const tmp: T = arr[i];
arr[i] = arr[j];
arr[j] = tmp;
} | 22.77551 | 102 | 0.541219 | 62 | 2 | 0 | 8 | 11 | 0 | 2 | 0 | 17 | 0 | 0 | 25.5 | 734 | 0.013624 | 0.014986 | 0 | 0 | 0 | 0 | 0.809524 | 0.250434 | /**
* Copyright 2021 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.
*/
/**
* Typescript implementation of the Javascript quick-select, https://www.npmjs.com/package/quickselect
*
* @author Jim Armstrong
*
* @version 1.0
*/
export /* Example usages of 'quickSelect' are shown below:
quickSelect(arr, k, newLeft, newRight, compare);
*/
function quickSelect<T>(
arr,
k,
left,
right,
compare)
{
while (right > left)
{
if (right - left > 600)
{
const n = right - left + 1;
const m = k - left + 1;
const z = Math.log(n);
const s = 0.5 * Math.exp(2 * z / 3);
const sd = 0.5 * Math.sqrt(z * s * (n - s) / n) * (m - n / 2 < 0 ? -1 : 1);
const newLeft = Math.max(left, Math.floor(k - m * s / n + sd));
const newRight = Math.min(right, Math.floor(k + (n - m) * s / n + sd));
quickSelect(arr, k, newLeft, newRight, compare);
}
const t = arr[k];
let i = left;
let j = right;
swap(arr, left, k);
if (compare(arr[right], t) > 0) {
swap(arr, left, right);
}
while (i < j)
{
swap(arr, i, j);
i++;
j--;
while (compare(arr[i], t) < 0) {
i++;
}
while (compare(arr[j], t) > 0) {
j--;
}
}
if (compare(arr[left], t) === 0)
{
swap(arr, left, j);
}
else
{
j++;
swap(arr, j, right);
}
if (j <= k) {
left = j + 1;
}
if (k <= j) {
right = j - 1;
}
}
}
/* Example usages of 'swap' are shown below:
swap(arr, left, k);
swap(arr, left, right);
swap(arr, i, j);
swap(arr, left, j);
swap(arr, j, right);
*/
function swap<T>(arr, i, j)
{
const tmp = arr[i];
arr[i] = arr[j];
arr[j] = tmp;
} |
ddbea5a54be6f748bed3a3467b1bd3b6c59b9f87 | 2,479 | ts | TypeScript | src/BaseRandom.ts | merakigenart/meraki-js-sdk | 975536ee5b0fa997c7222d68e9574ac7acf08fdd | [
"MIT"
] | 3 | 2022-01-20T23:02:12.000Z | 2022-02-05T10:27:55.000Z | src/BaseRandom.ts | merakigenart/meraki-js-sdk | 975536ee5b0fa997c7222d68e9574ac7acf08fdd | [
"MIT"
] | 8 | 2022-01-17T19:18:03.000Z | 2022-03-30T19:29:21.000Z | src/BaseRandom.ts | merakigenart/meraki-js-sdk | 975536ee5b0fa997c7222d68e9574ac7acf08fdd | [
"MIT"
] | null | null | null | export class BaseRandom {
public useA = false;
public prngA: () => number;
public prngB: () => number;
constructor(public tokenData = { tokenHash: '', tokenId: '' }) {
const sfc32 = function (uint128Hex) {
let a = parseInt(uint128Hex.substr(0, 8), 16);
let b = parseInt(uint128Hex.substr(8, 8), 16);
let c = parseInt(uint128Hex.substr(16, 8), 16);
let d = parseInt(uint128Hex.substr(24, 8), 16);
return function () {
a |= 0;
b |= 0;
c |= 0;
d |= 0;
const t = (((a + b) | 0) + d) | 0;
d = (d + 1) | 0;
a = b ^ (b >>> 9);
b = (c + (c << 3)) | 0;
c = (c << 21) | (c >>> 11);
c = (c + t) | 0;
return (t >>> 0) / 4294967296;
};
};
if (typeof tokenData.tokenHash !== 'string') {
// @ts-ignore
tokenData.tokenHash = `0x${tokenData.tokenHash.toString(16)}`;
}
// seed prngA with first half of tokenData.hash
// @ts-ignore
this.prngA = new sfc32(tokenData.tokenHash.substring(2, 32));
// seed prngB with second half of tokenData.hash
// @ts-ignore
this.prngB = new sfc32(tokenData.tokenHash.substring(34, 32));
for (let i = 0; i < 1e6; i += 2) {
this.prngA();
this.prngB();
}
}
// random number between 0 (inclusive) and 1 (exclusive)
decimal() {
this.useA = !this.useA;
return this.useA ? this.prngA() : this.prngB();
}
// random number between a (inclusive) and b (exclusive)
number(a: number, b: number | undefined = undefined) {
if (b === undefined) {
b = a;
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: number, b: number | undefined = undefined) {
if (b === undefined) {
b = a;
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)];
}
}
| 30.604938 | 74 | 0.474385 | 59 | 8 | 0 | 8 | 7 | 3 | 3 | 0 | 6 | 1 | 1 | 8.75 | 759 | 0.02108 | 0.009223 | 0.003953 | 0.001318 | 0.001318 | 0 | 0.230769 | 0.2519 | export class BaseRandom {
public useA = false;
public prngA;
public prngB;
constructor(public tokenData = { tokenHash: '', tokenId: '' }) {
/* Example usages of 'sfc32' are shown below:
// seed prngA with first half of tokenData.hash
// @ts-ignore
this.prngA = new sfc32(tokenData.tokenHash.substring(2, 32));
// seed prngB with second half of tokenData.hash
// @ts-ignore
this.prngB = new sfc32(tokenData.tokenHash.substring(34, 32));
*/
const sfc32 = function (uint128Hex) {
let a = parseInt(uint128Hex.substr(0, 8), 16);
let b = parseInt(uint128Hex.substr(8, 8), 16);
let c = parseInt(uint128Hex.substr(16, 8), 16);
let d = parseInt(uint128Hex.substr(24, 8), 16);
return function () {
a |= 0;
b |= 0;
c |= 0;
d |= 0;
const t = (((a + b) | 0) + d) | 0;
d = (d + 1) | 0;
a = b ^ (b >>> 9);
b = (c + (c << 3)) | 0;
c = (c << 21) | (c >>> 11);
c = (c + t) | 0;
return (t >>> 0) / 4294967296;
};
};
if (typeof tokenData.tokenHash !== 'string') {
// @ts-ignore
tokenData.tokenHash = `0x${tokenData.tokenHash.toString(16)}`;
}
// seed prngA with first half of tokenData.hash
// @ts-ignore
this.prngA = new sfc32(tokenData.tokenHash.substring(2, 32));
// seed prngB with second half of tokenData.hash
// @ts-ignore
this.prngB = new sfc32(tokenData.tokenHash.substring(34, 32));
for (let i = 0; i < 1e6; i += 2) {
this.prngA();
this.prngB();
}
}
// random number between 0 (inclusive) and 1 (exclusive)
decimal() {
this.useA = !this.useA;
return this.useA ? this.prngA() : this.prngB();
}
// random number between a (inclusive) and b (exclusive)
number(a, b = undefined) {
if (b === undefined) {
b = a;
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, b = undefined) {
if (b === undefined) {
b = a;
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)];
}
}
|
ddd0784f0397f8a4cd20df38a604abe499bfbc5d | 1,389 | ts | TypeScript | lambda/src/lib.ts | BigOrangeLab/jupiterone-wordgame | 4b5000f613d567d657f938166505e937449e4ffe | [
"MIT"
] | 2 | 2022-02-10T23:45:26.000Z | 2022-02-14T20:24:42.000Z | lambda/src/lib.ts | BigOrangeLab/jupiterone-wordgame | 4b5000f613d567d657f938166505e937449e4ffe | [
"MIT"
] | null | null | null | lambda/src/lib.ts | BigOrangeLab/jupiterone-wordgame | 4b5000f613d567d657f938166505e937449e4ffe | [
"MIT"
] | 2 | 2022-02-14T20:24:47.000Z | 2022-02-21T19:25:09.000Z | export type CharStatus = 'absent' | 'present' | 'correct'
export type CharValue =
| 'Q'
| 'W'
| 'E'
| 'R'
| 'T'
| 'Y'
| 'U'
| 'I'
| 'O'
| 'P'
| 'A'
| 'S'
| 'D'
| 'F'
| 'G'
| 'H'
| 'J'
| 'K'
| 'L'
| 'Z'
| 'X'
| 'C'
| 'V'
| 'B'
| 'N'
| 'M'
export const getGuessStatuses = (guess: string ,solution: string): CharStatus[] => {
const splitSolution = solution.toUpperCase().split('')
const splitGuess = guess.toUpperCase().split('')
const solutionCharsTaken = splitSolution.map((_) => false)
const statuses: CharStatus[] = Array.from(Array(guess.length))
// handle all correct cases first
splitGuess.forEach((letter, i) => {
if (letter === splitSolution[i]) {
statuses[i] = 'correct'
solutionCharsTaken[i] = true
return
}
})
splitGuess.forEach((letter, i) => {
if (statuses[i]) return
if (!splitSolution.includes(letter)) {
// handles the absent case
statuses[i] = 'absent'
return
}
// now we are left with "present"s
const indexOfPresentChar = splitSolution.findIndex(
(x, index) => x === letter && !solutionCharsTaken[index]
)
if (indexOfPresentChar > -1) {
statuses[i] = 'present'
solutionCharsTaken[indexOfPresentChar] = true
return
} else {
statuses[i] = 'absent'
return
}
})
return statuses
} | 19.291667 | 84 | 0.556515 | 60 | 5 | 0 | 9 | 6 | 0 | 0 | 0 | 2 | 2 | 0 | 10.6 | 432 | 0.032407 | 0.013889 | 0 | 0.00463 | 0 | 0 | 0.1 | 0.298619 | export type CharStatus = 'absent' | 'present' | 'correct'
export type CharValue =
| 'Q'
| 'W'
| 'E'
| 'R'
| 'T'
| 'Y'
| 'U'
| 'I'
| 'O'
| 'P'
| 'A'
| 'S'
| 'D'
| 'F'
| 'G'
| 'H'
| 'J'
| 'K'
| 'L'
| 'Z'
| 'X'
| 'C'
| 'V'
| 'B'
| 'N'
| 'M'
export const getGuessStatuses = (guess ,solution) => {
const splitSolution = solution.toUpperCase().split('')
const splitGuess = guess.toUpperCase().split('')
const solutionCharsTaken = splitSolution.map((_) => false)
const statuses = Array.from(Array(guess.length))
// handle all correct cases first
splitGuess.forEach((letter, i) => {
if (letter === splitSolution[i]) {
statuses[i] = 'correct'
solutionCharsTaken[i] = true
return
}
})
splitGuess.forEach((letter, i) => {
if (statuses[i]) return
if (!splitSolution.includes(letter)) {
// handles the absent case
statuses[i] = 'absent'
return
}
// now we are left with "present"s
const indexOfPresentChar = splitSolution.findIndex(
(x, index) => x === letter && !solutionCharsTaken[index]
)
if (indexOfPresentChar > -1) {
statuses[i] = 'present'
solutionCharsTaken[indexOfPresentChar] = true
return
} else {
statuses[i] = 'absent'
return
}
})
return statuses
} |
ddfd88becf0253fa2565b1eae70425abffa60c15 | 1,729 | ts | TypeScript | src/app/interfaces/user-options.ts | abelsco/sistemaExplocaoApp | e10a89a3f0e8257cf5dc68bf90264710b4dee11c | [
"Apache-2.0"
] | null | null | null | src/app/interfaces/user-options.ts | abelsco/sistemaExplocaoApp | e10a89a3f0e8257cf5dc68bf90264710b4dee11c | [
"Apache-2.0"
] | 1 | 2022-03-02T06:21:55.000Z | 2022-03-02T06:21:55.000Z | src/app/interfaces/user-options.ts | abelsco/sistemaExplosaoApp | e10a89a3f0e8257cf5dc68bf90264710b4dee11c | [
"Apache-2.0"
] | null | null | null | export interface Cliente {
codCli: number;
usuario: string;
senha: string;
}
export function construtorCliente() {
let cliente = {
codCli: 0,
usuario: '',
senha: '',
};
return cliente;
}
export interface Silo {
codSilo: number;
codCli: number;
codSerie: string;
nomeSilo: string;
tipoGrao: string;
}
export function construtorSilo() {
let silo: Silo = {
codSilo: 0,
codCli: 0,
codSerie: '',
nomeSilo: 'Você não está logado',
tipoGrao: 'Nenhum',
};
return silo;
}
export interface Leitura {
codLeitura: number;
codSilo: number;
dataLeitura: Date;
temperatura: number;
situTemperatura: number;
umidade: number;
situUmidade: number;
pressao: number;
situPressao: number;
concePo: number;
situConcePo: number;
conceOxi: number;
situConceOxi: number;
conceGas: number;
situConceGas: number;
situaSilo: number;
}
export function construtorLeitura() {
let leitura: Leitura = {
codLeitura: 0,
codSilo: 0,
dataLeitura: null,
temperatura: 0,
situTemperatura: 0,
umidade: 0,
situUmidade: 0,
pressao: 0,
situPressao: 0,
concePo: 0,
situConcePo: 0,
conceOxi: 0,
situConceOxi: 0,
conceGas: 0,
situConceGas: 0,
situaSilo: 0,
};
return leitura;
}
// export interface Relatorio {
// label: number;
// temperatura: number;
// umidade: number;
// pressao: number;
// concePo: number;
// conceOxi: number;
// conceGas: number;
// }
/* -Cliente-
codCli
usuario
nomeSilo
endSilo
tipoGrao
senha
1-1
-Silo-
codSilo
nomeSilo fore
data
temperatura
umidade
pressao
concePo
conceGas
conceOxi
situaSilo
select * from Cliente where usuario = user and senha = senha;
*/
| 15.300885 | 61 | 0.657606 | 69 | 3 | 0 | 0 | 3 | 24 | 0 | 0 | 23 | 3 | 0 | 11 | 648 | 0.00463 | 0.00463 | 0.037037 | 0.00463 | 0 | 0 | 0.766667 | 0.202479 | export interface Cliente {
codCli;
usuario;
senha;
}
export function construtorCliente() {
let cliente = {
codCli: 0,
usuario: '',
senha: '',
};
return cliente;
}
export interface Silo {
codSilo;
codCli;
codSerie;
nomeSilo;
tipoGrao;
}
export function construtorSilo() {
let silo = {
codSilo: 0,
codCli: 0,
codSerie: '',
nomeSilo: 'Você não está logado',
tipoGrao: 'Nenhum',
};
return silo;
}
export interface Leitura {
codLeitura;
codSilo;
dataLeitura;
temperatura;
situTemperatura;
umidade;
situUmidade;
pressao;
situPressao;
concePo;
situConcePo;
conceOxi;
situConceOxi;
conceGas;
situConceGas;
situaSilo;
}
export function construtorLeitura() {
let leitura = {
codLeitura: 0,
codSilo: 0,
dataLeitura: null,
temperatura: 0,
situTemperatura: 0,
umidade: 0,
situUmidade: 0,
pressao: 0,
situPressao: 0,
concePo: 0,
situConcePo: 0,
conceOxi: 0,
situConceOxi: 0,
conceGas: 0,
situConceGas: 0,
situaSilo: 0,
};
return leitura;
}
// export interface Relatorio {
// label: number;
// temperatura: number;
// umidade: number;
// pressao: number;
// concePo: number;
// conceOxi: number;
// conceGas: number;
// }
/* -Cliente-
codCli
usuario
nomeSilo
endSilo
tipoGrao
senha
1-1
-Silo-
codSilo
nomeSilo fore
data
temperatura
umidade
pressao
concePo
conceGas
conceOxi
situaSilo
select * from Cliente where usuario = user and senha = senha;
*/
|
da0ef1973818334ec9af63eb9d4d8f9b49d3597e | 1,941 | ts | TypeScript | src/Hooks/Chat/ClientReducer.ts | callmenikk/JetChat | 6f5ba02f6d112ed11e48f08c1a30a1a40a42cf6d | [
"CC0-1.0"
] | 7 | 2022-02-22T06:58:56.000Z | 2022-03-14T11:40:10.000Z | src/Hooks/Chat/ClientReducer.ts | callmenikk/JetChat | 6f5ba02f6d112ed11e48f08c1a30a1a40a42cf6d | [
"CC0-1.0"
] | null | null | null | src/Hooks/Chat/ClientReducer.ts | callmenikk/JetChat | 6f5ba02f6d112ed11e48f08c1a30a1a40a42cf6d | [
"CC0-1.0"
] | null | null | null | export type State = {
username: string,
profile_src: string,
createdAt: string,
client_id: string
message: string,
message_id: string,
reply?: {
reply_username: string,
reply_picture: string,
reply_message: string,
reply_message_owner_id: string
}
}
type Action = {
type: "SET_USER" | "MESSAGE_INPUT" | "CLEAR_MESSAGE_FIELD" | "SET_MESSAGE_ID" | "SET_REPLY_MESSAGE" | "CLEAR_REPLY",
payload: {
username: string,
profile_src: string,
createdAt: string,
client_id: string,
message: string,
message_id: string,
reply_username?: string,
reply_picture?: string,
reply_message?: string,
reply_message_id?: string
}
}
const clientState: State = {
username: '',
profile_src: '',
createdAt: '',
client_id: '',
message: '',
message_id: ''
}
export const clientReducer = (state: State = clientState, action: Action): State => {
switch(action.type){
case "SET_USER": {
const {username, message_id, profile_src, createdAt, client_id} = action.payload
return {
...state,
username: username,
profile_src: profile_src,
createdAt: createdAt,
client_id: client_id,
message_id: message_id
}
}case "MESSAGE_INPUT": {
const {message} = action.payload
return {
...state,
message: message
}
}
case "CLEAR_MESSAGE_FIELD": {
return {
...state,
message: ""
}
}
case "SET_MESSAGE_ID": {
return {
...state,
message_id: action.payload.message_id
}
}
case "SET_REPLY_MESSAGE": {
const {reply_username, reply_picture, reply_message, reply_message_id} = action.payload
return {
...state,
reply: {
reply_username: reply_username as string,
reply_picture: reply_picture as string,
reply_message: reply_message as string,
reply_message_owner_id: reply_message_id as string
}
}
}
case "CLEAR_REPLY": {
return {
...state,
reply: undefined
}
}
default: return state
}
} | 20.648936 | 117 | 0.666151 | 89 | 1 | 0 | 2 | 5 | 9 | 0 | 0 | 24 | 2 | 4 | 50 | 653 | 0.004594 | 0.007657 | 0.013783 | 0.003063 | 0.006126 | 0 | 1.411765 | 0.208194 | export type State = {
username,
profile_src,
createdAt,
client_id
message,
message_id,
reply?
}
type Action = {
type,
payload
}
const clientState = {
username: '',
profile_src: '',
createdAt: '',
client_id: '',
message: '',
message_id: ''
}
export const clientReducer = (state = clientState, action) => {
switch(action.type){
case "SET_USER": {
const {username, message_id, profile_src, createdAt, client_id} = action.payload
return {
...state,
username: username,
profile_src: profile_src,
createdAt: createdAt,
client_id: client_id,
message_id: message_id
}
}case "MESSAGE_INPUT": {
const {message} = action.payload
return {
...state,
message: message
}
}
case "CLEAR_MESSAGE_FIELD": {
return {
...state,
message: ""
}
}
case "SET_MESSAGE_ID": {
return {
...state,
message_id: action.payload.message_id
}
}
case "SET_REPLY_MESSAGE": {
const {reply_username, reply_picture, reply_message, reply_message_id} = action.payload
return {
...state,
reply: {
reply_username: reply_username as string,
reply_picture: reply_picture as string,
reply_message: reply_message as string,
reply_message_owner_id: reply_message_id as string
}
}
}
case "CLEAR_REPLY": {
return {
...state,
reply: undefined
}
}
default: return state
}
} |
da11b50cb1760b103fb38d5c342f7a8333b792fc | 1,540 | ts | TypeScript | src/devtool/utils/store_util.ts | Raykid/Cocoski | 304b505668d2e41650b625c30c0ac78e19f63757 | [
"MIT"
] | 5 | 2022-03-06T07:26:48.000Z | 2022-03-25T18:08:18.000Z | src/devtool/utils/store_util.ts | Raykid/Cocoski | 304b505668d2e41650b625c30c0ac78e19f63757 | [
"MIT"
] | null | null | null | src/devtool/utils/store_util.ts | Raykid/Cocoski | 304b505668d2e41650b625c30c0ac78e19f63757 | [
"MIT"
] | null | null | null | export function wrapProxy<T>(root: any): {
proxy: T;
update: (root: any) => void;
effect: () => void;
} {
const cache: any = {};
const subWrapperMap: Map<any, ReturnType<typeof wrapProxy>> = new Map();
return {
proxy: new Proxy(
{ ...root },
{
get: (_, key: string) => {
const temp = root[key];
if (temp && typeof temp === "object") {
// 移除缓存并释放副作用
const cached = cache[key];
if (cached && subWrapperMap.has(cached)) {
subWrapperMap.get(cached)!.effect();
subWrapperMap.delete(cached);
}
if (Object.getOwnPropertyDescriptor(root, key)) {
const wrapper = wrapProxy(temp);
subWrapperMap.set(wrapper.proxy, wrapper);
return (cache[key] = wrapper.proxy);
} else {
return temp;
}
} else {
return temp;
}
},
set: (_, key: string, value) => {
root[key] = value;
return true;
},
deleteProperty: (_, key) => {
delete root[key];
delete cache[key];
return true;
},
}
) as T,
update: (_root) => {
root = _root;
subWrapperMap.forEach((wrapper) => wrapper.update(root));
},
effect: () => {
for (const key of Object.keys(cache)) {
delete cache[key];
}
subWrapperMap.forEach((wrapper) => wrapper.effect());
subWrapperMap.clear();
},
};
}
| 27.5 | 74 | 0.47987 | 54 | 8 | 0 | 11 | 5 | 0 | 1 | 4 | 4 | 0 | 2 | 9.875 | 384 | 0.049479 | 0.013021 | 0 | 0 | 0.005208 | 0.166667 | 0.166667 | 0.325005 | export /* Example usages of 'wrapProxy' are shown below:
wrapProxy(temp);
*/
function wrapProxy<T>(root) {
const cache = {};
const subWrapperMap = new Map();
return {
proxy: new Proxy(
{ ...root },
{
get: (_, key) => {
const temp = root[key];
if (temp && typeof temp === "object") {
// 移除缓存并释放副作用
const cached = cache[key];
if (cached && subWrapperMap.has(cached)) {
subWrapperMap.get(cached)!.effect();
subWrapperMap.delete(cached);
}
if (Object.getOwnPropertyDescriptor(root, key)) {
const wrapper = wrapProxy(temp);
subWrapperMap.set(wrapper.proxy, wrapper);
return (cache[key] = wrapper.proxy);
} else {
return temp;
}
} else {
return temp;
}
},
set: (_, key, value) => {
root[key] = value;
return true;
},
deleteProperty: (_, key) => {
delete root[key];
delete cache[key];
return true;
},
}
) as T,
update: (_root) => {
root = _root;
subWrapperMap.forEach((wrapper) => wrapper.update(root));
},
effect: () => {
for (const key of Object.keys(cache)) {
delete cache[key];
}
subWrapperMap.forEach((wrapper) => wrapper.effect());
subWrapperMap.clear();
},
};
}
|
da1794125f7ca6e6fc2b840a89cd3c59133984f3 | 2,312 | ts | TypeScript | src/app/models/platform-api/requests/tokens/tokens-filter.ts | Opdex/opdex-v1-ui | 2ece9c2405d6e6b0b1aec342e381d5aad6a2a1e7 | [
"MIT"
] | 2 | 2022-01-06T23:47:44.000Z | 2022-01-06T23:49:37.000Z | src/app/models/platform-api/requests/tokens/tokens-filter.ts | Opdex/opdex-v1-ui | 2ece9c2405d6e6b0b1aec342e381d5aad6a2a1e7 | [
"MIT"
] | null | null | null | src/app/models/platform-api/requests/tokens/tokens-filter.ts | Opdex/opdex-v1-ui | 2ece9c2405d6e6b0b1aec342e381d5aad6a2a1e7 | [
"MIT"
] | null | null | null | export enum TokenOrderByTypes {
Name = 'Name',
Symbol = 'Symbol',
Default = 'Default',
PriceUsd = 'PriceUsd',
DailyPriceChangePercent = 'DailyPriceChangePercent'
}
export enum TokenAttributes {
Provisional = 'Provisional',
NonProvisional = 'NonProvisional',
Staking = 'Staking'
}
export interface ITokensRequest {
tokens?: string[];
tokenAttributes?: TokenAttributes[];
includeZeroLiquidity?: boolean;
orderBy?: TokenOrderByTypes;
limit?: number;
direction?: string;
cursor?: string;
keyword?: string;
}
export class TokensFilter implements ITokensRequest {
keyword?: string;
tokens?: string[];
tokenAttributes?: TokenAttributes[];
includeZeroLiquidity?: boolean;
orderBy?: TokenOrderByTypes;
limit?: number;
direction?: string;
cursor?: string;
constructor(request?: ITokensRequest) {
if (request === null || request === undefined) {
this.limit = 5;
this.direction = 'DESC';
return;
};
this.keyword = request.keyword;
this.tokens = request.tokens;
this.tokenAttributes = request.tokenAttributes;
this.orderBy = request.orderBy;
this.includeZeroLiquidity = request.includeZeroLiquidity;
this.cursor = request.cursor;
this.limit = request.limit;
this.direction = request.direction;
}
public buildQueryString(): string {
if (this.cursor?.length) return `?cursor=${this.cursor}`;
let query = '';
if (this.tokens?.length > 0) {
this.tokens.forEach(contract => query = this.addToQuery(query, 'tokens', contract));
}
if (this.tokenAttributes?.length > 0) {
this.tokenAttributes.forEach(attribute => query = this.addToQuery(query, 'tokenAttributes', attribute));
}
query = this.addToQuery(query, 'keyword', this.keyword);
query = this.addToQuery(query, 'includeZeroLiquidity', this.includeZeroLiquidity?.toString());
query = this.addToQuery(query, 'orderBy', this.orderBy);
query = this.addToQuery(query, 'limit', this.limit);
query = this.addToQuery(query, 'direction', this.direction);
return query
}
private addToQuery(query: string, key: string, value: string | number): string {
if (!!value === false) return query;
const leading = query.length > 0 ? '&' : '?';
return `${query}${leading}${key}=${value}`;
}
}
| 27.855422 | 110 | 0.676903 | 68 | 5 | 0 | 6 | 2 | 16 | 1 | 0 | 18 | 2 | 0 | 6.4 | 590 | 0.018644 | 0.00339 | 0.027119 | 0.00339 | 0 | 0 | 0.62069 | 0.229655 | export enum TokenOrderByTypes {
Name = 'Name',
Symbol = 'Symbol',
Default = 'Default',
PriceUsd = 'PriceUsd',
DailyPriceChangePercent = 'DailyPriceChangePercent'
}
export enum TokenAttributes {
Provisional = 'Provisional',
NonProvisional = 'NonProvisional',
Staking = 'Staking'
}
export interface ITokensRequest {
tokens?;
tokenAttributes?;
includeZeroLiquidity?;
orderBy?;
limit?;
direction?;
cursor?;
keyword?;
}
export class TokensFilter implements ITokensRequest {
keyword?;
tokens?;
tokenAttributes?;
includeZeroLiquidity?;
orderBy?;
limit?;
direction?;
cursor?;
constructor(request?) {
if (request === null || request === undefined) {
this.limit = 5;
this.direction = 'DESC';
return;
};
this.keyword = request.keyword;
this.tokens = request.tokens;
this.tokenAttributes = request.tokenAttributes;
this.orderBy = request.orderBy;
this.includeZeroLiquidity = request.includeZeroLiquidity;
this.cursor = request.cursor;
this.limit = request.limit;
this.direction = request.direction;
}
public buildQueryString() {
if (this.cursor?.length) return `?cursor=${this.cursor}`;
let query = '';
if (this.tokens?.length > 0) {
this.tokens.forEach(contract => query = this.addToQuery(query, 'tokens', contract));
}
if (this.tokenAttributes?.length > 0) {
this.tokenAttributes.forEach(attribute => query = this.addToQuery(query, 'tokenAttributes', attribute));
}
query = this.addToQuery(query, 'keyword', this.keyword);
query = this.addToQuery(query, 'includeZeroLiquidity', this.includeZeroLiquidity?.toString());
query = this.addToQuery(query, 'orderBy', this.orderBy);
query = this.addToQuery(query, 'limit', this.limit);
query = this.addToQuery(query, 'direction', this.direction);
return query
}
private addToQuery(query, key, value) {
if (!!value === false) return query;
const leading = query.length > 0 ? '&' : '?';
return `${query}${leading}${key}=${value}`;
}
}
|
da8d8a92eaaca1ae71822f48213378b05e72604f | 2,012 | ts | TypeScript | server/src/utils/Base32Encode.ts | andrinmeier/romme | 8993c8301db480e83aea3676d23a9e81a83405dc | [
"MIT"
] | null | null | null | server/src/utils/Base32Encode.ts | andrinmeier/romme | 8993c8301db480e83aea3676d23a9e81a83405dc | [
"MIT"
] | 16 | 2022-03-03T21:54:27.000Z | 2022-03-27T13:42:59.000Z | server/src/utils/Base32Encode.ts | andrinmeier/romme | 8993c8301db480e83aea3676d23a9e81a83405dc | [
"MIT"
] | 1 | 2022-03-06T13:23:27.000Z | 2022-03-06T13:23:27.000Z | /*
All credits go to https://github.com/LinusU/base32-encode.
Copied over because the library doesn't support CJS modules.
*/
const RFC4648 = "ABCDEFGHIJKLMNOPQRSTUVWXYZ234567";
const RFC4648_HEX = "0123456789ABCDEFGHIJKLMNOPQRSTUV";
const CROCKFORD = "0123456789ABCDEFGHJKMNPQRSTVWXYZ";
const toDataView = (data) => {
if (
data instanceof Int8Array ||
data instanceof Uint8Array ||
data instanceof Uint8ClampedArray
) {
return new DataView(data.buffer, data.byteOffset, data.byteLength);
}
if (data instanceof ArrayBuffer) {
return new DataView(data);
}
throw new TypeError(
"Expected `data` to be an ArrayBuffer, Buffer, Int8Array, Uint8Array or Uint8ClampedArray"
);
};
export default function base32Encode(data, variant, options?) {
options = options || {};
let alphabet, defaultPadding;
switch (variant) {
case "RFC3548":
case "RFC4648":
alphabet = RFC4648;
defaultPadding = true;
break;
case "RFC4648-HEX":
alphabet = RFC4648_HEX;
defaultPadding = true;
break;
case "Crockford":
alphabet = CROCKFORD;
defaultPadding = false;
break;
default:
throw new Error("Unknown base32 variant: " + variant);
}
const padding =
options.padding !== undefined ? options.padding : defaultPadding;
const view = toDataView(data);
let bits = 0;
let value = 0;
let output = "";
for (let i = 0; i < view.byteLength; i++) {
value = (value << 8) | view.getUint8(i);
bits += 8;
while (bits >= 5) {
output += alphabet[(value >>> (bits - 5)) & 31];
bits -= 5;
}
}
if (bits > 0) {
output += alphabet[(value << (5 - bits)) & 31];
}
if (padding) {
while (output.length % 8 !== 0) {
output += "=";
}
}
return output;
}
| 26.12987 | 98 | 0.562127 | 62 | 2 | 0 | 4 | 12 | 0 | 1 | 0 | 0 | 0 | 4 | 27.5 | 558 | 0.010753 | 0.021505 | 0 | 0 | 0.007168 | 0 | 0 | 0.264728 | /*
All credits go to https://github.com/LinusU/base32-encode.
Copied over because the library doesn't support CJS modules.
*/
const RFC4648 = "ABCDEFGHIJKLMNOPQRSTUVWXYZ234567";
const RFC4648_HEX = "0123456789ABCDEFGHIJKLMNOPQRSTUV";
const CROCKFORD = "0123456789ABCDEFGHJKMNPQRSTVWXYZ";
/* Example usages of 'toDataView' are shown below:
toDataView(data);
*/
const toDataView = (data) => {
if (
data instanceof Int8Array ||
data instanceof Uint8Array ||
data instanceof Uint8ClampedArray
) {
return new DataView(data.buffer, data.byteOffset, data.byteLength);
}
if (data instanceof ArrayBuffer) {
return new DataView(data);
}
throw new TypeError(
"Expected `data` to be an ArrayBuffer, Buffer, Int8Array, Uint8Array or Uint8ClampedArray"
);
};
export default function base32Encode(data, variant, options?) {
options = options || {};
let alphabet, defaultPadding;
switch (variant) {
case "RFC3548":
case "RFC4648":
alphabet = RFC4648;
defaultPadding = true;
break;
case "RFC4648-HEX":
alphabet = RFC4648_HEX;
defaultPadding = true;
break;
case "Crockford":
alphabet = CROCKFORD;
defaultPadding = false;
break;
default:
throw new Error("Unknown base32 variant: " + variant);
}
const padding =
options.padding !== undefined ? options.padding : defaultPadding;
const view = toDataView(data);
let bits = 0;
let value = 0;
let output = "";
for (let i = 0; i < view.byteLength; i++) {
value = (value << 8) | view.getUint8(i);
bits += 8;
while (bits >= 5) {
output += alphabet[(value >>> (bits - 5)) & 31];
bits -= 5;
}
}
if (bits > 0) {
output += alphabet[(value << (5 - bits)) & 31];
}
if (padding) {
while (output.length % 8 !== 0) {
output += "=";
}
}
return output;
}
|
daa41a516ce86058cf8228ecaa71a3114f28be2f | 7,142 | ts | TypeScript | src/utils/theme/index.ts | toimc-team/vue-toimc-admin | 500646049c801fc93d23a171f99ee8bb2a770974 | [
"MIT"
] | 3 | 2022-03-18T13:17:23.000Z | 2022-03-30T07:21:49.000Z | src/utils/theme/index.ts | toimc-team/vue-toimc-admin | 500646049c801fc93d23a171f99ee8bb2a770974 | [
"MIT"
] | 6 | 2022-03-21T02:07:09.000Z | 2022-03-31T16:17:05.000Z | src/utils/theme/index.ts | toimc-team/vue-toimc-admin | 500646049c801fc93d23a171f99ee8bb2a770974 | [
"MIT"
] | 12 | 2022-03-18T13:17:30.000Z | 2022-03-31T06:51:00.000Z | interface MixColorRes {
light: Object,
dark: Object
}
/**
* color mix
* @param color1
* @param color2
* @param weight
* @returns
*/
export function colorMix (color1: string, color2: string, weight: number) {
weight = Math.max(Math.min(Number(weight), 1), 0)
const r1 = parseInt(color1.substring(1, 3), 16)
const g1 = parseInt(color1.substring(3, 5), 16)
const b1 = parseInt(color1.substring(5, 7), 16)
const r2 = parseInt(color2.substring(1, 3), 16)
const g2 = parseInt(color2.substring(3, 5), 16)
const b2 = parseInt(color2.substring(5, 7), 16)
const r = Math.round(r1 * (1 - weight) + r2 * weight)
const g = Math.round(g1 * (1 - weight) + g2 * weight)
const b = Math.round(b1 * (1 - weight) + b2 * weight)
const rr = ('0' + (r || 0).toString(16)).slice(-2)
const gg = ('0' + (g || 0).toString(16)).slice(-2)
const bb = ('0' + (b || 0).toString(16)).slice(-2)
return '#' + rr + gg + bb;
}
/**
* darker color
* @param {*} color
* @param {*} mode
* @returns
*/
export function getDarkerColor(color, mode='light') {
const baseColor = mode === 'light' ? '#000000' : '#ffffff'
return colorMix(color, baseColor, 0.2)
}
/**
* color level
* @param {*} color
* @param {*} weightArr step Array
* @param {*} mode
*/
export function lighterLevelColor(color: string, weightArr: Array<number>, mode='light') {
const colors:Array<string> = []
const mixColor = mode === 'light' ? '#ffffff' : '#141414'
weightArr.forEach(weight => {
colors.push(colorMix(color, mixColor, weight))
});
return colors
}
/**
* generate main colors
* @param {*} colors base颜色
* @returns
*/
export function generateMainColors(colors = {}){
const prefix = '--el-color-'
let types = {
primary: { light: '#409eff', dark: '#409eff' },
success: { light: '#67c23a', dark: '#59b259' },
warning: { light: '#e6a23c', dark: '#d6a356' },
danger: { light: '#f56c6c', dark: '#cc5e5e' },
error: { light: '#f56c6c', dark: '#cc5e5e' },
info: {light: '#909399', dark: '#606266' }
}
types = { ...types, ...colors }
const res = {} as MixColorRes
Object.keys(types).forEach(type=>{
const item = types[type]
// weight
const weightArr = [0.3, 0.5, 0.7, 0.8, 0.9]
const lightColor = lighterLevelColor(item.light, weightArr)
const darkColor = lighterLevelColor(item.dark, weightArr, 'dark')
// light-mode color
lightColor.forEach((light, index)=>{
res.light = { ...res.light, ...{ [prefix+type+'-light-'+weightArr[index]*10]: light } }
})
// dark-mode color
darkColor.forEach((dark, index)=>{
res.dark = { ...res.dark, ...{ [prefix+type+'-light-'+weightArr[index]*10]: dark } }
})
// add base color
res.light[prefix+type] = item.light
res.dark[prefix+type] = item.dark
// add darker color
res.light[prefix+type+'-dark-2'] = getDarkerColor(item.light)
res.dark[prefix+type+'-dark-2'] = getDarkerColor(item.dark, 'dark')
})
return res
}
/**
* generate text colors
*/
export function generateTextColors(){
const prefix = '--el-text-color-'
const lightColor = {
primary: '#303133',
regular: '#606266',
secondary: '#909399',
placeholder: '#a8abb2',
disabled: '#c0c4cc'
}
const res = {} as MixColorRes
const colorKeys = Object.keys(lightColor)
colorKeys.forEach(key=>{
res.light = { ...res.light, ...{ [prefix+key]: lightColor[key] } }
})
const darkWeight = [0.05, 0.15, 0.35, 0.45, 0.60]
const darkColor = lighterLevelColor('#f0f5ff', darkWeight, 'dark')
darkColor.forEach((dark, index)=>{
res.dark = { ...res.dark, ...{ [prefix+colorKeys[index]]: dark } }
})
return res
}
/**
* generate border colors
*/
export function generateBorderColors(){
const prefix = '--el-border-color'
const lightColor = {
'darker': '#cdd0d6',
'dark': '#d4d7de',
'': '#dcdfe6',
'light': '#e4e7ed',
'lighter': '#ebeef5',
'extra-light': '#f2f6fc'
}
const res = {} as MixColorRes
const colorKeys = Object.keys(lightColor)
colorKeys.forEach(key=>{
res.light = { ...res.light, ...{ [key?(prefix+'-'+key):prefix]: lightColor[key] } }
})
const darkWeight = [0.65, 0.70, 0.75, 0.80, 0.85, 0.90]
const darkColor = lighterLevelColor('#f5f8ff', darkWeight, 'dark')
darkColor.forEach((dark, index)=>{
res.dark = { ...res.dark, ...{ [colorKeys[index] ? (prefix+'-'+colorKeys[index]) : prefix]: dark } }
})
return res
}
/**
* generate fill colors
*/
export function generateFillColors(){
const prefix = '--el-fill-color'
const lightColor = {
'darker': '#e6e8eb',
'dark': '#ebedf0',
'': '#f0f2f5',
'light': '#f5f7fa',
'lighter': '#fafafa',
'extra-light': '#fafcff',
'blank': '#ffffff'
}
const res = {} as MixColorRes
const colorKeys = Object.keys(lightColor)
colorKeys.forEach(key=>{
res.light = { ...res.light, ...{ [key?(prefix+'-'+key):prefix]: lightColor[key] } }
})
const darkWeight = [0.80, 0.84, 0.88, 0.92, 0.96, 0.98, 1]
const darkColor = lighterLevelColor('#fafcff', darkWeight, 'dark')
darkColor.forEach((dark, index)=>{
res.dark = { ...res.dark, ...{ [colorKeys[index] ? (prefix+'-'+colorKeys[index]) : prefix]: dark } }
})
return res
}
/**
* generate bg colors
* @returns
*/
export function generateBgColors(){
return {
light: {
'--el-bg-color': '#ffffff',
'--el-bg-page': '#ffffff',
'--el-bg-overlay': '#ffffff'
},
dark: {
'--el-bg-color': '#141414',
'--el-bg-page': '#0a0a0a',
'--el-bg-overlay': '#1d1e1f'
}
}
}
/**
* generate mask colors
*/
export function generateMaskColors(){
return {
light: {
'--el-overlay-color': 'rgba(0, 0, 0, 0.8)',
'--el-overlay-color-light': 'rgba(0, 0, 0, 0.7)',
'--el-overlay-color-lighter': 'rgba(0, 0, 0, 0.5)',
'--el-mask-color': 'rgba(255, 255, 255, 0.9)',
'--el-mask-color-extra-light': 'rgba(255, 255, 255, 0.3)'
},
dark: {
'--el-overlay-color': 'rgba(255, 255, 255, 0.8)',
'--el-overlay-color-light': 'rgba(255, 255, 255, 0.7)',
'--el-overlay-color-lighter': 'rgba(255, 255, 255, 0.5)',
'--el-mask-color': 'rgba(0, 0, 0, 0.9)',
'--el-mask-color-extra-light': 'rgba(0, 0, 0, 0.3)'
}
}
}
/**
* generate BoxShadow Colors
* @returns
*/
export function generateBoxShadowColors() {
return {
light: {
'--el-box-shadow': '0px 12px 32px 4px rgba(0, 0, 0, 0.04),0px 8px 20px rgba(0, 0, 0, 0.08)',
'--el-box-shadow-light': '0px 0px 12px rgba(0, 0, 0, 0.12)',
'--el-box-shadow-lighter': '0px 0px 6px rgba(0, 0, 0, 0.12)',
'--el-box-shadow-dark': '0px 16px 48px 16px rgba(0, 0, 0, 0.08),0px 12px 32px rgba(0, 0, 0, 0.12),0px 8px 16px -8px rgba(0, 0, 0, 0.16)'
},
dark: {
'--el-box-shadow': '0px 12px 32px 4px rgba(0, 0, 0, 0.36),0px 8px 20px rgba(0, 0, 0, 0.72)',
'--el-box-shadow-light': '0px 0px 12px rgba(0, 0, 0, 0.72)',
'--el-box-shadow-lighter': '0px 0px 6px rgba(0, 0, 0, 0.72)',
'--el-box-shadow-dark': '0px 16px 48px 16px rgba(0, 0, 0, 0.72),0px 12px 32px #000000,0px 8px 16px -8px #000000'
}
}
}
| 30.135021 | 142 | 0.58359 | 176 | 20 | 0 | 24 | 40 | 2 | 3 | 0 | 6 | 1 | 4 | 8.75 | 2,789 | 0.015776 | 0.014342 | 0.000717 | 0.000359 | 0.001434 | 0 | 0.069767 | 0.254855 | interface MixColorRes {
light,
dark
}
/**
* color mix
* @param color1
* @param color2
* @param weight
* @returns
*/
export /* Example usages of 'colorMix' are shown below:
colorMix(color, baseColor, 0.2);
colors.push(colorMix(color, mixColor, weight));
*/
function colorMix (color1, color2, weight) {
weight = Math.max(Math.min(Number(weight), 1), 0)
const r1 = parseInt(color1.substring(1, 3), 16)
const g1 = parseInt(color1.substring(3, 5), 16)
const b1 = parseInt(color1.substring(5, 7), 16)
const r2 = parseInt(color2.substring(1, 3), 16)
const g2 = parseInt(color2.substring(3, 5), 16)
const b2 = parseInt(color2.substring(5, 7), 16)
const r = Math.round(r1 * (1 - weight) + r2 * weight)
const g = Math.round(g1 * (1 - weight) + g2 * weight)
const b = Math.round(b1 * (1 - weight) + b2 * weight)
const rr = ('0' + (r || 0).toString(16)).slice(-2)
const gg = ('0' + (g || 0).toString(16)).slice(-2)
const bb = ('0' + (b || 0).toString(16)).slice(-2)
return '#' + rr + gg + bb;
}
/**
* darker color
* @param {*} color
* @param {*} mode
* @returns
*/
export /* Example usages of 'getDarkerColor' are shown below:
// add darker color
res.light[prefix + type + '-dark-2'] = getDarkerColor(item.light);
res.dark[prefix + type + '-dark-2'] = getDarkerColor(item.dark, 'dark');
*/
function getDarkerColor(color, mode='light') {
const baseColor = mode === 'light' ? '#000000' : '#ffffff'
return colorMix(color, baseColor, 0.2)
}
/**
* color level
* @param {*} color
* @param {*} weightArr step Array
* @param {*} mode
*/
export /* Example usages of 'lighterLevelColor' are shown below:
lighterLevelColor(item.light, weightArr);
lighterLevelColor(item.dark, weightArr, 'dark');
lighterLevelColor('#f0f5ff', darkWeight, 'dark');
lighterLevelColor('#f5f8ff', darkWeight, 'dark');
lighterLevelColor('#fafcff', darkWeight, 'dark');
*/
function lighterLevelColor(color, weightArr, mode='light') {
const colors = []
const mixColor = mode === 'light' ? '#ffffff' : '#141414'
weightArr.forEach(weight => {
colors.push(colorMix(color, mixColor, weight))
});
return colors
}
/**
* generate main colors
* @param {*} colors base颜色
* @returns
*/
export function generateMainColors(colors = {}){
const prefix = '--el-color-'
let types = {
primary: { light: '#409eff', dark: '#409eff' },
success: { light: '#67c23a', dark: '#59b259' },
warning: { light: '#e6a23c', dark: '#d6a356' },
danger: { light: '#f56c6c', dark: '#cc5e5e' },
error: { light: '#f56c6c', dark: '#cc5e5e' },
info: {light: '#909399', dark: '#606266' }
}
types = { ...types, ...colors }
const res = {} as MixColorRes
Object.keys(types).forEach(type=>{
const item = types[type]
// weight
const weightArr = [0.3, 0.5, 0.7, 0.8, 0.9]
const lightColor = lighterLevelColor(item.light, weightArr)
const darkColor = lighterLevelColor(item.dark, weightArr, 'dark')
// light-mode color
lightColor.forEach((light, index)=>{
res.light = { ...res.light, ...{ [prefix+type+'-light-'+weightArr[index]*10]: light } }
})
// dark-mode color
darkColor.forEach((dark, index)=>{
res.dark = { ...res.dark, ...{ [prefix+type+'-light-'+weightArr[index]*10]: dark } }
})
// add base color
res.light[prefix+type] = item.light
res.dark[prefix+type] = item.dark
// add darker color
res.light[prefix+type+'-dark-2'] = getDarkerColor(item.light)
res.dark[prefix+type+'-dark-2'] = getDarkerColor(item.dark, 'dark')
})
return res
}
/**
* generate text colors
*/
export function generateTextColors(){
const prefix = '--el-text-color-'
const lightColor = {
primary: '#303133',
regular: '#606266',
secondary: '#909399',
placeholder: '#a8abb2',
disabled: '#c0c4cc'
}
const res = {} as MixColorRes
const colorKeys = Object.keys(lightColor)
colorKeys.forEach(key=>{
res.light = { ...res.light, ...{ [prefix+key]: lightColor[key] } }
})
const darkWeight = [0.05, 0.15, 0.35, 0.45, 0.60]
const darkColor = lighterLevelColor('#f0f5ff', darkWeight, 'dark')
darkColor.forEach((dark, index)=>{
res.dark = { ...res.dark, ...{ [prefix+colorKeys[index]]: dark } }
})
return res
}
/**
* generate border colors
*/
export function generateBorderColors(){
const prefix = '--el-border-color'
const lightColor = {
'darker': '#cdd0d6',
'dark': '#d4d7de',
'': '#dcdfe6',
'light': '#e4e7ed',
'lighter': '#ebeef5',
'extra-light': '#f2f6fc'
}
const res = {} as MixColorRes
const colorKeys = Object.keys(lightColor)
colorKeys.forEach(key=>{
res.light = { ...res.light, ...{ [key?(prefix+'-'+key):prefix]: lightColor[key] } }
})
const darkWeight = [0.65, 0.70, 0.75, 0.80, 0.85, 0.90]
const darkColor = lighterLevelColor('#f5f8ff', darkWeight, 'dark')
darkColor.forEach((dark, index)=>{
res.dark = { ...res.dark, ...{ [colorKeys[index] ? (prefix+'-'+colorKeys[index]) : prefix]: dark } }
})
return res
}
/**
* generate fill colors
*/
export function generateFillColors(){
const prefix = '--el-fill-color'
const lightColor = {
'darker': '#e6e8eb',
'dark': '#ebedf0',
'': '#f0f2f5',
'light': '#f5f7fa',
'lighter': '#fafafa',
'extra-light': '#fafcff',
'blank': '#ffffff'
}
const res = {} as MixColorRes
const colorKeys = Object.keys(lightColor)
colorKeys.forEach(key=>{
res.light = { ...res.light, ...{ [key?(prefix+'-'+key):prefix]: lightColor[key] } }
})
const darkWeight = [0.80, 0.84, 0.88, 0.92, 0.96, 0.98, 1]
const darkColor = lighterLevelColor('#fafcff', darkWeight, 'dark')
darkColor.forEach((dark, index)=>{
res.dark = { ...res.dark, ...{ [colorKeys[index] ? (prefix+'-'+colorKeys[index]) : prefix]: dark } }
})
return res
}
/**
* generate bg colors
* @returns
*/
export function generateBgColors(){
return {
light: {
'--el-bg-color': '#ffffff',
'--el-bg-page': '#ffffff',
'--el-bg-overlay': '#ffffff'
},
dark: {
'--el-bg-color': '#141414',
'--el-bg-page': '#0a0a0a',
'--el-bg-overlay': '#1d1e1f'
}
}
}
/**
* generate mask colors
*/
export function generateMaskColors(){
return {
light: {
'--el-overlay-color': 'rgba(0, 0, 0, 0.8)',
'--el-overlay-color-light': 'rgba(0, 0, 0, 0.7)',
'--el-overlay-color-lighter': 'rgba(0, 0, 0, 0.5)',
'--el-mask-color': 'rgba(255, 255, 255, 0.9)',
'--el-mask-color-extra-light': 'rgba(255, 255, 255, 0.3)'
},
dark: {
'--el-overlay-color': 'rgba(255, 255, 255, 0.8)',
'--el-overlay-color-light': 'rgba(255, 255, 255, 0.7)',
'--el-overlay-color-lighter': 'rgba(255, 255, 255, 0.5)',
'--el-mask-color': 'rgba(0, 0, 0, 0.9)',
'--el-mask-color-extra-light': 'rgba(0, 0, 0, 0.3)'
}
}
}
/**
* generate BoxShadow Colors
* @returns
*/
export function generateBoxShadowColors() {
return {
light: {
'--el-box-shadow': '0px 12px 32px 4px rgba(0, 0, 0, 0.04),0px 8px 20px rgba(0, 0, 0, 0.08)',
'--el-box-shadow-light': '0px 0px 12px rgba(0, 0, 0, 0.12)',
'--el-box-shadow-lighter': '0px 0px 6px rgba(0, 0, 0, 0.12)',
'--el-box-shadow-dark': '0px 16px 48px 16px rgba(0, 0, 0, 0.08),0px 12px 32px rgba(0, 0, 0, 0.12),0px 8px 16px -8px rgba(0, 0, 0, 0.16)'
},
dark: {
'--el-box-shadow': '0px 12px 32px 4px rgba(0, 0, 0, 0.36),0px 8px 20px rgba(0, 0, 0, 0.72)',
'--el-box-shadow-light': '0px 0px 12px rgba(0, 0, 0, 0.72)',
'--el-box-shadow-lighter': '0px 0px 6px rgba(0, 0, 0, 0.72)',
'--el-box-shadow-dark': '0px 16px 48px 16px rgba(0, 0, 0, 0.72),0px 12px 32px #000000,0px 8px 16px -8px #000000'
}
}
}
|
dac7a34c23c6505fd564304a224f764b68dd8397 | 3,426 | ts | TypeScript | inlong-dashboard/src/pages/AccessCreate/DataStream/helper.ts | xuesongxs/incubator-inlong | b482895e1130fc6b9826ca665e35998c2be61f6b | [
"Apache-2.0"
] | 3 | 2022-01-24T10:03:02.000Z | 2022-02-10T04:52:33.000Z | inlong-dashboard/src/pages/AccessCreate/DataStream/helper.ts | xuesongxs/incubator-inlong | b482895e1130fc6b9826ca665e35998c2be61f6b | [
"Apache-2.0"
] | 11 | 2022-02-09T09:13:18.000Z | 2022-03-16T12:52:15.000Z | inlong-dashboard/src/pages/AccessCreate/DataStream/helper.ts | xuesongxs/incubator-inlong | b482895e1130fc6b9826ca665e35998c2be61f6b | [
"Apache-2.0"
] | null | null | null | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you 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.
*/
// Convert form data into interface submission data format
export const valuesToData = (values, inlongGroupId) => {
const array = values.map(item => {
const {
inlongStreamId,
predefinedFields = [],
rowTypeFields = [],
dataSourceType,
dataSourcesConfig = [],
streamSink = [],
...rest
} = item;
const output = {} as any;
if (dataSourceType !== 'AUTO_PUSH') {
output.sourceInfo = dataSourcesConfig.map(k => {
return {
...k,
sourceType: dataSourceType,
inlongGroupId,
inlongStreamId,
};
});
} else {
output.sourceInfo = [
{
sourceType: dataSourceType,
sourceName: inlongStreamId,
inlongGroupId,
inlongStreamId,
},
];
}
output.sinkInfo = streamSink.reduce((acc, type) => {
if (!type) return acc;
const data = rest[`streamSink${type}`] || [];
delete rest[`streamSink${type}`];
const formatData = data.map(ds => ({
...ds,
inlongGroupId,
inlongStreamId,
sinkType: type,
}));
return acc.concat(formatData);
}, []);
const fieldList = predefinedFields.concat(rowTypeFields).map((item, idx) => ({
...item,
inlongGroupId,
inlongStreamId,
isPredefinedField: idx < predefinedFields.length ? 1 : 0,
}));
output.streamInfo = {
...rest,
inlongGroupId,
inlongStreamId,
dataSourceType,
};
if (fieldList?.length) output.streamInfo.fieldList = fieldList;
return output;
});
return array;
};
// Convert interface data to form data
export const dataToValues = data => {
const array = data.map(item => {
const { sourceInfo, sinkInfo, streamInfo } = item;
let output = {
dataSourceType: sourceInfo[0]?.sourceType || 'AUTO_PUSH',
dataSourcesConfig: sourceInfo,
} as any;
sinkInfo.forEach(({ sinkType, ...item }) => {
if (!output[`streamSink${sinkType}`]) output[`streamSink${sinkType}`] = [];
output[`streamSink${sinkType}`].push(item);
});
output.streamSink = sinkInfo.map(item => item.sinkType);
const fieldList = streamInfo.fieldList?.reduce(
(acc, cur) => {
cur.isPredefinedField ? acc.predefinedFields.push(cur) : acc.rowTypeFields.push(cur);
return acc;
},
{
predefinedFields: [],
rowTypeFields: [],
},
);
output = {
hasHigher: false,
...output,
...fieldList,
...streamInfo,
};
return output;
});
return array;
};
| 26.765625 | 93 | 0.607706 | 92 | 11 | 0 | 15 | 12 | 0 | 0 | 2 | 0 | 0 | 2 | 18.454545 | 850 | 0.030588 | 0.014118 | 0 | 0 | 0.002353 | 0.052632 | 0 | 0.286609 | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you 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.
*/
// Convert form data into interface submission data format
export const valuesToData = (values, inlongGroupId) => {
const array = values.map(item => {
const {
inlongStreamId,
predefinedFields = [],
rowTypeFields = [],
dataSourceType,
dataSourcesConfig = [],
streamSink = [],
...rest
} = item;
const output = {} as any;
if (dataSourceType !== 'AUTO_PUSH') {
output.sourceInfo = dataSourcesConfig.map(k => {
return {
...k,
sourceType: dataSourceType,
inlongGroupId,
inlongStreamId,
};
});
} else {
output.sourceInfo = [
{
sourceType: dataSourceType,
sourceName: inlongStreamId,
inlongGroupId,
inlongStreamId,
},
];
}
output.sinkInfo = streamSink.reduce((acc, type) => {
if (!type) return acc;
const data = rest[`streamSink${type}`] || [];
delete rest[`streamSink${type}`];
const formatData = data.map(ds => ({
...ds,
inlongGroupId,
inlongStreamId,
sinkType: type,
}));
return acc.concat(formatData);
}, []);
const fieldList = predefinedFields.concat(rowTypeFields).map((item, idx) => ({
...item,
inlongGroupId,
inlongStreamId,
isPredefinedField: idx < predefinedFields.length ? 1 : 0,
}));
output.streamInfo = {
...rest,
inlongGroupId,
inlongStreamId,
dataSourceType,
};
if (fieldList?.length) output.streamInfo.fieldList = fieldList;
return output;
});
return array;
};
// Convert interface data to form data
export const dataToValues = data => {
const array = data.map(item => {
const { sourceInfo, sinkInfo, streamInfo } = item;
let output = {
dataSourceType: sourceInfo[0]?.sourceType || 'AUTO_PUSH',
dataSourcesConfig: sourceInfo,
} as any;
sinkInfo.forEach(({ sinkType, ...item }) => {
if (!output[`streamSink${sinkType}`]) output[`streamSink${sinkType}`] = [];
output[`streamSink${sinkType}`].push(item);
});
output.streamSink = sinkInfo.map(item => item.sinkType);
const fieldList = streamInfo.fieldList?.reduce(
(acc, cur) => {
cur.isPredefinedField ? acc.predefinedFields.push(cur) : acc.rowTypeFields.push(cur);
return acc;
},
{
predefinedFields: [],
rowTypeFields: [],
},
);
output = {
hasHigher: false,
...output,
...fieldList,
...streamInfo,
};
return output;
});
return array;
};
|
dadf55286f28793ab229a3f259e1af36d5c7836a | 1,851 | ts | TypeScript | src/Structures/Embed.ts | arnav7633/tej.js | 165cd1cc514ad24b1ea002e8c0831579f5a2f513 | [
"MIT"
] | 2 | 2022-03-12T04:29:58.000Z | 2022-03-29T18:31:34.000Z | src/Structures/Embed.ts | arnav7633/tej.js | 165cd1cc514ad24b1ea002e8c0831579f5a2f513 | [
"MIT"
] | 2 | 2022-02-26T21:08:48.000Z | 2022-03-16T05:37:30.000Z | src/Structures/Embed.ts | arnav7633/tej.js | 165cd1cc514ad24b1ea002e8c0831579f5a2f513 | [
"MIT"
] | null | null | null | interface Embed {
title: string
description: string
url: string
timestamp: Date
color: number
footer: {
text: string
icon_url: string
}
thumbnail: {
url: string
}
image: {
url: string
}
fields: {
name: string
value: string
inline: boolean
}[]
author: {
name: string
url: string
icon_url: string
}
}
class Embed {
constructor() {
this.title = ''
this.description = ''
this.url = ''
this.color = 0
this.timestamp = new Date()
this.footer = {
text: '',
icon_url: ''
}
this.image = {
url: ''
}
this.thumbnail = {
url: ''
}
this.author = {
name: '',
url: '',
icon_url: ''
}
this.fields = []
}
setTitle(title: string) {
this.title = title
return this
}
setDescription(description: string) {
this.description = description
return this
}
setURL(url: string) {
this.url = url
return this
}
setTimestamp(timestamp: Date) {
this.timestamp = timestamp
return this
}
setColor(color: number) {
this.color = color
return this
}
setFooter(text: string, icon: string) {
this.footer.text = text
this.footer.icon_url = icon
return this
}
setThumbnail(url: string) {
this.thumbnail.url = url
return this
}
setImage(url: string) {
this.image.url = url
return this
}
setAuthor(name: string, url: string, icon: string) {
this.author.name = name
this.author.url = url
this.author.icon_url = icon
return this
}
addField(name: string, value: string, inline: boolean = false) {
this.fields.push({
name,
value,
inline
})
return this
}
toJSON() {
return {
title: this.title,
description: this.description,
url: this.url,
timestamp: this.timestamp,
color: this.color,
footer: this.footer,
thumbnail: this.thumbnail,
image: this.image,
fields: this.fields,
author: this.author
}
}
}
| 16.236842 | 65 | 0.632631 | 113 | 12 | 0 | 15 | 0 | 10 | 0 | 0 | 28 | 2 | 0 | 5 | 666 | 0.040541 | 0 | 0.015015 | 0.003003 | 0 | 0 | 0.756757 | 0.268775 | interface Embed {
title
description
url
timestamp
color
footer
thumbnail
image
fields
author
}
class Embed {
constructor() {
this.title = ''
this.description = ''
this.url = ''
this.color = 0
this.timestamp = new Date()
this.footer = {
text: '',
icon_url: ''
}
this.image = {
url: ''
}
this.thumbnail = {
url: ''
}
this.author = {
name: '',
url: '',
icon_url: ''
}
this.fields = []
}
setTitle(title) {
this.title = title
return this
}
setDescription(description) {
this.description = description
return this
}
setURL(url) {
this.url = url
return this
}
setTimestamp(timestamp) {
this.timestamp = timestamp
return this
}
setColor(color) {
this.color = color
return this
}
setFooter(text, icon) {
this.footer.text = text
this.footer.icon_url = icon
return this
}
setThumbnail(url) {
this.thumbnail.url = url
return this
}
setImage(url) {
this.image.url = url
return this
}
setAuthor(name, url, icon) {
this.author.name = name
this.author.url = url
this.author.icon_url = icon
return this
}
addField(name, value, inline = false) {
this.fields.push({
name,
value,
inline
})
return this
}
toJSON() {
return {
title: this.title,
description: this.description,
url: this.url,
timestamp: this.timestamp,
color: this.color,
footer: this.footer,
thumbnail: this.thumbnail,
image: this.image,
fields: this.fields,
author: this.author
}
}
}
|
86008612be1088c151f15a854549f0c9cd566343 | 1,181 | ts | TypeScript | packages/client-core/lib/__mocks__/props-presets-steps.ts | IQ-tech/firebolt | 5ae7519505129ca268f97ec72623860312163c0f | [
"Apache-2.0"
] | 5 | 2022-03-08T21:18:17.000Z | 2022-03-09T13:13:59.000Z | packages/client-core/lib/__mocks__/props-presets-steps.ts | IQ-tech/firebolt | 5ae7519505129ca268f97ec72623860312163c0f | [
"Apache-2.0"
] | 11 | 2022-03-08T14:42:46.000Z | 2022-03-14T13:03:58.000Z | packages/client-core/lib/__mocks__/props-presets-steps.ts | IQ-tech/firebolt | 5ae7519505129ca268f97ec72623860312163c0f | [
"Apache-2.0"
] | 1 | 2022-03-14T17:40:23.000Z | 2022-03-14T17:40:23.000Z | export const customCollection = {
name: "specific-docs",
presets: {
"cod": {
label: "Press F to pay respects",
placeholder: "write something",
batata: "batata",
},
"bat": {
"label": "i'm batman",
"placeholder": "bat placeholder",
"cenoura": "cenoura"
}
}
}
export const secondCollection = {
name: "second-preset-collection",
presets: {
"buiu": {
label: "Buiu",
placeholder: "potato"
},
"cod": {
label: "second collection cod",
placeholder: "second collection cod",
"cebola": "cebola"
}
}
}
export const getRequestMock = (preset = "cod") => ({
message: "ok",
formData: {
step: {
data: {
slug: "personal_data",
type: "form",
friendlyName: "Vamos começar",
fields: [
{
slug: "full_name",
"ui:widget": "Text",
"ui:props-preset": preset,
"ui:props": {
label: "Nome completo",
placeholder: "Nome completo",
},
validators: [],
meta: {},
},
],
},
position: 1,
}
}
})
| 19.360656 | 52 | 0.470787 | 55 | 1 | 0 | 1 | 3 | 0 | 0 | 0 | 0 | 0 | 0 | 26 | 318 | 0.006289 | 0.009434 | 0 | 0 | 0 | 0 | 0 | 0.215647 | export const customCollection = {
name: "specific-docs",
presets: {
"cod": {
label: "Press F to pay respects",
placeholder: "write something",
batata: "batata",
},
"bat": {
"label": "i'm batman",
"placeholder": "bat placeholder",
"cenoura": "cenoura"
}
}
}
export const secondCollection = {
name: "second-preset-collection",
presets: {
"buiu": {
label: "Buiu",
placeholder: "potato"
},
"cod": {
label: "second collection cod",
placeholder: "second collection cod",
"cebola": "cebola"
}
}
}
export const getRequestMock = (preset = "cod") => ({
message: "ok",
formData: {
step: {
data: {
slug: "personal_data",
type: "form",
friendlyName: "Vamos começar",
fields: [
{
slug: "full_name",
"ui:widget": "Text",
"ui:props-preset": preset,
"ui:props": {
label: "Nome completo",
placeholder: "Nome completo",
},
validators: [],
meta: {},
},
],
},
position: 1,
}
}
})
|
714b8e472bcd3cdcca43385f9d5d2554fc1780a1 | 6,426 | ts | TypeScript | packages/fe-mockserver-core/src/router/batchParser.ts | SAP/open-ux-odata | 78af1d9b304427f3ec7fa8227d89bcc14cec08a0 | [
"Apache-2.0"
] | 3 | 2022-03-29T10:29:19.000Z | 2022-03-29T12:17:51.000Z | packages/fe-mockserver-core/src/router/batchParser.ts | SAP/open-ux-odata | 78af1d9b304427f3ec7fa8227d89bcc14cec08a0 | [
"Apache-2.0"
] | 27 | 2022-03-29T09:29:35.000Z | 2022-03-31T13:07:33.000Z | packages/fe-mockserver-core/src/router/batchParser.ts | SAP/open-ux-odata | 78af1d9b304427f3ec7fa8227d89bcc14cec08a0 | [
"Apache-2.0"
] | null | null | null | function split(input: string) {
const LF = '\n';
const CRLF = '\r\n';
const a = [];
let pL = 0;
let p1 = input.indexOf(CRLF, pL);
let p2 = input.indexOf(LF, pL);
while (p1 !== -1 || p2 !== -1) {
if (p1 !== -1 && p1 <= p2) {
a.push(input.substring(pL, p1));
pL = p1 + 2;
} else {
a.push(input.substring(pL, p2));
pL = p2 + 1;
}
p1 = input.indexOf(CRLF, pL);
p2 = input.indexOf(LF, pL);
}
if (pL < input.length) {
a.push(input.substring(pL));
}
return a;
}
/**
*
*/
export class BatchContent {
type: number;
stringData: string;
stringSplit: any;
pos: number;
public constructor(data: string) {
this.type = 0;
this.stringData = data;
this.stringSplit = split(data);
this.pos = 0;
}
public lookLine(): string {
return this.stringSplit[this.pos];
}
public readLine(): string {
return this.stringSplit[this.pos++];
}
public inc(): void {
this.pos++;
}
}
export class Batch {
changeSetErrorResponse: any;
parts: (BatchPart | Batch)[];
public constructor(public isChangeSet: boolean, public boundary: string) {
if (this.isChangeSet) {
this.changeSetErrorResponse = null;
}
this.parts = [];
}
}
export function getBoundary(headerValue: string) {
const l = headerValue.split(';');
for (const element of l) {
const ll = element.split('=');
if (ll[0].trim() === 'boundary') {
return ll[1];
}
}
return '';
}
function readHeader(line: string) {
const colPos = line.indexOf(':');
if (colPos === -1) {
throw new Error('Invalid header "content-type" in batch part');
}
const s0 = line.substring(0, colPos);
const s1 = line.substring(colPos + 1);
return {
name: s0.toLowerCase(),
value: s1.trim()
};
}
export type BatchPart = {
url: string;
method: string;
body: any;
headers: Record<string, string>;
contentId?: string;
};
function readAppHttp(batchContent: BatchContent, boundary: string): BatchPart {
const headers: any = {};
const payload = [];
let state = 0; //read url
const rawUrl = batchContent.readLine();
state = 1; //read header
let line = batchContent.lookLine();
while (line !== null && line !== undefined && line.indexOf(boundary) !== 0) {
if (state === 1) {
if (line.length === 0) {
state = 2; //read body
batchContent.inc();
} else {
const h = readHeader(line);
headers[h.name] = h.value;
batchContent.inc();
}
} else if (state === 2) {
payload.push(line);
batchContent.inc();
}
line = batchContent.lookLine();
}
if (line === undefined) {
throw new Error('Invalid boundary while parsing batch request. Expect boundary ' + boundary);
}
const [method, url] = rawUrl.split(' ');
let actualBody: any;
if (payload.length > 0) {
try {
actualBody = JSON.parse(payload[0]);
} catch (e) {
actualBody = payload[0];
}
}
return {
url: `/${url}`,
method: method,
headers: headers,
body: actualBody
};
}
function extractContent(batchContent: BatchContent, headers: any, boundary: string) {
let content;
if (!headers['content-type']) {
throw new Error('Missing header "content-type" in batch part');
} else if (headers['content-type'] === 'application/http') {
content = readAppHttp(batchContent, boundary);
if (headers['content-id']) {
content.contentId = headers['content-id'];
}
} else if (headers['content-type'].indexOf('multipart/mixed;') > -1) {
const changeSetBoundary = getBoundary(headers['content-type']);
content = parseBatch(batchContent, changeSetBoundary, true);
}
return content;
}
function parsePart(batchContent: BatchContent, boundary: string) {
const boundaryNext = boundary;
const boundaryEnd = boundary + '--';
const headers: any = {};
let content;
let state = 1; //read header
let line = batchContent.lookLine();
while (line !== null && line !== undefined && line !== boundaryNext && line !== boundaryEnd) {
if (state === 1) {
if (line.length === 0) {
state = 2; //read body
batchContent.inc();
} else {
const h = readHeader(line);
headers[h.name] = h.value;
batchContent.inc();
}
} else if (state === 2) {
content = extractContent(batchContent, headers, boundary);
}
line = batchContent.lookLine();
}
if (line === undefined) {
throw new Error('Invalid boundary while parsing batch request. Expect boundary ' + boundary);
}
return content;
}
export function parseBatch(content: BatchContent, boundary: string, isChangeset: boolean = false) {
const boundaryNext = '--' + boundary;
const boundaryEnd = '--' + boundary + '--';
const batch = new Batch(isChangeset, boundary);
let part;
let line = content.readLine();
while (line !== null && line !== undefined && line !== boundaryNext) {
//read lines before first boundary
line = content.readLine();
}
if (line === undefined) {
throw new Error('Invalid boundary while parsing batch request');
}
//line is now read boundary
line = content.lookLine(); //read line behind
while (line !== null && line !== undefined && line !== boundaryEnd) {
part = parsePart(content, boundaryNext);
if (part) {
batch.parts.push(part);
}
line = content.lookLine(); //now on boundary
if (line === boundaryNext) {
line = content.readLine(); //consume boundaryNext
}
}
content.readLine(); //consume boundaryEnd
line = content.lookLine(); //read line behind
while (line !== null && line !== undefined && line.length === 0) {
//read empty lines after first boundary end
content.readLine();
line = content.lookLine();
}
return batch;
}
| 27.344681 | 101 | 0.546685 | 198 | 12 | 0 | 16 | 33 | 11 | 10 | 7 | 22 | 3 | 0 | 13.083333 | 1,639 | 0.017084 | 0.020134 | 0.006711 | 0.00183 | 0 | 0.097222 | 0.305556 | 0.279399 | /* Example usages of 'split' are shown below:
this.stringSplit = split(data);
headerValue.split(';');
element.split('=');
rawUrl.split(' ');
*/
function split(input) {
const LF = '\n';
const CRLF = '\r\n';
const a = [];
let pL = 0;
let p1 = input.indexOf(CRLF, pL);
let p2 = input.indexOf(LF, pL);
while (p1 !== -1 || p2 !== -1) {
if (p1 !== -1 && p1 <= p2) {
a.push(input.substring(pL, p1));
pL = p1 + 2;
} else {
a.push(input.substring(pL, p2));
pL = p2 + 1;
}
p1 = input.indexOf(CRLF, pL);
p2 = input.indexOf(LF, pL);
}
if (pL < input.length) {
a.push(input.substring(pL));
}
return a;
}
/**
*
*/
export class BatchContent {
type;
stringData;
stringSplit;
pos;
public constructor(data) {
this.type = 0;
this.stringData = data;
this.stringSplit = split(data);
this.pos = 0;
}
public lookLine() {
return this.stringSplit[this.pos];
}
public readLine() {
return this.stringSplit[this.pos++];
}
public inc() {
this.pos++;
}
}
export class Batch {
changeSetErrorResponse;
parts;
public constructor(public isChangeSet, public boundary) {
if (this.isChangeSet) {
this.changeSetErrorResponse = null;
}
this.parts = [];
}
}
export /* Example usages of 'getBoundary' are shown below:
getBoundary(headers['content-type']);
*/
function getBoundary(headerValue) {
const l = headerValue.split(';');
for (const element of l) {
const ll = element.split('=');
if (ll[0].trim() === 'boundary') {
return ll[1];
}
}
return '';
}
/* Example usages of 'readHeader' are shown below:
readHeader(line);
*/
function readHeader(line) {
const colPos = line.indexOf(':');
if (colPos === -1) {
throw new Error('Invalid header "content-type" in batch part');
}
const s0 = line.substring(0, colPos);
const s1 = line.substring(colPos + 1);
return {
name: s0.toLowerCase(),
value: s1.trim()
};
}
export type BatchPart = {
url;
method;
body;
headers;
contentId?;
};
/* Example usages of 'readAppHttp' are shown below:
content = readAppHttp(batchContent, boundary);
*/
function readAppHttp(batchContent, boundary) {
const headers = {};
const payload = [];
let state = 0; //read url
const rawUrl = batchContent.readLine();
state = 1; //read header
let line = batchContent.lookLine();
while (line !== null && line !== undefined && line.indexOf(boundary) !== 0) {
if (state === 1) {
if (line.length === 0) {
state = 2; //read body
batchContent.inc();
} else {
const h = readHeader(line);
headers[h.name] = h.value;
batchContent.inc();
}
} else if (state === 2) {
payload.push(line);
batchContent.inc();
}
line = batchContent.lookLine();
}
if (line === undefined) {
throw new Error('Invalid boundary while parsing batch request. Expect boundary ' + boundary);
}
const [method, url] = rawUrl.split(' ');
let actualBody;
if (payload.length > 0) {
try {
actualBody = JSON.parse(payload[0]);
} catch (e) {
actualBody = payload[0];
}
}
return {
url: `/${url}`,
method: method,
headers: headers,
body: actualBody
};
}
/* Example usages of 'extractContent' are shown below:
content = extractContent(batchContent, headers, boundary);
*/
function extractContent(batchContent, headers, boundary) {
let content;
if (!headers['content-type']) {
throw new Error('Missing header "content-type" in batch part');
} else if (headers['content-type'] === 'application/http') {
content = readAppHttp(batchContent, boundary);
if (headers['content-id']) {
content.contentId = headers['content-id'];
}
} else if (headers['content-type'].indexOf('multipart/mixed;') > -1) {
const changeSetBoundary = getBoundary(headers['content-type']);
content = parseBatch(batchContent, changeSetBoundary, true);
}
return content;
}
/* Example usages of 'parsePart' are shown below:
part = parsePart(content, boundaryNext);
*/
function parsePart(batchContent, boundary) {
const boundaryNext = boundary;
const boundaryEnd = boundary + '--';
const headers = {};
let content;
let state = 1; //read header
let line = batchContent.lookLine();
while (line !== null && line !== undefined && line !== boundaryNext && line !== boundaryEnd) {
if (state === 1) {
if (line.length === 0) {
state = 2; //read body
batchContent.inc();
} else {
const h = readHeader(line);
headers[h.name] = h.value;
batchContent.inc();
}
} else if (state === 2) {
content = extractContent(batchContent, headers, boundary);
}
line = batchContent.lookLine();
}
if (line === undefined) {
throw new Error('Invalid boundary while parsing batch request. Expect boundary ' + boundary);
}
return content;
}
export /* Example usages of 'parseBatch' are shown below:
content = parseBatch(batchContent, changeSetBoundary, true);
*/
function parseBatch(content, boundary, isChangeset = false) {
const boundaryNext = '--' + boundary;
const boundaryEnd = '--' + boundary + '--';
const batch = new Batch(isChangeset, boundary);
let part;
let line = content.readLine();
while (line !== null && line !== undefined && line !== boundaryNext) {
//read lines before first boundary
line = content.readLine();
}
if (line === undefined) {
throw new Error('Invalid boundary while parsing batch request');
}
//line is now read boundary
line = content.lookLine(); //read line behind
while (line !== null && line !== undefined && line !== boundaryEnd) {
part = parsePart(content, boundaryNext);
if (part) {
batch.parts.push(part);
}
line = content.lookLine(); //now on boundary
if (line === boundaryNext) {
line = content.readLine(); //consume boundaryNext
}
}
content.readLine(); //consume boundaryEnd
line = content.lookLine(); //read line behind
while (line !== null && line !== undefined && line.length === 0) {
//read empty lines after first boundary end
content.readLine();
line = content.lookLine();
}
return batch;
}
|
7152924558e0bb8be3e7e217c76d00b140bf1695 | 16,696 | ts | TypeScript | src/ui/app/Snapshooter.ts | nickbradley/scout | b2bd99925877421415567393e40d6be51d7a2c28 | [
"MIT"
] | null | null | null | src/ui/app/Snapshooter.ts | nickbradley/scout | b2bd99925877421415567393e40d6be51d7a2c28 | [
"MIT"
] | 1 | 2022-01-11T19:07:36.000Z | 2022-01-11T19:07:36.000Z | src/ui/app/Snapshooter.ts | nickbradley/scout | b2bd99925877421415567393e40d6be51d7a2c28 | [
"MIT"
] | null | null | null | /* eslint-disable */
// @ts-nocheck
"use strict";
/**
* Snapshooter is responsible for returning HTML and computed CSS of all nodes from selected DOM subtree.
*
* @param HTMLElement root Root node for the subtree that will be processed
* @returns {*} object with HTML as a string and CSS as an array of arrays of css properties
*/
export function Snapshooter(root) {
"use strict";
// list of shorthand properties based on CSSShorthands.in from the Chromium code (https://code.google.com/p/chromium/codesearch)
// TODO this list should not be hardcoded here
var shorthandProperties = {
'animation': 'animation',
'background': 'background',
'border': 'border',
'border-top': 'borderTop',
'border-right': 'borderRight',
'border-bottom': 'borderBottom',
'border-left': 'borderLeft',
'border-width': 'borderWidth',
'border-color': 'borderColor',
'border-style': 'borderStyle',
'border-radius': 'borderRadius',
'border-image': 'borderImage',
'border-spacing': 'borderSpacing',
'flex': 'flex',
'flex-flow': 'flexFlow',
'font': 'font',
'grid-area': 'gridArea',
'grid-column': 'gridColumn',
'grid-row': 'gridRow',
'list-style': 'listStyle',
'margin': 'margin',
'marker': 'marker',
'outline': 'outline',
'overflow': 'overflow',
'padding': 'padding',
'text-decoration': 'textDecoration',
'transition': 'transition',
'-webkit-border-after': 'webkitBorderAfter',
'-webkit-border-before': 'webkitBorderBefore',
'-webkit-border-end': 'webkitBorderEnd',
'-webkit-border-start': 'webkitBorderStart',
'-webkit-columns': 'webkitBorderColumns',
'-webkit-column-rule': 'webkitBorderColumnRule',
'-webkit-margin-collapse': 'webkitMarginCollapse',
'-webkit-mask': 'webkitMask',
'-webkit-mask-position': 'webkitMaskPosition',
'-webkit-mask-repeat': 'webkitMaskRepeat',
'-webkit-text-emphasis': 'webkitTextEmphasis',
'-webkit-transition': 'webkitTransition',
'-webkit-transform-origin': 'webkitTransformOrigin'
}, idCounter = 1;
/**
* Changes CSSStyleDeclaration to simple Object removing unwanted properties ('1','2','parentRule','cssText' etc.) in the process.
*
* @param CSSStyleDeclaration style
* @returns {}
*/
function styleDeclarationToSimpleObject(style) {
var i, l, cssName, camelCaseName, output = {};
const excludeStyles = ["height", "width", "block-size", "perspective-origin", "inline-size", "transform-origin", "-webkit-transform-origin", "webkitTransformOrigin", "grid-template-columns", "grid-template-rows"];
for (i = 0, l = style.length; i < l; i++) {
if (!excludeStyles.includes(style[i])) {
output[style[i]] = style[style[i]];
}
}
// Work around http://crbug.com/313670 (the "content" property is not present as a computed style indexed property value).
output.content = fixContentProperty(style.content);
// Since shorthand properties are not available in the indexed array, copy them from named properties
for (cssName in shorthandProperties) {
if (shorthandProperties.hasOwnProperty(cssName)) {
camelCaseName = shorthandProperties[cssName];
output[cssName] = style[camelCaseName];
}
}
return output;
}
// Partial workaround for http://crbug.com/315028 (single words in the "content" property are not wrapped with quotes)
function fixContentProperty(content) {
var values, output, value, i, l;
output = [];
if (content) {
//content property can take multiple values - we need to split them up
//FIXME this won't work for '\''
values = content.match(/(?:[^\s']+|'[^']*')+/g);
for (i = 0, l = values.length; i < l; i++) {
value = values[i];
if (value.match(/^(url\()|(attr\()|normal|none|open-quote|close-quote|no-open-quote|no-close-quote|chapter_counter|'/g)) {
output.push(value);
}
else {
output.push("'" + value + "'");
}
}
}
return output.join(' ');
}
function createID(node) {
//":snappysnippet_prefix:" is a prefix placeholder
return ':snappysnippet_prefix:' + node.tagName + '_' + idCounter++;
}
function dumpCSS(node, pseudoElement) {
var styles;
// There is no default view when out page is loaded as srcdoc in iFrame
styles = node.ownerDocument.defaultView?.getComputedStyle(node, pseudoElement);
if (pseudoElement) {
//if we are dealing with pseudoelement, check if 'content' property isn't empty
//if it is, then we can ignore the whole element
if (!styles.getPropertyValue('content')) {
return null;
}
}
if (styles) {
return styleDeclarationToSimpleObject(styles);
} else {
return {};
}
}
function cssObjectForElement(element, omitPseudoElements = true) {
return {
id: createID(element),
tagName: element.tagName,
node: dumpCSS(element, null),
before: omitPseudoElements ? null : dumpCSS(element, ':before'),
after: omitPseudoElements ? null : dumpCSS(element, ':after')
};
}
function ancestorTagHTML(element, closingTag) {
var i, attr, value, idSeen, result, attributes;
if (closingTag) {
return '</' + element.tagName + '>';
}
result = '<' + element.tagName;
attributes = element.attributes;
for (i = 0; i < attributes.length; ++i) {
attr = attributes[i];
if (attr.name.toLowerCase() === 'id') {
value = createID(element);
idSeen = true;
}
else {
value = attr.value;
}
result += ' ' + attributes[i].name + '="' + value + '"';
}
if (!idSeen) {
result += ' id="' + createID(element) + '"';
}
result += '>';
return result;
}
/**
* Replaces all relative URLs (in images, links etc.) with absolute URLs
* @param element
*/
function relativeURLsToAbsoluteURLs(element) {
switch (element.nodeName) {
case 'A':
case 'AREA':
case 'LINK':
case 'BASE':
if (element.hasAttribute('href')) {
element.setAttribute('href', element.href);
}
break;
case 'IMG':
case 'IFRAME':
case 'INPUT':
case 'FRAME':
case 'SCRIPT':
if (element.hasAttribute('src')) {
element.setAttribute('src', element.src);
}
break;
case 'FORM':
if (element.hasAttribute('action')) {
element.setAttribute('action', element.action);
}
break;
}
}
function init() {
var css = [], ancestorCss = [], descendants, descendant, htmlSegments, leadingAncestorHtml, trailingAncestorHtml, reverseAncestors = [], i, l, parent, clone;
descendants = root.getElementsByTagName('*');
parent = root.parentElement;
while (parent && parent !== document.body) {
reverseAncestors.push(parent);
parent = parent.parentElement;
}
// First we go through all nodes and dump all CSS
css.push(cssObjectForElement(root));
for (i = 0, l = descendants.length; i < l; i++) {
css.push(cssObjectForElement(descendants[i]));
}
for (i = reverseAncestors.length - 1; i >= 0; i--) {
ancestorCss.push(cssObjectForElement(reverseAncestors[i], true));
}
// Next we dump all HTML and update IDs
// Since we don't want to touch original DOM and we want to change IDs, we clone the original DOM subtree
clone = root.cloneNode(true);
descendants = clone.getElementsByTagName('*');
idCounter = 1;
clone.setAttribute('id', createID(clone));
for (i = 0, l = descendants.length; i < l; i++) {
descendant = descendants[i];
descendant.setAttribute('id', createID(descendant));
relativeURLsToAbsoluteURLs(descendant);
}
// Build leading and trailing HTML for ancestors
htmlSegments = [];
for (i = reverseAncestors.length - 1; i >= 0; i--) {
htmlSegments.push(ancestorTagHTML(reverseAncestors[i]));
}
leadingAncestorHtml = htmlSegments.join('');
htmlSegments = [];
for (i = 0, l = reverseAncestors.length; i < l; i++) {
htmlSegments.push(ancestorTagHTML(reverseAncestors[i], true));
}
trailingAncestorHtml = htmlSegments.join('');
return JSON.stringify({
html: clone.outerHTML,
leadingAncestorHtml: leadingAncestorHtml,
trailingAncestorHtml: trailingAncestorHtml,
css: css,
ancestorCss: ancestorCss
});
}
return init();
}
/**
* Utility that transforms object representing CSS rules to actual CSS code.
*
* @constructor
*/
export function CSSStringifier() {
"use strict";
function propertiesToString(properties) {
var propertyName, output = "";
for (propertyName in properties) {
if (properties.hasOwnProperty(propertyName)) {
output += " " + propertyName + ": " + properties[propertyName] + ";\n";
}
}
return output;
}
function printIDs(ids, pseudoElement) {
var i, l, idString, output = [];
if (!(ids instanceof Array)) {
ids = [ids];
}
for (i = 0, l = ids.length; i < l; i++) {
idString = '#' + ids[i];
if (pseudoElement) {
idString += pseudoElement;
}
output.push(idString);
}
return output.join(', ');
}
this.process = function (styles) {
var i, l, style, output = "";
for (i = 0, l = styles.length; i < l; i++) {
style = styles[i];
output += printIDs(style.id) + ' {\n';
output += propertiesToString(style.node);
output += '}/*' + printIDs(style.id) + '*/\n\n';
if (style.after) {
output += printIDs(style.id, ':after') + ' {\n';
output += propertiesToString(style.after);
output += '}/*' + printIDs(style.id, ':after') + '*/\n\n';
}
if (style.before) {
output += printIDs(style.id, ':before') + ' {\n';
output += propertiesToString(style.before);
output += '}/*' + printIDs(style.id, ':before') + '*/\n\n';
}
}
return output;
};
}
/**
* Injects the CSS into the HTML as Style attributes.
*
* @constructor
*/
export function HTMLStylesCombiner() {
"use strict";
var cursor = 0, stylesMap,
// constants
ATTRIBUTE_ENCLOSING_CHARACTERS = ['"', "'"], ESCAPING_CHARACTER = '\\', ID_ATTRIBUTE = "id=", STYLE_ATTRIBUTE = "style=";
/**
* Looks for the next 'id' attribute inside a tag. Returns -1 if not found.
*/
function getNextIdAttributePosition(html, lastCursor) {
var currentCursor, tagStartCursor, tagEndCursor, idCursor;
while (lastCursor >= 0) {
tagStartCursor = html.indexOf("<", lastCursor);
if (tagStartCursor < 0) {
return -1;
}
tagEndCursor = html.indexOf(">", tagStartCursor);
if (tagEndCursor < 0) {
return -1;
}
currentCursor = tagStartCursor;
do {
idCursor = html.indexOf(ID_ATTRIBUTE, currentCursor);
if (idCursor < 0) {
return -1;
}
else if (ATTRIBUTE_ENCLOSING_CHARACTERS.indexOf(html.charAt(idCursor + ID_ATTRIBUTE.length)) < 0) {
// Not the right 'id=', look for the next
currentCursor++;
}
else if (idCursor < tagEndCursor) {
// Finally!
return idCursor;
}
} while (idCursor < tagEndCursor);
lastCursor = tagEndCursor;
}
}
/**
* Extracts the attribute value that is in the current position.
* @param html the text to extract from.
* @param attributeEnclosingChar the string/character that encloses the value.
* @returns {*} The value that relates to the closest attribute, or null if not found.
*/
function extractValueInCurrentPosition(html, attributeEnclosingChar) {
var idStartIndex, idEndIndex;
idStartIndex = html.indexOf(attributeEnclosingChar, cursor) + 1;
idEndIndex = html.indexOf(attributeEnclosingChar, idStartIndex + 1);
if (idStartIndex < 0 || idEndIndex < 0) {
return null;
}
return html.substring(idStartIndex, idEndIndex);
}
/**
* Converts SnappySnippet's CSS object into a string of CSS properties.
* @param properties The CSS object to extort.
* @param attributeEnclosingChar The string/character that encloses values.
* @returns {string} CSS properties contained in the given object.
*/
function propertiesToString(properties, attributeEnclosingChar) {
var propertyName, output = "";
for (propertyName in properties) {
if (properties.hasOwnProperty(propertyName)) {
// Treat those special url() functionals, that sometimes have quotation marks although they are not required
var propertyValue = properties[propertyName].replace(/url\("(.*)"\)/g, "url($1)").replace(/url\('(.*)'\)/g, "url($1)")
.replace(attributeEnclosingChar, ESCAPING_CHARACTER + attributeEnclosingChar);
output += propertyName + ": " + propertyValue + "; ";
}
}
return output;
}
/**
* Injects style attribute to the current position in the HTML.
* @param html The text to use.
* @param styleId What key we are currently on.
* @param attributeEnclosingChar The string/character that encloses values.
* @returns {*} the modified string.
*/
function insertStyleAtIndex(html, styleId, attributeEnclosingChar) {
var cssStyles = stylesMap[styleId] && stylesMap[styleId].node;
if (!cssStyles) {
return html;
}
return html.substring(0, cursor) + // The head of the string
STYLE_ATTRIBUTE + attributeEnclosingChar + // The attribute key
propertiesToString(stylesMap[styleId].node, attributeEnclosingChar) + // The attribute value
attributeEnclosingChar + " " + // Closing the value just before the next attribute
html.substring(cursor); // The tail of the string
}
this.process = function (html, styles) {
var currentId, attributeEnclosingChar;
// Sanity check
if (Boolean(html) && Boolean(styles)) {
// Prepare a lookup dictionary of styles by the respective element id
stylesMap = styles.map(function (styleObj) {
var keyValuePair = {};
keyValuePair[styleObj.id] = styleObj;
return keyValuePair;
}).reduce(function (mergedObj, currentObj) {
return Object.assign(mergedObj, currentObj); //$.extend(mergedObj, currentObj);
});
cursor = getNextIdAttributePosition(html, 0);
while (cursor >= 0) {
// Make use of the fact that attribute value is always enclosed with the same char (either " or ')
attributeEnclosingChar = html.charAt(cursor + ID_ATTRIBUTE.length);
currentId = extractValueInCurrentPosition(html, attributeEnclosingChar);
if (currentId === null)
break;
html = insertStyleAtIndex(html, currentId, attributeEnclosingChar);
cursor = getNextIdAttributePosition(html, cursor);
}
}
return html;
};
}
| 41.224691 | 221 | 0.561512 | 330 | 21 | 0 | 29 | 61 | 0 | 13 | 0 | 0 | 0 | 1 | 27.142857 | 3,829 | 0.013058 | 0.015931 | 0 | 0 | 0.000261 | 0 | 0 | 0.256017 | /* eslint-disable */
// @ts-nocheck
"use strict";
/**
* Snapshooter is responsible for returning HTML and computed CSS of all nodes from selected DOM subtree.
*
* @param HTMLElement root Root node for the subtree that will be processed
* @returns {*} object with HTML as a string and CSS as an array of arrays of css properties
*/
export function Snapshooter(root) {
"use strict";
// list of shorthand properties based on CSSShorthands.in from the Chromium code (https://code.google.com/p/chromium/codesearch)
// TODO this list should not be hardcoded here
var shorthandProperties = {
'animation': 'animation',
'background': 'background',
'border': 'border',
'border-top': 'borderTop',
'border-right': 'borderRight',
'border-bottom': 'borderBottom',
'border-left': 'borderLeft',
'border-width': 'borderWidth',
'border-color': 'borderColor',
'border-style': 'borderStyle',
'border-radius': 'borderRadius',
'border-image': 'borderImage',
'border-spacing': 'borderSpacing',
'flex': 'flex',
'flex-flow': 'flexFlow',
'font': 'font',
'grid-area': 'gridArea',
'grid-column': 'gridColumn',
'grid-row': 'gridRow',
'list-style': 'listStyle',
'margin': 'margin',
'marker': 'marker',
'outline': 'outline',
'overflow': 'overflow',
'padding': 'padding',
'text-decoration': 'textDecoration',
'transition': 'transition',
'-webkit-border-after': 'webkitBorderAfter',
'-webkit-border-before': 'webkitBorderBefore',
'-webkit-border-end': 'webkitBorderEnd',
'-webkit-border-start': 'webkitBorderStart',
'-webkit-columns': 'webkitBorderColumns',
'-webkit-column-rule': 'webkitBorderColumnRule',
'-webkit-margin-collapse': 'webkitMarginCollapse',
'-webkit-mask': 'webkitMask',
'-webkit-mask-position': 'webkitMaskPosition',
'-webkit-mask-repeat': 'webkitMaskRepeat',
'-webkit-text-emphasis': 'webkitTextEmphasis',
'-webkit-transition': 'webkitTransition',
'-webkit-transform-origin': 'webkitTransformOrigin'
}, idCounter = 1;
/**
* Changes CSSStyleDeclaration to simple Object removing unwanted properties ('1','2','parentRule','cssText' etc.) in the process.
*
* @param CSSStyleDeclaration style
* @returns {}
*/
/* Example usages of 'styleDeclarationToSimpleObject' are shown below:
styleDeclarationToSimpleObject(styles);
*/
function styleDeclarationToSimpleObject(style) {
var i, l, cssName, camelCaseName, output = {};
const excludeStyles = ["height", "width", "block-size", "perspective-origin", "inline-size", "transform-origin", "-webkit-transform-origin", "webkitTransformOrigin", "grid-template-columns", "grid-template-rows"];
for (i = 0, l = style.length; i < l; i++) {
if (!excludeStyles.includes(style[i])) {
output[style[i]] = style[style[i]];
}
}
// Work around http://crbug.com/313670 (the "content" property is not present as a computed style indexed property value).
output.content = fixContentProperty(style.content);
// Since shorthand properties are not available in the indexed array, copy them from named properties
for (cssName in shorthandProperties) {
if (shorthandProperties.hasOwnProperty(cssName)) {
camelCaseName = shorthandProperties[cssName];
output[cssName] = style[camelCaseName];
}
}
return output;
}
// Partial workaround for http://crbug.com/315028 (single words in the "content" property are not wrapped with quotes)
/* Example usages of 'fixContentProperty' are shown below:
// Work around http://crbug.com/313670 (the "content" property is not present as a computed style indexed property value).
output.content = fixContentProperty(style.content);
*/
function fixContentProperty(content) {
var values, output, value, i, l;
output = [];
if (content) {
//content property can take multiple values - we need to split them up
//FIXME this won't work for '\''
values = content.match(/(?:[^\s']+|'[^']*')+/g);
for (i = 0, l = values.length; i < l; i++) {
value = values[i];
if (value.match(/^(url\()|(attr\()|normal|none|open-quote|close-quote|no-open-quote|no-close-quote|chapter_counter|'/g)) {
output.push(value);
}
else {
output.push("'" + value + "'");
}
}
}
return output.join(' ');
}
/* Example usages of 'createID' are shown below:
createID(element);
value = createID(element);
result += ' id="' + createID(element) + '"';
clone.setAttribute('id', createID(clone));
descendant.setAttribute('id', createID(descendant));
*/
function createID(node) {
//":snappysnippet_prefix:" is a prefix placeholder
return ':snappysnippet_prefix:' + node.tagName + '_' + idCounter++;
}
/* Example usages of 'dumpCSS' are shown below:
dumpCSS(element, null);
omitPseudoElements ? null : dumpCSS(element, ':before');
omitPseudoElements ? null : dumpCSS(element, ':after');
*/
function dumpCSS(node, pseudoElement) {
var styles;
// There is no default view when out page is loaded as srcdoc in iFrame
styles = node.ownerDocument.defaultView?.getComputedStyle(node, pseudoElement);
if (pseudoElement) {
//if we are dealing with pseudoelement, check if 'content' property isn't empty
//if it is, then we can ignore the whole element
if (!styles.getPropertyValue('content')) {
return null;
}
}
if (styles) {
return styleDeclarationToSimpleObject(styles);
} else {
return {};
}
}
/* Example usages of 'cssObjectForElement' are shown below:
// First we go through all nodes and dump all CSS
css.push(cssObjectForElement(root));
css.push(cssObjectForElement(descendants[i]));
ancestorCss.push(cssObjectForElement(reverseAncestors[i], true));
*/
function cssObjectForElement(element, omitPseudoElements = true) {
return {
id: createID(element),
tagName: element.tagName,
node: dumpCSS(element, null),
before: omitPseudoElements ? null : dumpCSS(element, ':before'),
after: omitPseudoElements ? null : dumpCSS(element, ':after')
};
}
/* Example usages of 'ancestorTagHTML' are shown below:
htmlSegments.push(ancestorTagHTML(reverseAncestors[i]));
htmlSegments.push(ancestorTagHTML(reverseAncestors[i], true));
*/
function ancestorTagHTML(element, closingTag) {
var i, attr, value, idSeen, result, attributes;
if (closingTag) {
return '</' + element.tagName + '>';
}
result = '<' + element.tagName;
attributes = element.attributes;
for (i = 0; i < attributes.length; ++i) {
attr = attributes[i];
if (attr.name.toLowerCase() === 'id') {
value = createID(element);
idSeen = true;
}
else {
value = attr.value;
}
result += ' ' + attributes[i].name + '="' + value + '"';
}
if (!idSeen) {
result += ' id="' + createID(element) + '"';
}
result += '>';
return result;
}
/**
* Replaces all relative URLs (in images, links etc.) with absolute URLs
* @param element
*/
/* Example usages of 'relativeURLsToAbsoluteURLs' are shown below:
relativeURLsToAbsoluteURLs(descendant);
*/
function relativeURLsToAbsoluteURLs(element) {
switch (element.nodeName) {
case 'A':
case 'AREA':
case 'LINK':
case 'BASE':
if (element.hasAttribute('href')) {
element.setAttribute('href', element.href);
}
break;
case 'IMG':
case 'IFRAME':
case 'INPUT':
case 'FRAME':
case 'SCRIPT':
if (element.hasAttribute('src')) {
element.setAttribute('src', element.src);
}
break;
case 'FORM':
if (element.hasAttribute('action')) {
element.setAttribute('action', element.action);
}
break;
}
}
/* Example usages of 'init' are shown below:
init();
*/
function init() {
var css = [], ancestorCss = [], descendants, descendant, htmlSegments, leadingAncestorHtml, trailingAncestorHtml, reverseAncestors = [], i, l, parent, clone;
descendants = root.getElementsByTagName('*');
parent = root.parentElement;
while (parent && parent !== document.body) {
reverseAncestors.push(parent);
parent = parent.parentElement;
}
// First we go through all nodes and dump all CSS
css.push(cssObjectForElement(root));
for (i = 0, l = descendants.length; i < l; i++) {
css.push(cssObjectForElement(descendants[i]));
}
for (i = reverseAncestors.length - 1; i >= 0; i--) {
ancestorCss.push(cssObjectForElement(reverseAncestors[i], true));
}
// Next we dump all HTML and update IDs
// Since we don't want to touch original DOM and we want to change IDs, we clone the original DOM subtree
clone = root.cloneNode(true);
descendants = clone.getElementsByTagName('*');
idCounter = 1;
clone.setAttribute('id', createID(clone));
for (i = 0, l = descendants.length; i < l; i++) {
descendant = descendants[i];
descendant.setAttribute('id', createID(descendant));
relativeURLsToAbsoluteURLs(descendant);
}
// Build leading and trailing HTML for ancestors
htmlSegments = [];
for (i = reverseAncestors.length - 1; i >= 0; i--) {
htmlSegments.push(ancestorTagHTML(reverseAncestors[i]));
}
leadingAncestorHtml = htmlSegments.join('');
htmlSegments = [];
for (i = 0, l = reverseAncestors.length; i < l; i++) {
htmlSegments.push(ancestorTagHTML(reverseAncestors[i], true));
}
trailingAncestorHtml = htmlSegments.join('');
return JSON.stringify({
html: clone.outerHTML,
leadingAncestorHtml: leadingAncestorHtml,
trailingAncestorHtml: trailingAncestorHtml,
css: css,
ancestorCss: ancestorCss
});
}
return init();
}
/**
* Utility that transforms object representing CSS rules to actual CSS code.
*
* @constructor
*/
export function CSSStringifier() {
"use strict";
/* Example usages of 'propertiesToString' are shown below:
output += propertiesToString(style.node);
output += propertiesToString(style.after);
output += propertiesToString(style.before);
html.substring(0, cursor) + // The head of the string
STYLE_ATTRIBUTE + attributeEnclosingChar + // The attribute key
propertiesToString(stylesMap[styleId].node, attributeEnclosingChar) + // The attribute value
attributeEnclosingChar + " " + // Closing the value just before the next attribute
html.substring(cursor);
*/
function propertiesToString(properties) {
var propertyName, output = "";
for (propertyName in properties) {
if (properties.hasOwnProperty(propertyName)) {
output += " " + propertyName + ": " + properties[propertyName] + ";\n";
}
}
return output;
}
/* Example usages of 'printIDs' are shown below:
output += printIDs(style.id) + ' {\n';
output += '}' + printIDs(style.id) + '\n\n';
output += printIDs(style.id, ':after') + ' {\n';
output += '}' + printIDs(style.id, ':after') + '\n\n';
output += printIDs(style.id, ':before') + ' {\n';
output += '}' + printIDs(style.id, ':before') + '\n\n';
*/
function printIDs(ids, pseudoElement) {
var i, l, idString, output = [];
if (!(ids instanceof Array)) {
ids = [ids];
}
for (i = 0, l = ids.length; i < l; i++) {
idString = '#' + ids[i];
if (pseudoElement) {
idString += pseudoElement;
}
output.push(idString);
}
return output.join(', ');
}
this.process = function (styles) {
var i, l, style, output = "";
for (i = 0, l = styles.length; i < l; i++) {
style = styles[i];
output += printIDs(style.id) + ' {\n';
output += propertiesToString(style.node);
output += '}/*' + printIDs(style.id) + '*/\n\n';
if (style.after) {
output += printIDs(style.id, ':after') + ' {\n';
output += propertiesToString(style.after);
output += '}/*' + printIDs(style.id, ':after') + '*/\n\n';
}
if (style.before) {
output += printIDs(style.id, ':before') + ' {\n';
output += propertiesToString(style.before);
output += '}/*' + printIDs(style.id, ':before') + '*/\n\n';
}
}
return output;
};
}
/**
* Injects the CSS into the HTML as Style attributes.
*
* @constructor
*/
export function HTMLStylesCombiner() {
"use strict";
var cursor = 0, stylesMap,
// constants
ATTRIBUTE_ENCLOSING_CHARACTERS = ['"', "'"], ESCAPING_CHARACTER = '\\', ID_ATTRIBUTE = "id=", STYLE_ATTRIBUTE = "style=";
/**
* Looks for the next 'id' attribute inside a tag. Returns -1 if not found.
*/
/* Example usages of 'getNextIdAttributePosition' are shown below:
cursor = getNextIdAttributePosition(html, 0);
cursor = getNextIdAttributePosition(html, cursor);
*/
function getNextIdAttributePosition(html, lastCursor) {
var currentCursor, tagStartCursor, tagEndCursor, idCursor;
while (lastCursor >= 0) {
tagStartCursor = html.indexOf("<", lastCursor);
if (tagStartCursor < 0) {
return -1;
}
tagEndCursor = html.indexOf(">", tagStartCursor);
if (tagEndCursor < 0) {
return -1;
}
currentCursor = tagStartCursor;
do {
idCursor = html.indexOf(ID_ATTRIBUTE, currentCursor);
if (idCursor < 0) {
return -1;
}
else if (ATTRIBUTE_ENCLOSING_CHARACTERS.indexOf(html.charAt(idCursor + ID_ATTRIBUTE.length)) < 0) {
// Not the right 'id=', look for the next
currentCursor++;
}
else if (idCursor < tagEndCursor) {
// Finally!
return idCursor;
}
} while (idCursor < tagEndCursor);
lastCursor = tagEndCursor;
}
}
/**
* Extracts the attribute value that is in the current position.
* @param html the text to extract from.
* @param attributeEnclosingChar the string/character that encloses the value.
* @returns {*} The value that relates to the closest attribute, or null if not found.
*/
/* Example usages of 'extractValueInCurrentPosition' are shown below:
currentId = extractValueInCurrentPosition(html, attributeEnclosingChar);
*/
function extractValueInCurrentPosition(html, attributeEnclosingChar) {
var idStartIndex, idEndIndex;
idStartIndex = html.indexOf(attributeEnclosingChar, cursor) + 1;
idEndIndex = html.indexOf(attributeEnclosingChar, idStartIndex + 1);
if (idStartIndex < 0 || idEndIndex < 0) {
return null;
}
return html.substring(idStartIndex, idEndIndex);
}
/**
* Converts SnappySnippet's CSS object into a string of CSS properties.
* @param properties The CSS object to extort.
* @param attributeEnclosingChar The string/character that encloses values.
* @returns {string} CSS properties contained in the given object.
*/
/* Example usages of 'propertiesToString' are shown below:
output += propertiesToString(style.node);
output += propertiesToString(style.after);
output += propertiesToString(style.before);
html.substring(0, cursor) + // The head of the string
STYLE_ATTRIBUTE + attributeEnclosingChar + // The attribute key
propertiesToString(stylesMap[styleId].node, attributeEnclosingChar) + // The attribute value
attributeEnclosingChar + " " + // Closing the value just before the next attribute
html.substring(cursor);
*/
function propertiesToString(properties, attributeEnclosingChar) {
var propertyName, output = "";
for (propertyName in properties) {
if (properties.hasOwnProperty(propertyName)) {
// Treat those special url() functionals, that sometimes have quotation marks although they are not required
var propertyValue = properties[propertyName].replace(/url\("(.*)"\)/g, "url($1)").replace(/url\('(.*)'\)/g, "url($1)")
.replace(attributeEnclosingChar, ESCAPING_CHARACTER + attributeEnclosingChar);
output += propertyName + ": " + propertyValue + "; ";
}
}
return output;
}
/**
* Injects style attribute to the current position in the HTML.
* @param html The text to use.
* @param styleId What key we are currently on.
* @param attributeEnclosingChar The string/character that encloses values.
* @returns {*} the modified string.
*/
/* Example usages of 'insertStyleAtIndex' are shown below:
html = insertStyleAtIndex(html, currentId, attributeEnclosingChar);
*/
function insertStyleAtIndex(html, styleId, attributeEnclosingChar) {
var cssStyles = stylesMap[styleId] && stylesMap[styleId].node;
if (!cssStyles) {
return html;
}
return html.substring(0, cursor) + // The head of the string
STYLE_ATTRIBUTE + attributeEnclosingChar + // The attribute key
propertiesToString(stylesMap[styleId].node, attributeEnclosingChar) + // The attribute value
attributeEnclosingChar + " " + // Closing the value just before the next attribute
html.substring(cursor); // The tail of the string
}
this.process = function (html, styles) {
var currentId, attributeEnclosingChar;
// Sanity check
if (Boolean(html) && Boolean(styles)) {
// Prepare a lookup dictionary of styles by the respective element id
stylesMap = styles.map(function (styleObj) {
var keyValuePair = {};
keyValuePair[styleObj.id] = styleObj;
return keyValuePair;
}).reduce(function (mergedObj, currentObj) {
return Object.assign(mergedObj, currentObj); //$.extend(mergedObj, currentObj);
});
cursor = getNextIdAttributePosition(html, 0);
while (cursor >= 0) {
// Make use of the fact that attribute value is always enclosed with the same char (either " or ')
attributeEnclosingChar = html.charAt(cursor + ID_ATTRIBUTE.length);
currentId = extractValueInCurrentPosition(html, attributeEnclosingChar);
if (currentId === null)
break;
html = insertStyleAtIndex(html, currentId, attributeEnclosingChar);
cursor = getNextIdAttributePosition(html, cursor);
}
}
return html;
};
}
|
71559fc424d8ed8c2e6b4b0cd7587a54599ddf5b | 3,672 | ts | TypeScript | packages/crypto/src/hashes/curl.ts | eike-hass/iota.js | 18ddf1ab7ffdd2ef59c6b345fe9ec70a4629bb48 | [
"Apache-2.0"
] | 1 | 2022-02-27T05:28:41.000Z | 2022-02-27T05:28:41.000Z | packages/crypto/src/hashes/curl.ts | eike-hass/iota.js | 18ddf1ab7ffdd2ef59c6b345fe9ec70a4629bb48 | [
"Apache-2.0"
] | null | null | null | packages/crypto/src/hashes/curl.ts | eike-hass/iota.js | 18ddf1ab7ffdd2ef59c6b345fe9ec70a4629bb48 | [
"Apache-2.0"
] | null | null | null | // Copyright 2020 IOTA Stiftung
// SPDX-License-Identifier: Apache-2.0
/* eslint-disable no-bitwise */
/**
* Class to implement Curl sponge.
*/
export class Curl {
/**
* The Hash Length.
*/
public static readonly HASH_LENGTH: number = 243;
/**
* The State Length.
*/
public static readonly STATE_LENGTH: number = 3 * Curl.HASH_LENGTH;
/**
* The default number of rounds.
* @internal
*/
private static readonly NUMBER_OF_ROUNDS: number = 81;
/**
* Truth Table.
* @internal
*/
private static readonly TRUTH_TABLE: number[] = [1, 0, -1, 2, 1, -1, 0, 2, -1, 1, 0];
/**
* The number of rounds.
* @internal
*/
private readonly _rounds: number;
/**
* The state of the sponge.
* @internal
*/
private _state: Int8Array;
/**
* Create a new instance of Curl.
* @param rounds The number of rounds to perform.
*/
constructor(rounds: number = Curl.NUMBER_OF_ROUNDS) {
if (rounds !== 27 && rounds !== 81) {
throw new Error("Illegal number of rounds. Only `27` and `81` rounds are supported.");
}
this._state = new Int8Array(Curl.STATE_LENGTH);
this._rounds = rounds;
}
/**
* Sponge transform function.
* @param curlState The curl state to transform.
* @param rounds The number of rounds to use.
*/
public static transform(curlState: Int8Array, rounds: number): void {
let stateCopy;
let index = 0;
for (let round = 0; round < rounds; round++) {
stateCopy = curlState.slice();
for (let i = 0; i < Curl.STATE_LENGTH; i++) {
const lastVal = stateCopy[index];
if (index < 365) {
index += 364;
} else {
index -= 365;
}
const nextVal = stateCopy[index] << 2;
curlState[i] = Curl.TRUTH_TABLE[lastVal + nextVal + 5];
}
}
}
/**
* Resets the state.
*/
public reset(): void {
this._state = new Int8Array(Curl.STATE_LENGTH);
}
/**
* Get the state of the sponge.
* @param len The length of the state to get.
* @returns The state.
*/
public rate(len: number = Curl.HASH_LENGTH): Int8Array {
return this._state.slice(0, len);
}
/**
* Absorbs trits given an offset and length.
* @param trits The trits to absorb.
* @param offset The offset to start abororbing from the array.
* @param length The length of trits to absorb.
*/
public absorb(trits: Int8Array, offset: number, length: number): void {
do {
const limit = length < Curl.HASH_LENGTH ? length : Curl.HASH_LENGTH;
this._state.set(trits.subarray(offset, offset + limit));
Curl.transform(this._state, this._rounds);
length -= Curl.HASH_LENGTH;
offset += limit;
} while (length > 0);
}
/**
* Squeezes trits given an offset and length.
* @param trits The trits to squeeze.
* @param offset The offset to start squeezing from the array.
* @param length The length of trits to squeeze.
*/
public squeeze(trits: Int8Array, offset: number, length: number): void {
do {
const limit = length < Curl.HASH_LENGTH ? length : Curl.HASH_LENGTH;
trits.set(this._state.subarray(0, limit), offset);
Curl.transform(this._state, this._rounds);
length -= Curl.HASH_LENGTH;
offset += limit;
} while (length > 0);
}
}
| 27.818182 | 98 | 0.555828 | 56 | 6 | 0 | 10 | 8 | 6 | 1 | 0 | 16 | 1 | 0 | 6 | 1,000 | 0.016 | 0.008 | 0.006 | 0.001 | 0 | 0 | 0.533333 | 0.234785 | // Copyright 2020 IOTA Stiftung
// SPDX-License-Identifier: Apache-2.0
/* eslint-disable no-bitwise */
/**
* Class to implement Curl sponge.
*/
export class Curl {
/**
* The Hash Length.
*/
public static readonly HASH_LENGTH = 243;
/**
* The State Length.
*/
public static readonly STATE_LENGTH = 3 * Curl.HASH_LENGTH;
/**
* The default number of rounds.
* @internal
*/
private static readonly NUMBER_OF_ROUNDS = 81;
/**
* Truth Table.
* @internal
*/
private static readonly TRUTH_TABLE = [1, 0, -1, 2, 1, -1, 0, 2, -1, 1, 0];
/**
* The number of rounds.
* @internal
*/
private readonly _rounds;
/**
* The state of the sponge.
* @internal
*/
private _state;
/**
* Create a new instance of Curl.
* @param rounds The number of rounds to perform.
*/
constructor(rounds = Curl.NUMBER_OF_ROUNDS) {
if (rounds !== 27 && rounds !== 81) {
throw new Error("Illegal number of rounds. Only `27` and `81` rounds are supported.");
}
this._state = new Int8Array(Curl.STATE_LENGTH);
this._rounds = rounds;
}
/**
* Sponge transform function.
* @param curlState The curl state to transform.
* @param rounds The number of rounds to use.
*/
public static transform(curlState, rounds) {
let stateCopy;
let index = 0;
for (let round = 0; round < rounds; round++) {
stateCopy = curlState.slice();
for (let i = 0; i < Curl.STATE_LENGTH; i++) {
const lastVal = stateCopy[index];
if (index < 365) {
index += 364;
} else {
index -= 365;
}
const nextVal = stateCopy[index] << 2;
curlState[i] = Curl.TRUTH_TABLE[lastVal + nextVal + 5];
}
}
}
/**
* Resets the state.
*/
public reset() {
this._state = new Int8Array(Curl.STATE_LENGTH);
}
/**
* Get the state of the sponge.
* @param len The length of the state to get.
* @returns The state.
*/
public rate(len = Curl.HASH_LENGTH) {
return this._state.slice(0, len);
}
/**
* Absorbs trits given an offset and length.
* @param trits The trits to absorb.
* @param offset The offset to start abororbing from the array.
* @param length The length of trits to absorb.
*/
public absorb(trits, offset, length) {
do {
const limit = length < Curl.HASH_LENGTH ? length : Curl.HASH_LENGTH;
this._state.set(trits.subarray(offset, offset + limit));
Curl.transform(this._state, this._rounds);
length -= Curl.HASH_LENGTH;
offset += limit;
} while (length > 0);
}
/**
* Squeezes trits given an offset and length.
* @param trits The trits to squeeze.
* @param offset The offset to start squeezing from the array.
* @param length The length of trits to squeeze.
*/
public squeeze(trits, offset, length) {
do {
const limit = length < Curl.HASH_LENGTH ? length : Curl.HASH_LENGTH;
trits.set(this._state.subarray(0, limit), offset);
Curl.transform(this._state, this._rounds);
length -= Curl.HASH_LENGTH;
offset += limit;
} while (length > 0);
}
}
|
719d8ef7e693a43b35201b8bfe890e01809031ca | 1,676 | ts | TypeScript | src/lib/triangles.ts | We-Gold/identity | 18139b3806117bc81f107c36873cbf8b152ca1c3 | [
"MIT"
] | 1 | 2022-03-11T18:16:32.000Z | 2022-03-11T18:16:32.000Z | src/lib/triangles.ts | We-Gold/identity | 18139b3806117bc81f107c36873cbf8b152ca1c3 | [
"MIT"
] | null | null | null | src/lib/triangles.ts | We-Gold/identity | 18139b3806117bc81f107c36873cbf8b152ca1c3 | [
"MIT"
] | null | null | null | const DEFAULT_AVERAGE_DIVISOR = 2
interface Point {
x: number
y: number
}
// Corners 1 and 3 form the hypotenuse
export interface Triangle {
corner1: Point
corner2: Point
corner3: Point
}
export const makeTriangle = (
x1: number,
y1: number,
x2: number,
y2: number,
x3: number,
y3: number
): Triangle => {
return {
corner1: { x: x1, y: y1 },
corner2: { x: x2, y: y2 },
corner3: { x: x3, y: y3 },
}
}
export const copyTriangle = (triangle: Triangle) => {
return makeTriangle(
triangle.corner1.x,
triangle.corner1.y,
triangle.corner2.x,
triangle.corner2.y,
triangle.corner3.x,
triangle.corner3.y
)
}
const getHypotenuseMidpoint = (
triangle: Triangle,
averageDivisor = DEFAULT_AVERAGE_DIVISOR
): Point => ({
x: average(triangle.corner1.x, triangle.corner3.x, averageDivisor),
y: average(triangle.corner1.y, triangle.corner3.y, averageDivisor),
})
export const lerp = (point1: Point, point2: Point, percent: number) => {
return {
x: lerp1D(point1.x, point2.x, percent),
y: lerp1D(point1.y, point2.y, percent),
}
}
const lerp1D = (x1: number, x2: number, percent: number) =>
x1 + (x2 - x1) * percent
const average = (
x1: number,
x2: number,
averageDivisor = DEFAULT_AVERAGE_DIVISOR
) => (x1 + x2) / averageDivisor
export const splitTriangle = (
triangle: Triangle,
averageDivisor = DEFAULT_AVERAGE_DIVISOR
) => {
const midpoint = getHypotenuseMidpoint(triangle, averageDivisor)
const triangle1 = {
corner1: triangle.corner1,
corner2: midpoint,
corner3: triangle.corner2,
}
const triangle2 = {
corner1: triangle.corner2,
corner2: midpoint,
corner3: triangle.corner3,
}
return [triangle1, triangle2]
}
| 19.717647 | 72 | 0.695107 | 71 | 7 | 0 | 20 | 11 | 5 | 4 | 0 | 14 | 2 | 0 | 5 | 646 | 0.041796 | 0.017028 | 0.00774 | 0.003096 | 0 | 0 | 0.325581 | 0.329087 | const DEFAULT_AVERAGE_DIVISOR = 2
interface Point {
x
y
}
// Corners 1 and 3 form the hypotenuse
export interface Triangle {
corner1
corner2
corner3
}
export /* Example usages of 'makeTriangle' are shown below:
makeTriangle(triangle.corner1.x, triangle.corner1.y, triangle.corner2.x, triangle.corner2.y, triangle.corner3.x, triangle.corner3.y);
*/
const makeTriangle = (
x1,
y1,
x2,
y2,
x3,
y3
) => {
return {
corner1: { x: x1, y: y1 },
corner2: { x: x2, y: y2 },
corner3: { x: x3, y: y3 },
}
}
export const copyTriangle = (triangle) => {
return makeTriangle(
triangle.corner1.x,
triangle.corner1.y,
triangle.corner2.x,
triangle.corner2.y,
triangle.corner3.x,
triangle.corner3.y
)
}
/* Example usages of 'getHypotenuseMidpoint' are shown below:
getHypotenuseMidpoint(triangle, averageDivisor);
*/
const getHypotenuseMidpoint = (
triangle,
averageDivisor = DEFAULT_AVERAGE_DIVISOR
) => ({
x: average(triangle.corner1.x, triangle.corner3.x, averageDivisor),
y: average(triangle.corner1.y, triangle.corner3.y, averageDivisor),
})
export const lerp = (point1, point2, percent) => {
return {
x: lerp1D(point1.x, point2.x, percent),
y: lerp1D(point1.y, point2.y, percent),
}
}
/* Example usages of 'lerp1D' are shown below:
lerp1D(point1.x, point2.x, percent);
lerp1D(point1.y, point2.y, percent);
*/
const lerp1D = (x1, x2, percent) =>
x1 + (x2 - x1) * percent
/* Example usages of 'average' are shown below:
average(triangle.corner1.x, triangle.corner3.x, averageDivisor);
average(triangle.corner1.y, triangle.corner3.y, averageDivisor);
*/
const average = (
x1,
x2,
averageDivisor = DEFAULT_AVERAGE_DIVISOR
) => (x1 + x2) / averageDivisor
export const splitTriangle = (
triangle,
averageDivisor = DEFAULT_AVERAGE_DIVISOR
) => {
const midpoint = getHypotenuseMidpoint(triangle, averageDivisor)
const triangle1 = {
corner1: triangle.corner1,
corner2: midpoint,
corner3: triangle.corner2,
}
const triangle2 = {
corner1: triangle.corner2,
corner2: midpoint,
corner3: triangle.corner3,
}
return [triangle1, triangle2]
}
|
71c579615e5d168e90ad4fba5ce11f8ce54036e8 | 1,370 | ts | TypeScript | libs/shared/utils/template/src/template.ts | TheUnderScorer/time-neko | 9722f64137524081750639f3c4ae359d638a7031 | [
"MIT"
] | null | null | null | libs/shared/utils/template/src/template.ts | TheUnderScorer/time-neko | 9722f64137524081750639f3c4ae359d638a7031 | [
"MIT"
] | 26 | 2022-03-25T20:50:54.000Z | 2022-03-31T13:42:19.000Z | libs/shared/utils/template/src/template.ts | TheUnderScorer/LofiPomodo | 9722f64137524081750639f3c4ae359d638a7031 | [
"MIT"
] | null | null | null | export enum TemplateType {
Braces = 'Braces',
Colon = 'Colon',
}
export type TemplateVariables = Record<
string,
string | number | boolean | undefined
>;
export const applyVariablesToText = (
text: string,
variables: TemplateVariables,
type: TemplateType = TemplateType.Braces
) => {
return Object.entries(variables).reduce((currentText, [key, value]) => {
if (!value || !key) {
return currentText;
}
const regExp = getTemplateRegexByType(key, type);
return currentText.replace(regExp, convertValue(value));
}, text);
};
const convertValue = (value: unknown) => {
switch (typeof value) {
case 'boolean':
return value ? '1' : '0';
case 'function':
case 'number':
case 'string':
return value.toString();
case 'object':
if (Array.isArray(value)) {
return value.join(',');
}
return JSON.stringify(value);
default:
return '';
}
};
export const getTemplateRegexByType = (key: unknown, type: TemplateType) =>
new RegExp(getTextVariableTemplate(key, type), 'g');
export const getTextVariableTemplate = (key: unknown, type: TemplateType) => {
switch (type) {
case TemplateType.Braces:
return `{{${key}}}`;
case TemplateType.Colon:
return `:${key}`;
default:
throw new TypeError(`Invalid template type: ${type}`);
}
};
| 21.40625 | 78 | 0.629197 | 50 | 5 | 0 | 10 | 5 | 0 | 3 | 0 | 8 | 1 | 1 | 7.2 | 354 | 0.042373 | 0.014124 | 0 | 0.002825 | 0.002825 | 0 | 0.4 | 0.319745 | export enum TemplateType {
Braces = 'Braces',
Colon = 'Colon',
}
export type TemplateVariables = Record<
string,
string | number | boolean | undefined
>;
export const applyVariablesToText = (
text,
variables,
type = TemplateType.Braces
) => {
return Object.entries(variables).reduce((currentText, [key, value]) => {
if (!value || !key) {
return currentText;
}
const regExp = getTemplateRegexByType(key, type);
return currentText.replace(regExp, convertValue(value));
}, text);
};
/* Example usages of 'convertValue' are shown below:
currentText.replace(regExp, convertValue(value));
*/
const convertValue = (value) => {
switch (typeof value) {
case 'boolean':
return value ? '1' : '0';
case 'function':
case 'number':
case 'string':
return value.toString();
case 'object':
if (Array.isArray(value)) {
return value.join(',');
}
return JSON.stringify(value);
default:
return '';
}
};
export /* Example usages of 'getTemplateRegexByType' are shown below:
getTemplateRegexByType(key, type);
*/
const getTemplateRegexByType = (key, type) =>
new RegExp(getTextVariableTemplate(key, type), 'g');
export /* Example usages of 'getTextVariableTemplate' are shown below:
new RegExp(getTextVariableTemplate(key, type), 'g');
*/
const getTextVariableTemplate = (key, type) => {
switch (type) {
case TemplateType.Braces:
return `{{${key}}}`;
case TemplateType.Colon:
return `:${key}`;
default:
throw new TypeError(`Invalid template type: ${type}`);
}
};
|
71cab3a7b771d2d9e7ea9f42deccf80aeae73c9e | 1,477 | tsx | TypeScript | src/client/utils/passwordComplexity.tsx | manix84/lite_event_checkin | 428e13981ab55035eb8757312c95f52945e5f4e0 | [
"MIT"
] | null | null | null | src/client/utils/passwordComplexity.tsx | manix84/lite_event_checkin | 428e13981ab55035eb8757312c95f52945e5f4e0 | [
"MIT"
] | 2 | 2022-02-14T19:50:45.000Z | 2022-02-27T20:32:12.000Z | src/client/utils/passwordComplexity.tsx | manix84/lite_event_checkin | 428e13981ab55035eb8757312c95f52945e5f4e0 | [
"MIT"
] | null | null | null |
export enum ComplexityEnum {
STRONG = "strong",
MEDIUM = "medium",
WEAK = "weak",
EMPTY = "empty"
}
const complexities = {
strong: new RegExp(
'(?=.*[a-z])(?=.*[A-Z])(?=.*[0-9])(?=.*[^A-Za-z0-9])(?=.{8,})'
),
medium: new RegExp(
'((?=.*[a-z])(?=.*[A-Z])(?=.*[0-9])(?=.*[^A-Za-z0-9])(?=.{6,}))|((?=.*[a-z])(?=.*[A-Z])(?=.*[^A-Za-z0-9])(?=.{8,}))'
)
};
class PasswordComplexity {
_password: string = '';
_currentComplexity: ComplexityEnum = ComplexityEnum.EMPTY;
updatePassword(password: string) {
this._password = password;
this._checkComplexity();
}
_checkComplexity = (): void => {
if (this._password.length === 0) {
this._currentComplexity = ComplexityEnum.EMPTY;
} else if (this._password.match(complexities.strong)) {
this._currentComplexity = ComplexityEnum.STRONG;
} else if (this._password.match(complexities.medium)) {
this._currentComplexity = ComplexityEnum.MEDIUM;
} else {
this._currentComplexity = ComplexityEnum.WEAK;
}
};
getAlertText = (): string => {
switch (this._currentComplexity) {
case ComplexityEnum.STRONG:
return 'Strong';
case ComplexityEnum.MEDIUM:
return 'Medium';
case ComplexityEnum.WEAK:
return 'Weak';
case ComplexityEnum.EMPTY:
default:
return '';
}
};
getComplexity = (): ComplexityEnum => {
return this._currentComplexity;
};
};
export default PasswordComplexity;
| 25.033898 | 120 | 0.592417 | 50 | 4 | 0 | 1 | 1 | 5 | 0 | 0 | 4 | 1 | 0 | 5.75 | 460 | 0.01087 | 0.002174 | 0.01087 | 0.002174 | 0 | 0 | 0.363636 | 0.20559 |
export enum ComplexityEnum {
STRONG = "strong",
MEDIUM = "medium",
WEAK = "weak",
EMPTY = "empty"
}
const complexities = {
strong: new RegExp(
'(?=.*[a-z])(?=.*[A-Z])(?=.*[0-9])(?=.*[^A-Za-z0-9])(?=.{8,})'
),
medium: new RegExp(
'((?=.*[a-z])(?=.*[A-Z])(?=.*[0-9])(?=.*[^A-Za-z0-9])(?=.{6,}))|((?=.*[a-z])(?=.*[A-Z])(?=.*[^A-Za-z0-9])(?=.{8,}))'
)
};
class PasswordComplexity {
_password = '';
_currentComplexity = ComplexityEnum.EMPTY;
updatePassword(password) {
this._password = password;
this._checkComplexity();
}
_checkComplexity = () => {
if (this._password.length === 0) {
this._currentComplexity = ComplexityEnum.EMPTY;
} else if (this._password.match(complexities.strong)) {
this._currentComplexity = ComplexityEnum.STRONG;
} else if (this._password.match(complexities.medium)) {
this._currentComplexity = ComplexityEnum.MEDIUM;
} else {
this._currentComplexity = ComplexityEnum.WEAK;
}
};
getAlertText = () => {
switch (this._currentComplexity) {
case ComplexityEnum.STRONG:
return 'Strong';
case ComplexityEnum.MEDIUM:
return 'Medium';
case ComplexityEnum.WEAK:
return 'Weak';
case ComplexityEnum.EMPTY:
default:
return '';
}
};
getComplexity = () => {
return this._currentComplexity;
};
};
export default PasswordComplexity;
|
c357008c208ae8300a38c7cf3a54daa262090b67 | 2,182 | ts | TypeScript | problemset/spiral-matrix/index.ts | OUDUIDUI/leet-code | 50e61ce16d1c419ccefc075ae9ead721cdd1cdbb | [
"MIT"
] | 6 | 2022-01-17T03:19:56.000Z | 2022-01-17T05:45:39.000Z | problemset/spiral-matrix/index.ts | OUDUIDUI/leet-code | 50e61ce16d1c419ccefc075ae9ead721cdd1cdbb | [
"MIT"
] | null | null | null | problemset/spiral-matrix/index.ts | OUDUIDUI/leet-code | 50e61ce16d1c419ccefc075ae9ead721cdd1cdbb | [
"MIT"
] | null | null | null | /**
* 模拟
* @desc 时间复杂度 O(mn) 空间复杂度 O(mn)
* @param matrix {number[][]}
* @return {number[]}
*/
export function spiralOrder(matrix: number[][]): number[] {
if (!matrix.length || !matrix[0].length) return []
const rows = matrix.length
const cols = matrix[0].length
const total = rows * cols
// 已经走过的元素
const visited: boolean[][] = new Array(rows)
.fill([])
.map(() => new Array(cols).fill(false))
const ans: number[] = []
// 方向走位
const directions = [
[0, 1],
[1, 0],
[0, -1],
[-1, 0],
]
let directionIndex = 0
let row = 0
let col = 0
for (let i = 0; i < total; i++) {
ans[i] = matrix[row][col]
visited[row][col] = true
// 获取下一个走位
const nextRow = row + directions[directionIndex][0]
const nextCol = col + directions[directionIndex][1]
// 判断是否走到头了
if (
!(
nextRow >= 0
&& nextRow < rows
&& nextCol >= 0
&& nextCol < cols
&& !visited[nextRow][nextCol]
)
) {
// 当到头了,就需要调换方向
directionIndex = (directionIndex + 1) % 4 /* 确保小于4 */
}
// 更新下一个走位
row += directions[directionIndex][0]
col += directions[directionIndex][1]
}
return ans
}
/**
* 按层模拟
* @desc 时间复杂度 O(mn) 空间复杂度 O(1)
* @param matrix {number[][]}
* @return {number[]}
*/
export function spiralOrder2(matrix: number[][]): number[] {
if (!matrix.length || !matrix[0].length) return []
const rows = matrix.length
const cols = matrix[0].length
const ans: number[] = []
// 边界
let left = 0
let right = cols - 1
let top = 0
let bottom = rows - 1
while (left <= right && top <= bottom) {
// 向右走
for (let col = left; col <= right; col++)
ans.push(matrix[top][col])
// 向下走
for (let row = top + 1; row <= bottom; row++)
ans.push(matrix[row][right])
if (left < right && top < bottom) {
// 向左走
for (let col = right - 1; col > left; col--)
ans.push(matrix[bottom][col])
// 向上走
for (let row = bottom; row > top; row--)
ans.push(matrix[row][left])
}
// 更新边界
[left, right, top, bottom] = [left + 1, right - 1, top + 1, bottom - 1]
}
return ans
}
| 20.780952 | 75 | 0.53483 | 63 | 3 | 0 | 2 | 23 | 0 | 0 | 0 | 7 | 0 | 0 | 20 | 752 | 0.006649 | 0.030585 | 0 | 0 | 0 | 0 | 0.25 | 0.285263 | /**
* 模拟
* @desc 时间复杂度 O(mn) 空间复杂度 O(mn)
* @param matrix {number[][]}
* @return {number[]}
*/
export function spiralOrder(matrix) {
if (!matrix.length || !matrix[0].length) return []
const rows = matrix.length
const cols = matrix[0].length
const total = rows * cols
// 已经走过的元素
const visited = new Array(rows)
.fill([])
.map(() => new Array(cols).fill(false))
const ans = []
// 方向走位
const directions = [
[0, 1],
[1, 0],
[0, -1],
[-1, 0],
]
let directionIndex = 0
let row = 0
let col = 0
for (let i = 0; i < total; i++) {
ans[i] = matrix[row][col]
visited[row][col] = true
// 获取下一个走位
const nextRow = row + directions[directionIndex][0]
const nextCol = col + directions[directionIndex][1]
// 判断是否走到头了
if (
!(
nextRow >= 0
&& nextRow < rows
&& nextCol >= 0
&& nextCol < cols
&& !visited[nextRow][nextCol]
)
) {
// 当到头了,就需要调换方向
directionIndex = (directionIndex + 1) % 4 /* 确保小于4 */
}
// 更新下一个走位
row += directions[directionIndex][0]
col += directions[directionIndex][1]
}
return ans
}
/**
* 按层模拟
* @desc 时间复杂度 O(mn) 空间复杂度 O(1)
* @param matrix {number[][]}
* @return {number[]}
*/
export function spiralOrder2(matrix) {
if (!matrix.length || !matrix[0].length) return []
const rows = matrix.length
const cols = matrix[0].length
const ans = []
// 边界
let left = 0
let right = cols - 1
let top = 0
let bottom = rows - 1
while (left <= right && top <= bottom) {
// 向右走
for (let col = left; col <= right; col++)
ans.push(matrix[top][col])
// 向下走
for (let row = top + 1; row <= bottom; row++)
ans.push(matrix[row][right])
if (left < right && top < bottom) {
// 向左走
for (let col = right - 1; col > left; col--)
ans.push(matrix[bottom][col])
// 向上走
for (let row = bottom; row > top; row--)
ans.push(matrix[row][left])
}
// 更新边界
[left, right, top, bottom] = [left + 1, right - 1, top + 1, bottom - 1]
}
return ans
}
|
c358405d1841d33247044d3f419702007ba78670 | 1,806 | ts | TypeScript | utils/perfectBinaryTree.ts | OUDUIDUI/leet-code | 50e61ce16d1c419ccefc075ae9ead721cdd1cdbb | [
"MIT"
] | 6 | 2022-01-17T03:19:56.000Z | 2022-01-17T05:45:39.000Z | utils/perfectBinaryTree.ts | OUDUIDUI/leet-code | 50e61ce16d1c419ccefc075ae9ead721cdd1cdbb | [
"MIT"
] | null | null | null | utils/perfectBinaryTree.ts | OUDUIDUI/leet-code | 50e61ce16d1c419ccefc075ae9ead721cdd1cdbb | [
"MIT"
] | null | null | null | // 完美二叉树
export class Node {
val: number
left: Node | null
right: Node | null
next: Node | null
constructor(val?: number, left?: Node, right?: Node, next?: Node) {
this.val = val === undefined ? 0 : val
this.left = left === undefined ? null : left
this.right = right === undefined ? null : right
this.next = next === undefined ? null : next
}
}
export function createBinaryTree(array: (number | null)[]): Node | null {
if (!array.length || array[0] === null) return null
const rootTree = new Node(array.shift()!)
const queue: Node[] = [rootTree]
while (array.length) {
const tree = queue.pop()!
const num1 = array.shift()
if (num1) {
tree.left = new Node(num1)
queue.unshift(tree.left)
}
const num2 = array.shift()
if (num2) {
tree.right = new Node(num2)
queue.unshift(tree.right)
}
}
return rootTree
}
export function createPerfectBinaryTree(
array: (number | '#' | null)[],
): Node | null {
if (!array.length || array[0] === null) return null
const rootTree = new Node(array.shift() as number)
const queue: Node[] = [rootTree]
const nextQueue: Node[] = [rootTree]
while (array.length) {
const item = array.shift()
if (item === '#') {
while (nextQueue.length) {
const node1 = nextQueue.pop()!
node1.next = nextQueue.length ? nextQueue[nextQueue.length - 1] : null
}
}
else {
const node = queue.pop()!
if (item) {
node.left = new Node(item)
queue.unshift(node.left)
nextQueue.unshift(node.left)
}
const item2 = array.shift() as number
if (item2) {
node.right = new Node(item2)
queue.unshift(node.right)
nextQueue.unshift(node.right)
}
}
}
return rootTree
}
| 24.405405 | 78 | 0.586932 | 63 | 3 | 0 | 6 | 12 | 4 | 0 | 0 | 6 | 1 | 2 | 16.333333 | 531 | 0.016949 | 0.022599 | 0.007533 | 0.001883 | 0.003766 | 0 | 0.24 | 0.285743 | // 完美二叉树
export class Node {
val
left
right
next
constructor(val?, left?, right?, next?) {
this.val = val === undefined ? 0 : val
this.left = left === undefined ? null : left
this.right = right === undefined ? null : right
this.next = next === undefined ? null : next
}
}
export function createBinaryTree(array) {
if (!array.length || array[0] === null) return null
const rootTree = new Node(array.shift()!)
const queue = [rootTree]
while (array.length) {
const tree = queue.pop()!
const num1 = array.shift()
if (num1) {
tree.left = new Node(num1)
queue.unshift(tree.left)
}
const num2 = array.shift()
if (num2) {
tree.right = new Node(num2)
queue.unshift(tree.right)
}
}
return rootTree
}
export function createPerfectBinaryTree(
array,
) {
if (!array.length || array[0] === null) return null
const rootTree = new Node(array.shift() as number)
const queue = [rootTree]
const nextQueue = [rootTree]
while (array.length) {
const item = array.shift()
if (item === '#') {
while (nextQueue.length) {
const node1 = nextQueue.pop()!
node1.next = nextQueue.length ? nextQueue[nextQueue.length - 1] : null
}
}
else {
const node = queue.pop()!
if (item) {
node.left = new Node(item)
queue.unshift(node.left)
nextQueue.unshift(node.left)
}
const item2 = array.shift() as number
if (item2) {
node.right = new Node(item2)
queue.unshift(node.right)
nextQueue.unshift(node.right)
}
}
}
return rootTree
}
|
c38752012af85acf631b1098996b211efd12d596 | 2,728 | ts | TypeScript | src/filters/core/convert.ts | MahmoudAboelazm/image-editor-pwa | 768d423e43ccee07789d08914caff6aef2935368 | [
"MIT"
] | null | null | null | src/filters/core/convert.ts | MahmoudAboelazm/image-editor-pwa | 768d423e43ccee07789d08914caff6aef2935368 | [
"MIT"
] | 3 | 2022-01-22T04:31:47.000Z | 2022-03-30T02:26:53.000Z | src/filters/core/convert.ts | MahmoudAboelazm/image-editor-pwa | 768d423e43ccee07789d08914caff6aef2935368 | [
"MIT"
] | null | null | null | export default class Convert {
// Converts the hex representation of a color to RGB values.
// Hex value can optionally start with the hash (#).
//
// @param [String] hex The colors hex value
// @return [Array] The RGB representation
hexToRGB(hex) {
if (hex.charAt(0) === "#") {
hex = hex.substr(1);
}
const r = parseInt(hex.substr(0, 2), 16);
const g = parseInt(hex.substr(2, 2), 16);
const b = parseInt(hex.substr(4, 2), 16);
return { r, g, b };
}
// Converts an RGB color value to HSV. Conversion formula
// adapted from {http://en.wikipedia.org/wiki/HSV_color_space}.
// Assumes r, g, and b are contained in the set [0, 255] and
// returns h, s, and v in the set [0, 1].
//
// @param [Number] r The red color value
// @param [Number] g The green color value
// @param [Number] b The blue color value
// @return [Array] The HSV representation
rgbToHSV(r, g, b) {
let h;
r /= 255;
g /= 255;
b /= 255;
const max = Math.max(r, g, b);
const min = Math.min(r, g, b);
const v = max;
const d = max - min;
const s = max === 0 ? 0 : d / max;
if (max === min) {
h = 0;
} else {
h = (() => {
switch (max) {
case r:
return (g - b) / d + (g < b ? 6 : 0);
case g:
return (b - r) / d + 2;
case b:
return (r - g) / d + 4;
}
})();
h /= 6;
}
return { h, s, v };
}
// Converts an HSV color value to RGB. Conversion formula
// adapted from http://en.wikipedia.org/wiki/HSV_color_space.
// Assumes h, s, and v are contained in the set [0, 1] and
// returns r, g, and b in the set [0, 255].
//
// @param [Number] h The hue
// @param [Number] s The saturation
// @param [Number] v The value
// @return [Array] The RGB representation
hsvToRGB(h, s, v) {
let b, g, r;
const i = Math.floor(h * 6);
const f = h * 6 - i;
const p = v * (1 - s);
const q = v * (1 - f * s);
const t = v * (1 - (1 - f) * s);
switch (i % 6) {
case 0:
r = v;
g = t;
b = p;
break;
case 1:
r = q;
g = v;
b = p;
break;
case 2:
r = p;
g = v;
b = t;
break;
case 3:
r = p;
g = q;
b = v;
break;
case 4:
r = t;
g = p;
b = v;
break;
case 5:
r = v;
g = p;
b = q;
break;
}
return {
r: Math.floor(r * 255),
g: Math.floor(g * 255),
b: Math.floor(b * 255),
};
}
}
| 23.316239 | 65 | 0.450147 | 83 | 4 | 0 | 7 | 17 | 0 | 0 | 0 | 0 | 1 | 0 | 20.75 | 915 | 0.012022 | 0.018579 | 0 | 0.001093 | 0 | 0 | 0 | 0.260693 | export default class Convert {
// Converts the hex representation of a color to RGB values.
// Hex value can optionally start with the hash (#).
//
// @param [String] hex The colors hex value
// @return [Array] The RGB representation
hexToRGB(hex) {
if (hex.charAt(0) === "#") {
hex = hex.substr(1);
}
const r = parseInt(hex.substr(0, 2), 16);
const g = parseInt(hex.substr(2, 2), 16);
const b = parseInt(hex.substr(4, 2), 16);
return { r, g, b };
}
// Converts an RGB color value to HSV. Conversion formula
// adapted from {http://en.wikipedia.org/wiki/HSV_color_space}.
// Assumes r, g, and b are contained in the set [0, 255] and
// returns h, s, and v in the set [0, 1].
//
// @param [Number] r The red color value
// @param [Number] g The green color value
// @param [Number] b The blue color value
// @return [Array] The HSV representation
rgbToHSV(r, g, b) {
let h;
r /= 255;
g /= 255;
b /= 255;
const max = Math.max(r, g, b);
const min = Math.min(r, g, b);
const v = max;
const d = max - min;
const s = max === 0 ? 0 : d / max;
if (max === min) {
h = 0;
} else {
h = (() => {
switch (max) {
case r:
return (g - b) / d + (g < b ? 6 : 0);
case g:
return (b - r) / d + 2;
case b:
return (r - g) / d + 4;
}
})();
h /= 6;
}
return { h, s, v };
}
// Converts an HSV color value to RGB. Conversion formula
// adapted from http://en.wikipedia.org/wiki/HSV_color_space.
// Assumes h, s, and v are contained in the set [0, 1] and
// returns r, g, and b in the set [0, 255].
//
// @param [Number] h The hue
// @param [Number] s The saturation
// @param [Number] v The value
// @return [Array] The RGB representation
hsvToRGB(h, s, v) {
let b, g, r;
const i = Math.floor(h * 6);
const f = h * 6 - i;
const p = v * (1 - s);
const q = v * (1 - f * s);
const t = v * (1 - (1 - f) * s);
switch (i % 6) {
case 0:
r = v;
g = t;
b = p;
break;
case 1:
r = q;
g = v;
b = p;
break;
case 2:
r = p;
g = v;
b = t;
break;
case 3:
r = p;
g = q;
b = v;
break;
case 4:
r = t;
g = p;
b = v;
break;
case 5:
r = v;
g = p;
b = q;
break;
}
return {
r: Math.floor(r * 255),
g: Math.floor(g * 255),
b: Math.floor(b * 255),
};
}
}
|
c39329f4bcf1964406669ff9c8cc4acf8abf7462 | 1,429 | ts | TypeScript | src/utils/format_time.ts | NewtTheWolf/TieCMS | 878db4ceda24e9c61f13f8c1d739e8d14ff255f9 | [
"Apache-2.0"
] | 23 | 2022-01-23T19:01:48.000Z | 2022-02-14T16:25:00.000Z | src/utils/format_time.ts | MiraibiitwitchDE/TieCMS | 878db4ceda24e9c61f13f8c1d739e8d14ff255f9 | [
"Apache-2.0"
] | 15 | 2022-02-01T20:24:47.000Z | 2022-02-01T21:33:10.000Z | src/utils/format_time.ts | MiraibiitwitchDE/TieCMS | 878db4ceda24e9c61f13f8c1d739e8d14ff255f9 | [
"Apache-2.0"
] | 1 | 2022-02-03T04:28:47.000Z | 2022-02-03T04:28:47.000Z | export function formatTime(ms: number) {
let remaining = ms;
let times = [];
let result = null;
const days = Math.floor(remaining / 1000 / 60 / 60 / 24);
if (days > 0) {
remaining -= days * 1000 * 60 * 60 * 24;
times.push(`${days} day${days > 1 ? "s" : ""}`);
}
const hours = Math.floor(remaining / 1000 / 60 / 60);
if (hours > 0) {
remaining -= hours * 1000 * 60 * 60;
times.push(`${hours} hour${hours > 1 ? "s" : ""}`);
}
const minutes = Math.floor(remaining / 1000 / 60);
if (minutes > 0) {
remaining -= minutes * 1000 * 60;
times.push(`${minutes} minute${minutes > 1 ? "s" : ""}`);
}
const seconds = Math.floor(remaining / 1000);
if (seconds > 0) {
remaining -= seconds * 1000;
times.push(`${seconds} second${seconds > 1 ? "s" : ""}`);
}
ms = Math.floor(remaining);
times = times.reverse();
switch (times.length) {
case 0:
result = `${ms}ms`;
break;
case 1:
result = `${times[0]}`;
break;
case 2:
result = `${times[1]} and ${times[0]}`;
break;
case 3:
result = `${times[2]}, ${times[1]} and ${times[0]}`;
break;
case 4:
result = `${times[3]}, ${times[2]}, ${times[1]} and ${times[0]}`;
break;
}
return result;
}
export function formatDate(date: any) {
return (
date.getDate() +
" " +
new Intl.DateTimeFormat("en", { month: "short" }).format(date)
);
}
| 24.637931 | 71 | 0.525542 | 52 | 2 | 0 | 2 | 7 | 0 | 0 | 1 | 1 | 0 | 0 | 24 | 504 | 0.007937 | 0.013889 | 0 | 0 | 0 | 0.090909 | 0.090909 | 0.23249 | export function formatTime(ms) {
let remaining = ms;
let times = [];
let result = null;
const days = Math.floor(remaining / 1000 / 60 / 60 / 24);
if (days > 0) {
remaining -= days * 1000 * 60 * 60 * 24;
times.push(`${days} day${days > 1 ? "s" : ""}`);
}
const hours = Math.floor(remaining / 1000 / 60 / 60);
if (hours > 0) {
remaining -= hours * 1000 * 60 * 60;
times.push(`${hours} hour${hours > 1 ? "s" : ""}`);
}
const minutes = Math.floor(remaining / 1000 / 60);
if (minutes > 0) {
remaining -= minutes * 1000 * 60;
times.push(`${minutes} minute${minutes > 1 ? "s" : ""}`);
}
const seconds = Math.floor(remaining / 1000);
if (seconds > 0) {
remaining -= seconds * 1000;
times.push(`${seconds} second${seconds > 1 ? "s" : ""}`);
}
ms = Math.floor(remaining);
times = times.reverse();
switch (times.length) {
case 0:
result = `${ms}ms`;
break;
case 1:
result = `${times[0]}`;
break;
case 2:
result = `${times[1]} and ${times[0]}`;
break;
case 3:
result = `${times[2]}, ${times[1]} and ${times[0]}`;
break;
case 4:
result = `${times[3]}, ${times[2]}, ${times[1]} and ${times[0]}`;
break;
}
return result;
}
export function formatDate(date) {
return (
date.getDate() +
" " +
new Intl.DateTimeFormat("en", { month: "short" }).format(date)
);
}
|
c39a87b644970d56d81830bc23d2468ddd1d7f7b | 3,842 | ts | TypeScript | src/utils/string/string.ts | arasekinci/begonya | 862e5bac37eb814e3378b3b9c6d5ce160c8ed8df | [
"MIT"
] | 3 | 2022-02-04T13:28:38.000Z | 2022-03-30T17:35:50.000Z | src/utils/string/string.ts | arasekinci/mandalina | 862e5bac37eb814e3378b3b9c6d5ce160c8ed8df | [
"MIT"
] | null | null | null | src/utils/string/string.ts | arasekinci/mandalina | 862e5bac37eb814e3378b3b9c6d5ce160c8ed8df | [
"MIT"
] | null | null | null | /**
* The truncate() method truncates the text from a full word.
*
* @param str A String that specifies the text you want to shorten
* @param limit A Number to limit the text character size
* @returns A truncated or empty string
*/
export const truncate = (str: string, limit = 140): string => {
if (str) {
const end = str.indexOf(' ', limit)
if (end >= 0) {
return str.substring(0, end) + '...'
}
return str
}
return ''
}
/**
* The escape() method clears the special characters in the text.
*
* @param str A String specifying the text you want to clear
* @returns A cleared or empty string
*/
export const escape = (str: string): string => {
if (str) {
return str
.trim()
.replace(/\s+/g, ' ')
.replace(/[^a-zA-Z0-9 ".',?]/g, '')
}
return ''
}
/**
* The slugify() method cleans and fixes by text URL pathname.
*
* @param str A String specifying the text you want to convert
* @returns A slugified or empty string
*/
export const slugify = (str: string): string => {
if (str) {
return str
.replace(/[^a-zA-Z0-9 ]/g, '')
.replace(/\s+/g, '-')
.toLowerCase()
}
return ''
}
/**
* The capitalize() method capitalizes the first letter of text and lowers the rest.
*
* @param str A String specifying the text you want to convert
* @returns A capitalized or empty string
*/
export const capitalize = (str: string): string => {
if (str) {
return escape(str).charAt(0).toUpperCase() + str.slice(1).toLowerCase()
}
return ''
}
/**
*The lowercase() method will reduce all words in the text.
*
* @param str A String specifying the text you want to convert
* @returns A lowercase or empty string
*/
export const lowercase = (str: string): string => {
if (str) {
return escape(str).toLowerCase()
}
return ''
}
/**
* The uppercase() method capitalizes all words in the text and converts spaces to underscores.
*
* @param str A String specifying the text you want to convert
* @returns A uppercase or empty string
*/
export const uppercase = (str: string): string => {
if (str) {
return escape(str).toUpperCase()
}
return ''
}
/**
* The camelcase() method reduces the first letter of the text
* and capitalizes the first letter of each remaining word.
*
* @param str A String specifying the text you want to convert
* @returns A camelcase or empty string
*/
export const camelcase = (str: string): string => {
if (str) {
return slugify(str)
.split('-')
.map((word, index) => {
if (index) {
return capitalize(word)
}
return word.toLowerCase()
})
.join('')
}
return ''
}
/**
* The camelcase() method capitalizes the first letter of each word of the text.
*
* @param str A String specifying the text you want to convert
* @returns A pascalcase or empty string
*/
export const pascalcase = (str: string): string => {
if (str) {
return slugify(str)
.split('-')
.map((word) => capitalize(word))
.join('')
}
return ''
}
/**
* The kebabcase() method shrinks all words in the text and converts spaces to hyphens.
*
* @param str A String specifying the text you want to convert
* @returns A kebabcase or empty string
*/
export const kebabcase = (str: string): string => {
if (str) {
return slugify(str).toLowerCase()
}
return ''
}
/**
* The snakecase() method shrinks all words in the text and converts spaces to underscore.
*
* @param str A String specifying the text you want to convert
* @returns A snakecase or empty string
*/
export const snakecase = (str: string, uppercase?: boolean): string => {
if (str) {
const snake = slugify(str).replace(/-/g, '_')
if (uppercase) {
return snake.toUpperCase()
}
return snake
}
return ''
}
| 21.10989 | 95 | 0.626497 | 85 | 12 | 0 | 15 | 12 | 0 | 3 | 0 | 21 | 0 | 0 | 5.833333 | 1,053 | 0.025641 | 0.011396 | 0 | 0 | 0 | 0 | 0.538462 | 0.267343 | /**
* The truncate() method truncates the text from a full word.
*
* @param str A String that specifies the text you want to shorten
* @param limit A Number to limit the text character size
* @returns A truncated or empty string
*/
export const truncate = (str, limit = 140) => {
if (str) {
const end = str.indexOf(' ', limit)
if (end >= 0) {
return str.substring(0, end) + '...'
}
return str
}
return ''
}
/**
* The escape() method clears the special characters in the text.
*
* @param str A String specifying the text you want to clear
* @returns A cleared or empty string
*/
export /* Example usages of 'escape' are shown below:
escape(str).charAt(0).toUpperCase() + str.slice(1).toLowerCase();
escape(str).toLowerCase();
escape(str).toUpperCase();
*/
const escape = (str) => {
if (str) {
return str
.trim()
.replace(/\s+/g, ' ')
.replace(/[^a-zA-Z0-9 ".',?]/g, '')
}
return ''
}
/**
* The slugify() method cleans and fixes by text URL pathname.
*
* @param str A String specifying the text you want to convert
* @returns A slugified or empty string
*/
export /* Example usages of 'slugify' are shown below:
slugify(str)
.split('-')
.map((word, index) => {
if (index) {
return capitalize(word);
}
return word.toLowerCase();
})
.join('');
slugify(str)
.split('-')
.map((word) => capitalize(word))
.join('');
slugify(str).toLowerCase();
slugify(str).replace(/-/g, '_');
*/
const slugify = (str) => {
if (str) {
return str
.replace(/[^a-zA-Z0-9 ]/g, '')
.replace(/\s+/g, '-')
.toLowerCase()
}
return ''
}
/**
* The capitalize() method capitalizes the first letter of text and lowers the rest.
*
* @param str A String specifying the text you want to convert
* @returns A capitalized or empty string
*/
export /* Example usages of 'capitalize' are shown below:
capitalize(word);
*/
const capitalize = (str) => {
if (str) {
return escape(str).charAt(0).toUpperCase() + str.slice(1).toLowerCase()
}
return ''
}
/**
*The lowercase() method will reduce all words in the text.
*
* @param str A String specifying the text you want to convert
* @returns A lowercase or empty string
*/
export const lowercase = (str) => {
if (str) {
return escape(str).toLowerCase()
}
return ''
}
/**
* The uppercase() method capitalizes all words in the text and converts spaces to underscores.
*
* @param str A String specifying the text you want to convert
* @returns A uppercase or empty string
*/
export /* Example usages of 'uppercase' are shown below:
;
*/
const uppercase = (str) => {
if (str) {
return escape(str).toUpperCase()
}
return ''
}
/**
* The camelcase() method reduces the first letter of the text
* and capitalizes the first letter of each remaining word.
*
* @param str A String specifying the text you want to convert
* @returns A camelcase or empty string
*/
export const camelcase = (str) => {
if (str) {
return slugify(str)
.split('-')
.map((word, index) => {
if (index) {
return capitalize(word)
}
return word.toLowerCase()
})
.join('')
}
return ''
}
/**
* The camelcase() method capitalizes the first letter of each word of the text.
*
* @param str A String specifying the text you want to convert
* @returns A pascalcase or empty string
*/
export const pascalcase = (str) => {
if (str) {
return slugify(str)
.split('-')
.map((word) => capitalize(word))
.join('')
}
return ''
}
/**
* The kebabcase() method shrinks all words in the text and converts spaces to hyphens.
*
* @param str A String specifying the text you want to convert
* @returns A kebabcase or empty string
*/
export const kebabcase = (str) => {
if (str) {
return slugify(str).toLowerCase()
}
return ''
}
/**
* The snakecase() method shrinks all words in the text and converts spaces to underscore.
*
* @param str A String specifying the text you want to convert
* @returns A snakecase or empty string
*/
export const snakecase = (str, uppercase?) => {
if (str) {
const snake = slugify(str).replace(/-/g, '_')
if (uppercase) {
return snake.toUpperCase()
}
return snake
}
return ''
}
|
c3a638642c61e9f2f6f40ae6a71cdbf67fc9c4a0 | 6,275 | ts | TypeScript | src/compression/LZSS_LBA_type_2.ts | LBALab/hqr | 1ec3361283e0efbc8159c633580f538ae3c49e2f | [
"MIT"
] | 1 | 2022-01-25T13:12:22.000Z | 2022-01-25T13:12:22.000Z | src/compression/LZSS_LBA_type_2.ts | LBALab/hqr | 1ec3361283e0efbc8159c633580f538ae3c49e2f | [
"MIT"
] | 1 | 2022-01-25T01:30:08.000Z | 2022-01-25T01:58:58.000Z | src/compression/LZSS_LBA_type_2.ts | LBALab/hqr | 1ec3361283e0efbc8159c633580f538ae3c49e2f | [
"MIT"
] | null | null | null | const INDEX_BIT_COUNT = 12;
const LENGTH_BIT_COUNT = 4;
const RAW_LOOK_AHEAD_SIZE = 1 << LENGTH_BIT_COUNT;
const MAX_OFFSET = (1 << INDEX_BIT_COUNT) + 1;
const TREE_ROOT = MAX_OFFSET;
const UNUSED = -1;
enum Child {
Smaller = 0,
Larger = 1,
}
interface DefTree {
parent: number;
children: [number, number];
which_child: number;
}
const tree: DefTree[] = (() => {
const t = new Array<DefTree>(MAX_OFFSET + 2);
for (let i = 0; i < t.length; i++) {
t[i] = { parent: 0, children: [0, 0], which_child: 0 };
}
return t;
})();
function initTree() {
tree[0].parent = 0;
tree[0].children[0] = 0;
tree[0].children[1] = 0;
tree[0].which_child = 0;
for (let i = 1; i < tree.length; i++) {
tree[i].parent = UNUSED;
tree[i].children[0] = UNUSED;
tree[i].children[1] = UNUSED;
tree[i].which_child = UNUSED;
}
}
function copyNode(src: number, tgt: number) {
tree[tgt].parent = tree[src].parent;
tree[tgt].children[0] = tree[src].children[0];
tree[tgt].children[1] = tree[src].children[1];
tree[tgt].which_child = tree[src].which_child;
}
function replaceParents(node: number) {
tree[tree[node + 1].children[Child.Smaller] + 1].parent = node;
tree[tree[node + 1].children[Child.Larger] + 1].parent = node;
}
function replace_node(old_node: number, new_node: number) {
copyNode(old_node + 1, new_node + 1);
replaceParents(new_node);
tree[tree[old_node + 1].parent + 1].children[tree[old_node + 1].which_child] =
new_node;
}
function updateParent(node: number, parent: number, which_child: number) {
tree[node + 1].parent = parent;
tree[node + 1].which_child = which_child;
}
function findNextNode(node: number): number {
let next = tree[node + 1].children[Child.Smaller];
if (tree[next + 1].children[Child.Larger] === UNUSED)
tree[node + 1].children[Child.Smaller] =
tree[next + 1].children[Child.Smaller];
else {
while (tree[next + 1].children[Child.Larger] !== UNUSED)
next = tree[next + 1].children[Child.Larger];
tree[tree[next + 1].parent + 1].children[Child.Larger] =
tree[next + 1].children[Child.Smaller];
}
return next;
}
function updateChild(src_tree: number, which_child: number) {
if (tree[src_tree + 1].children[which_child] !== UNUSED)
updateParent(
tree[src_tree + 1].children[which_child],
tree[src_tree + 1].parent,
tree[src_tree + 1].which_child
);
tree[tree[src_tree + 1].parent + 1].children[tree[src_tree + 1].which_child] =
tree[src_tree + 1].children[which_child];
}
// Adapted from:
// https://github.com/OBattler/lbatools-c/blob/master/compress/lzmit.c
export function compressLZSS_LBA_type_2(data: ArrayBuffer): ArrayBuffer {
let val = 0;
let src_off = 0;
let out_len = 1;
let offset_off = 0;
let flag_bit = 0;
let best_match = 1;
let best_node = 0;
const length = data.byteLength;
if (length <= RAW_LOOK_AHEAD_SIZE) {
return data;
}
const input = new Uint8Array(data);
const output = new Uint8Array(length);
initTree();
while (best_match + src_off - 1 < length) {
let i = best_match;
while (i > 0) {
const src_tree = src_off % MAX_OFFSET;
if (tree[src_tree + 1].parent !== UNUSED) {
if (
tree[src_tree + 1].children[Child.Smaller] !== UNUSED &&
tree[src_tree + 1].children[Child.Larger] !== UNUSED
) {
const replacement = findNextNode(src_tree);
updateParent(
tree[replacement + 1].children[Child.Smaller],
tree[replacement + 1].parent,
tree[replacement + 1].which_child
);
replace_node(src_tree, replacement);
} else {
updateChild(
src_tree,
tree[src_tree + 1].children[Child.Smaller] === UNUSED
? Child.Larger
: Child.Smaller
);
}
}
tree[src_tree + 1].children[Child.Larger] = UNUSED;
tree[src_tree + 1].children[Child.Smaller] = UNUSED;
let cur_node = tree[TREE_ROOT + 1].children[Child.Smaller];
if (cur_node < 0) {
best_match = 0;
best_node = 0;
updateParent(src_tree, TREE_ROOT, 0);
tree[TREE_ROOT + 1].children[Child.Smaller] = src_tree;
} else {
best_match = 2;
// eslint-disable-next-line no-constant-condition
while (true) {
let cur_string = src_off;
let cmp_string =
cur_string - ((src_tree - cur_node + MAX_OFFSET) % MAX_OFFSET);
const node = cur_node;
let j = RAW_LOOK_AHEAD_SIZE + 2;
cur_node = j - 1;
let diff: number;
do diff = input[cur_string++] - input[cmp_string++];
while (--j !== 0 && diff === 0);
if (j !== 0 || diff !== 0) {
cur_node -= j;
if (cur_node > best_match) {
best_match = cur_node;
best_node = node;
}
j = diff >= 0 ? 1 : 0;
cur_node = tree[node + 1].children[j];
if (cur_node < 0) {
updateParent(src_tree, node, j);
tree[node + 1].children[j] = src_tree;
break;
}
} else {
replace_node(node, src_tree);
tree[node + 1].parent = UNUSED;
best_match = RAW_LOOK_AHEAD_SIZE + 2;
best_node = node;
break;
}
}
}
if (--i > 0) src_off++;
}
if (out_len >= length - RAW_LOOK_AHEAD_SIZE - 1) {
return data;
}
val >>= 1;
if (best_match > 2 && src_off + best_match <= length) {
const temp =
(best_match - 3) |
((src_off - best_node - 1 + MAX_OFFSET) % MAX_OFFSET <<
LENGTH_BIT_COUNT);
output[out_len] = temp & 0xff;
output[out_len + 1] = temp >> 8;
out_len += 2;
} else {
output[out_len++] = input[src_off];
val |= 0x80;
best_match = 1;
}
flag_bit++;
if (flag_bit >= 8) {
flag_bit = 0;
output[offset_off] = val & 0xff;
offset_off = out_len;
out_len++;
}
src_off++;
}
if (flag_bit === 0) out_len--;
else if (flag_bit < 8) output[offset_off] = val >> (8 - flag_bit);
return output.buffer.slice(0, out_len);
}
| 26.816239 | 80 | 0.575618 | 191 | 9 | 0 | 12 | 31 | 3 | 7 | 0 | 17 | 1 | 0 | 17.555556 | 2,100 | 0.01 | 0.014762 | 0.001429 | 0.000476 | 0 | 0 | 0.309091 | 0.243869 | const INDEX_BIT_COUNT = 12;
const LENGTH_BIT_COUNT = 4;
const RAW_LOOK_AHEAD_SIZE = 1 << LENGTH_BIT_COUNT;
const MAX_OFFSET = (1 << INDEX_BIT_COUNT) + 1;
const TREE_ROOT = MAX_OFFSET;
const UNUSED = -1;
enum Child {
Smaller = 0,
Larger = 1,
}
interface DefTree {
parent;
children;
which_child;
}
const tree = (() => {
const t = new Array<DefTree>(MAX_OFFSET + 2);
for (let i = 0; i < t.length; i++) {
t[i] = { parent: 0, children: [0, 0], which_child: 0 };
}
return t;
})();
/* Example usages of 'initTree' are shown below:
initTree();
*/
function initTree() {
tree[0].parent = 0;
tree[0].children[0] = 0;
tree[0].children[1] = 0;
tree[0].which_child = 0;
for (let i = 1; i < tree.length; i++) {
tree[i].parent = UNUSED;
tree[i].children[0] = UNUSED;
tree[i].children[1] = UNUSED;
tree[i].which_child = UNUSED;
}
}
/* Example usages of 'copyNode' are shown below:
copyNode(old_node + 1, new_node + 1);
*/
function copyNode(src, tgt) {
tree[tgt].parent = tree[src].parent;
tree[tgt].children[0] = tree[src].children[0];
tree[tgt].children[1] = tree[src].children[1];
tree[tgt].which_child = tree[src].which_child;
}
/* Example usages of 'replaceParents' are shown below:
replaceParents(new_node);
*/
function replaceParents(node) {
tree[tree[node + 1].children[Child.Smaller] + 1].parent = node;
tree[tree[node + 1].children[Child.Larger] + 1].parent = node;
}
/* Example usages of 'replace_node' are shown below:
replace_node(src_tree, replacement);
replace_node(node, src_tree);
*/
function replace_node(old_node, new_node) {
copyNode(old_node + 1, new_node + 1);
replaceParents(new_node);
tree[tree[old_node + 1].parent + 1].children[tree[old_node + 1].which_child] =
new_node;
}
/* Example usages of 'updateParent' are shown below:
updateParent(tree[src_tree + 1].children[which_child], tree[src_tree + 1].parent, tree[src_tree + 1].which_child);
updateParent(tree[replacement + 1].children[Child.Smaller], tree[replacement + 1].parent, tree[replacement + 1].which_child);
updateParent(src_tree, TREE_ROOT, 0);
updateParent(src_tree, node, j);
*/
function updateParent(node, parent, which_child) {
tree[node + 1].parent = parent;
tree[node + 1].which_child = which_child;
}
/* Example usages of 'findNextNode' are shown below:
findNextNode(src_tree);
*/
function findNextNode(node) {
let next = tree[node + 1].children[Child.Smaller];
if (tree[next + 1].children[Child.Larger] === UNUSED)
tree[node + 1].children[Child.Smaller] =
tree[next + 1].children[Child.Smaller];
else {
while (tree[next + 1].children[Child.Larger] !== UNUSED)
next = tree[next + 1].children[Child.Larger];
tree[tree[next + 1].parent + 1].children[Child.Larger] =
tree[next + 1].children[Child.Smaller];
}
return next;
}
/* Example usages of 'updateChild' are shown below:
updateChild(src_tree, tree[src_tree + 1].children[Child.Smaller] === UNUSED
? Child.Larger
: Child.Smaller);
*/
function updateChild(src_tree, which_child) {
if (tree[src_tree + 1].children[which_child] !== UNUSED)
updateParent(
tree[src_tree + 1].children[which_child],
tree[src_tree + 1].parent,
tree[src_tree + 1].which_child
);
tree[tree[src_tree + 1].parent + 1].children[tree[src_tree + 1].which_child] =
tree[src_tree + 1].children[which_child];
}
// Adapted from:
// https://github.com/OBattler/lbatools-c/blob/master/compress/lzmit.c
export function compressLZSS_LBA_type_2(data) {
let val = 0;
let src_off = 0;
let out_len = 1;
let offset_off = 0;
let flag_bit = 0;
let best_match = 1;
let best_node = 0;
const length = data.byteLength;
if (length <= RAW_LOOK_AHEAD_SIZE) {
return data;
}
const input = new Uint8Array(data);
const output = new Uint8Array(length);
initTree();
while (best_match + src_off - 1 < length) {
let i = best_match;
while (i > 0) {
const src_tree = src_off % MAX_OFFSET;
if (tree[src_tree + 1].parent !== UNUSED) {
if (
tree[src_tree + 1].children[Child.Smaller] !== UNUSED &&
tree[src_tree + 1].children[Child.Larger] !== UNUSED
) {
const replacement = findNextNode(src_tree);
updateParent(
tree[replacement + 1].children[Child.Smaller],
tree[replacement + 1].parent,
tree[replacement + 1].which_child
);
replace_node(src_tree, replacement);
} else {
updateChild(
src_tree,
tree[src_tree + 1].children[Child.Smaller] === UNUSED
? Child.Larger
: Child.Smaller
);
}
}
tree[src_tree + 1].children[Child.Larger] = UNUSED;
tree[src_tree + 1].children[Child.Smaller] = UNUSED;
let cur_node = tree[TREE_ROOT + 1].children[Child.Smaller];
if (cur_node < 0) {
best_match = 0;
best_node = 0;
updateParent(src_tree, TREE_ROOT, 0);
tree[TREE_ROOT + 1].children[Child.Smaller] = src_tree;
} else {
best_match = 2;
// eslint-disable-next-line no-constant-condition
while (true) {
let cur_string = src_off;
let cmp_string =
cur_string - ((src_tree - cur_node + MAX_OFFSET) % MAX_OFFSET);
const node = cur_node;
let j = RAW_LOOK_AHEAD_SIZE + 2;
cur_node = j - 1;
let diff;
do diff = input[cur_string++] - input[cmp_string++];
while (--j !== 0 && diff === 0);
if (j !== 0 || diff !== 0) {
cur_node -= j;
if (cur_node > best_match) {
best_match = cur_node;
best_node = node;
}
j = diff >= 0 ? 1 : 0;
cur_node = tree[node + 1].children[j];
if (cur_node < 0) {
updateParent(src_tree, node, j);
tree[node + 1].children[j] = src_tree;
break;
}
} else {
replace_node(node, src_tree);
tree[node + 1].parent = UNUSED;
best_match = RAW_LOOK_AHEAD_SIZE + 2;
best_node = node;
break;
}
}
}
if (--i > 0) src_off++;
}
if (out_len >= length - RAW_LOOK_AHEAD_SIZE - 1) {
return data;
}
val >>= 1;
if (best_match > 2 && src_off + best_match <= length) {
const temp =
(best_match - 3) |
((src_off - best_node - 1 + MAX_OFFSET) % MAX_OFFSET <<
LENGTH_BIT_COUNT);
output[out_len] = temp & 0xff;
output[out_len + 1] = temp >> 8;
out_len += 2;
} else {
output[out_len++] = input[src_off];
val |= 0x80;
best_match = 1;
}
flag_bit++;
if (flag_bit >= 8) {
flag_bit = 0;
output[offset_off] = val & 0xff;
offset_off = out_len;
out_len++;
}
src_off++;
}
if (flag_bit === 0) out_len--;
else if (flag_bit < 8) output[offset_off] = val >> (8 - flag_bit);
return output.buffer.slice(0, out_len);
}
|
c3c8ca64779bab3b26d05d1498d36da20c9d8fe8 | 2,321 | ts | TypeScript | lib/reporters/compareMarkdownReport.ts | gael-boyenval/debt-collector | 68fe52153b1e99217fbc51007ca9e18f94d9da08 | [
"MIT"
] | 3 | 2022-02-16T10:35:15.000Z | 2022-02-18T15:23:56.000Z | lib/reporters/compareMarkdownReport.ts | gael-boyenval/debt-collector | 68fe52153b1e99217fbc51007ca9e18f94d9da08 | [
"MIT"
] | 1 | 2022-03-11T10:29:55.000Z | 2022-03-11T10:29:55.000Z | lib/reporters/compareMarkdownReport.ts | gael-boyenval/debt-collector | 68fe52153b1e99217fbc51007ca9e18f94d9da08 | [
"MIT"
] | null | null | null | const createTable = (data) => `
|File|Prev|Current|Trend|
|--|--|--|--|
${data
.map((file) => `|${file.file}|${file.rev}|${file.current}|${file.trend}|`)
.join('\n')}
`
const createFileTable = (fileResult) => `
<br/>
<br/>
<b>${fileResult.fileShortPath}</b><br/>
total score : ${fileResult.totalScore}
<br/>
|Broken rule|score|
|--|--|
${fileResult.brokenRules
.map((rule) => `|🚫 ${rule.ruleTitle}|${rule.ruleTotalSore}|`)
.join('\n')}
`
const getFileScoreComparaison = (data) => {
let result = ''
if (data.noChangesFiles.length > 0) {
result += `
### 💤 Files with same debt :
${createTable(data.noChangesFiles)}
`
}
if (data.lessDeptFiles.length > 0) {
result += `
### ✅ Files with less debt :
${createTable(data.lessDeptFiles)}
`
}
if (data.moreDeptFiles.length > 0) {
result += `
### ❌ Files with more debt :
${createTable(data.moreDeptFiles)}
`
}
return result
}
const getConclusions = (data) => {
if (data.totalScores.solde > 0) {
return `### ❌ Debt score increased by ${data.totalScores.solde}[^1]`
}
if (data.totalScores.solde < 0) {
return `### ✅ Debt score decreased by ${data.totalScores.solde}[^1]`
}
return '### 💤 Debt score did not change[^1]'
}
const getMotivationSpeatch = (data) => {
if (data.totalScores.solde > 0) {
return `Maybe try something else 😭`
}
if (data.totalScores.solde < 0) {
return `You did great ! 🎉`
}
return '💤 Neither good or bad, I guess'
}
const compareMarkDownReport = (data) => `
## Debt collector report:
${getConclusions(data)}
${getMotivationSpeatch(data)}
|Previous debt|Current debt|trend|
|--|--|--|
|${data.totalScores.rev.toString()}|${data.totalScores.cur.toString()}|${data.totalScores.solde.toString()}|
<details>
<summary>
<h3>Modified files • see scores before and after</h3>
</summary>
<div>
${getFileScoreComparaison(data)}
<br/>
<br/>
</div>
</details>
<details>
<summary>
<h3>Help us improve code quality! Here are some ideas for you:</h3>
</summary>
<div>
${data.currentResults
.filter((res) => res.totalScore !== 0)
.map(createFileTable)
.join('\n')}
<br/>
<br/>
</div>
</details>
[^1]: Scores based on modified files only <br/>The report may not be accurate if your branch is not up to date with the base branch.
`
export default compareMarkDownReport
| 19.181818 | 132 | 0.635933 | 92 | 9 | 0 | 9 | 7 | 0 | 4 | 0 | 0 | 0 | 0 | 9.777778 | 830 | 0.021687 | 0.008434 | 0 | 0 | 0 | 0 | 0 | 0.24937 | /* Example usages of 'createTable' are shown below:
createTable(data.noChangesFiles);
createTable(data.lessDeptFiles);
createTable(data.moreDeptFiles);
*/
const createTable = (data) => `
|File|Prev|Current|Trend|
|--|--|--|--|
${data
.map((file) => `|${file.file}|${file.rev}|${file.current}|${file.trend}|`)
.join('\n')}
`
/* Example usages of 'createFileTable' are shown below:
data.currentResults
.filter((res) => res.totalScore !== 0)
.map(createFileTable)
.join('\n');
*/
const createFileTable = (fileResult) => `
<br/>
<br/>
<b>${fileResult.fileShortPath}</b><br/>
total score : ${fileResult.totalScore}
<br/>
|Broken rule|score|
|--|--|
${fileResult.brokenRules
.map((rule) => `|🚫 ${rule.ruleTitle}|${rule.ruleTotalSore}|`)
.join('\n')}
`
/* Example usages of 'getFileScoreComparaison' are shown below:
getFileScoreComparaison(data);
*/
const getFileScoreComparaison = (data) => {
let result = ''
if (data.noChangesFiles.length > 0) {
result += `
### 💤 Files with same debt :
${createTable(data.noChangesFiles)}
`
}
if (data.lessDeptFiles.length > 0) {
result += `
### ✅ Files with less debt :
${createTable(data.lessDeptFiles)}
`
}
if (data.moreDeptFiles.length > 0) {
result += `
### ❌ Files with more debt :
${createTable(data.moreDeptFiles)}
`
}
return result
}
/* Example usages of 'getConclusions' are shown below:
getConclusions(data);
*/
const getConclusions = (data) => {
if (data.totalScores.solde > 0) {
return `### ❌ Debt score increased by ${data.totalScores.solde}[^1]`
}
if (data.totalScores.solde < 0) {
return `### ✅ Debt score decreased by ${data.totalScores.solde}[^1]`
}
return '### 💤 Debt score did not change[^1]'
}
/* Example usages of 'getMotivationSpeatch' are shown below:
getMotivationSpeatch(data);
*/
const getMotivationSpeatch = (data) => {
if (data.totalScores.solde > 0) {
return `Maybe try something else 😭`
}
if (data.totalScores.solde < 0) {
return `You did great ! 🎉`
}
return '💤 Neither good or bad, I guess'
}
/* Example usages of 'compareMarkDownReport' are shown below:
;
*/
const compareMarkDownReport = (data) => `
## Debt collector report:
${getConclusions(data)}
${getMotivationSpeatch(data)}
|Previous debt|Current debt|trend|
|--|--|--|
|${data.totalScores.rev.toString()}|${data.totalScores.cur.toString()}|${data.totalScores.solde.toString()}|
<details>
<summary>
<h3>Modified files • see scores before and after</h3>
</summary>
<div>
${getFileScoreComparaison(data)}
<br/>
<br/>
</div>
</details>
<details>
<summary>
<h3>Help us improve code quality! Here are some ideas for you:</h3>
</summary>
<div>
${data.currentResults
.filter((res) => res.totalScore !== 0)
.map(createFileTable)
.join('\n')}
<br/>
<br/>
</div>
</details>
[^1]: Scores based on modified files only <br/>The report may not be accurate if your branch is not up to date with the base branch.
`
export default compareMarkDownReport
|
070e2121d18dbd51aa54db70b601fd281c0c408e | 4,714 | ts | TypeScript | problemset/number-of-islands/index.ts | OUDUIDUI/leet-code | 50e61ce16d1c419ccefc075ae9ead721cdd1cdbb | [
"MIT"
] | 6 | 2022-01-17T03:19:56.000Z | 2022-01-17T05:45:39.000Z | problemset/number-of-islands/index.ts | OUDUIDUI/leet-code | 50e61ce16d1c419ccefc075ae9ead721cdd1cdbb | [
"MIT"
] | null | null | null | problemset/number-of-islands/index.ts | OUDUIDUI/leet-code | 50e61ce16d1c419ccefc075ae9ead721cdd1cdbb | [
"MIT"
] | null | null | null | /**
* 深度优先遍历
* @desc 时间复杂度 O(NM) 空间复杂度 O(NM)
* @param grid
* @returns
*/
export function numIslands(grid: string[][]): number {
if (grid.length === 0 || grid[0].length === 0) return 0
const m = grid.length
const n = grid[0].length
let result = 0
for (let i = 0; i < m; i++) {
for (let j = 0; j < n; j++) {
if (grid[i][j] !== '1') continue
result++
dfs(grid, m, n, i, j)
}
}
return result
function dfs(
grid: string[][],
m: number,
n: number,
i: number,
j: number,
): void {
if (i < 0 || j < 0 || i >= m || j >= n || grid[i][j] === '0') return
grid[i][j] = '0'
dfs(grid, m, n, i + 1, j)
dfs(grid, m, n, i - 1, j)
dfs(grid, m, n, i, j + 1)
dfs(grid, m, n, i, j - 1)
}
}
/**
* 广度优先遍历
* @desc 时间复杂度 O(NM) 空间复杂度 O(NM)
* @param grid
* @returns
*/
export function numIslands2(grid: string[][]): number {
if (grid.length === 0 || grid[0].length === 0) return 0
const m = grid.length
const n = grid[0].length
let result = 0
// 生成队列key
const generateKey = (i: number, j: number): number =>
i * n + j /* j 恒小于 n */
for (let i = 0; i < m; i++) {
for (let j = 0; j < n; j++) {
if (grid[i][j] !== '1') continue
result++
grid[i][j] = '0'
const queue = [generateKey(i, j)]
while (queue.length) {
const key = queue.pop()!
const row = (key / n) >> 0
const col = key % n
if (row - 1 >= 0 && grid[row - 1][col] === '1') {
queue.unshift(generateKey(row - 1, col))
grid[row - 1][col] = '0'
}
if (row + 1 < m && grid[row + 1][col] === '1') {
queue.unshift(generateKey(row + 1, col))
grid[row + 1][col] = '0'
}
if (col - 1 >= 0 && grid[row][col - 1] === '1') {
queue.unshift(generateKey(row, col - 1))
grid[row][col - 1] = '0'
}
if (col + 1 < n && grid[row][col + 1] === '1') {
queue.unshift(generateKey(row, col + 1))
grid[row][col + 1] = '0'
}
}
}
}
return result
}
/**
* 并查集
* @desc 时间复杂度 O(NM) 空间复杂度 O(NM)
* @param grid
* @returns
*/
export function numIslands3(grid: string[][]): number {
if (grid.length === 0 || grid[0].length === 0) return 0
const unionFind = new UnionFind(grid)
const { m, n } = unionFind
for (let i = 0; i < m; i++) {
for (let j = 0; j < n; j++) {
if (grid[i][j] === '1') {
grid[i][j] = '0'
if (i - 1 >= 0 && grid[i - 1][j] === '1') {
unionFind.union(
unionFind.generateKey(i, j),
unionFind.generateKey(i - 1, j),
)
}
if (i + 1 < m && grid[i + 1][j] === '1') {
unionFind.union(
unionFind.generateKey(i, j),
unionFind.generateKey(i + 1, j),
)
}
if (j - 1 >= 0 && grid[i][j - 1] === '1') {
unionFind.union(
unionFind.generateKey(i, j),
unionFind.generateKey(i, j - 1),
)
}
if (j + 1 < n && grid[i][j + 1] === '1') {
unionFind.union(
unionFind.generateKey(i, j),
unionFind.generateKey(i, j + 1),
)
}
}
}
}
return unionFind.count
}
class UnionFind {
count: number // 记录item为1的个数
parent: number[] // index为每个item的唯一key,value为它们合并后的根位置
rank: number[] // 记录每个根位置的合并数量
m: number
n: number
constructor(grid: string[][]) {
// 初始化
this.count = 0
const m = (this.m = grid.length)
const n = (this.n = grid[0].length)
this.parent = new Array(m * n).fill(-1)
this.rank = new Array(m * n).fill(0)
for (let i = 0; i < m; i++) {
for (let j = 0; j < n; j++) {
const key = this.generateKey(i, j)
if (grid[i][j] === '1') {
this.parent[key] = key
this.count++
}
}
}
}
/**
* 生成唯一keys
* @param i
* @param j
* @returns
*/
generateKey(i: number, j: number): number {
return i * this.n + j
}
find(i: number): number {
if (this.parent[i] !== i) this.parent[i] = this.find(this.parent[i])
return this.parent[i]
}
/**
* 合并操作
* @param x
* @param y
*/
union(x: number, y: number) {
// 找到x,y的根位置
// 这里可以确保x,y的item都为1
const xRoot = this.find(x)
const yRoot = this.find(y)
// xRoot === yRoot 代表已经合并了
if (xRoot === yRoot) return
// 合并操作
if (this.rank[xRoot] > this.rank[yRoot]) {
this.parent[yRoot] = xRoot
}
else if (this.rank[xRoot] < this.rank[yRoot]) {
this.parent[xRoot] = yRoot
}
else {
this.parent[yRoot] = xRoot
this.rank[xRoot] += 1
}
this.count--
}
}
| 22.555024 | 72 | 0.469241 | 149 | 9 | 0 | 16 | 26 | 5 | 4 | 0 | 28 | 1 | 0 | 15 | 1,732 | 0.014434 | 0.015012 | 0.002887 | 0.000577 | 0 | 0 | 0.5 | 0.254204 | /**
* 深度优先遍历
* @desc 时间复杂度 O(NM) 空间复杂度 O(NM)
* @param grid
* @returns
*/
export function numIslands(grid) {
if (grid.length === 0 || grid[0].length === 0) return 0
const m = grid.length
const n = grid[0].length
let result = 0
for (let i = 0; i < m; i++) {
for (let j = 0; j < n; j++) {
if (grid[i][j] !== '1') continue
result++
dfs(grid, m, n, i, j)
}
}
return result
/* Example usages of 'dfs' are shown below:
dfs(grid, m, n, i, j);
dfs(grid, m, n, i + 1, j);
dfs(grid, m, n, i - 1, j);
dfs(grid, m, n, i, j + 1);
dfs(grid, m, n, i, j - 1);
*/
function dfs(
grid,
m,
n,
i,
j,
) {
if (i < 0 || j < 0 || i >= m || j >= n || grid[i][j] === '0') return
grid[i][j] = '0'
dfs(grid, m, n, i + 1, j)
dfs(grid, m, n, i - 1, j)
dfs(grid, m, n, i, j + 1)
dfs(grid, m, n, i, j - 1)
}
}
/**
* 广度优先遍历
* @desc 时间复杂度 O(NM) 空间复杂度 O(NM)
* @param grid
* @returns
*/
export function numIslands2(grid) {
if (grid.length === 0 || grid[0].length === 0) return 0
const m = grid.length
const n = grid[0].length
let result = 0
// 生成队列key
/* Example usages of 'generateKey' are shown below:
generateKey(i, j);
queue.unshift(generateKey(row - 1, col));
queue.unshift(generateKey(row + 1, col));
queue.unshift(generateKey(row, col - 1));
queue.unshift(generateKey(row, col + 1));
unionFind.union(unionFind.generateKey(i, j), unionFind.generateKey(i - 1, j));
unionFind.union(unionFind.generateKey(i, j), unionFind.generateKey(i + 1, j));
unionFind.union(unionFind.generateKey(i, j), unionFind.generateKey(i, j - 1));
unionFind.union(unionFind.generateKey(i, j), unionFind.generateKey(i, j + 1));
this.generateKey(i, j);
*/
const generateKey = (i, j) =>
i * n + j /* j 恒小于 n */
for (let i = 0; i < m; i++) {
for (let j = 0; j < n; j++) {
if (grid[i][j] !== '1') continue
result++
grid[i][j] = '0'
const queue = [generateKey(i, j)]
while (queue.length) {
const key = queue.pop()!
const row = (key / n) >> 0
const col = key % n
if (row - 1 >= 0 && grid[row - 1][col] === '1') {
queue.unshift(generateKey(row - 1, col))
grid[row - 1][col] = '0'
}
if (row + 1 < m && grid[row + 1][col] === '1') {
queue.unshift(generateKey(row + 1, col))
grid[row + 1][col] = '0'
}
if (col - 1 >= 0 && grid[row][col - 1] === '1') {
queue.unshift(generateKey(row, col - 1))
grid[row][col - 1] = '0'
}
if (col + 1 < n && grid[row][col + 1] === '1') {
queue.unshift(generateKey(row, col + 1))
grid[row][col + 1] = '0'
}
}
}
}
return result
}
/**
* 并查集
* @desc 时间复杂度 O(NM) 空间复杂度 O(NM)
* @param grid
* @returns
*/
export function numIslands3(grid) {
if (grid.length === 0 || grid[0].length === 0) return 0
const unionFind = new UnionFind(grid)
const { m, n } = unionFind
for (let i = 0; i < m; i++) {
for (let j = 0; j < n; j++) {
if (grid[i][j] === '1') {
grid[i][j] = '0'
if (i - 1 >= 0 && grid[i - 1][j] === '1') {
unionFind.union(
unionFind.generateKey(i, j),
unionFind.generateKey(i - 1, j),
)
}
if (i + 1 < m && grid[i + 1][j] === '1') {
unionFind.union(
unionFind.generateKey(i, j),
unionFind.generateKey(i + 1, j),
)
}
if (j - 1 >= 0 && grid[i][j - 1] === '1') {
unionFind.union(
unionFind.generateKey(i, j),
unionFind.generateKey(i, j - 1),
)
}
if (j + 1 < n && grid[i][j + 1] === '1') {
unionFind.union(
unionFind.generateKey(i, j),
unionFind.generateKey(i, j + 1),
)
}
}
}
}
return unionFind.count
}
class UnionFind {
count // 记录item为1的个数
parent // index为每个item的唯一key,value为它们合并后的根位置
rank // 记录每个根位置的合并数量
m
n
constructor(grid) {
// 初始化
this.count = 0
const m = (this.m = grid.length)
const n = (this.n = grid[0].length)
this.parent = new Array(m * n).fill(-1)
this.rank = new Array(m * n).fill(0)
for (let i = 0; i < m; i++) {
for (let j = 0; j < n; j++) {
const key = this.generateKey(i, j)
if (grid[i][j] === '1') {
this.parent[key] = key
this.count++
}
}
}
}
/**
* 生成唯一keys
* @param i
* @param j
* @returns
*/
generateKey(i, j) {
return i * this.n + j
}
find(i) {
if (this.parent[i] !== i) this.parent[i] = this.find(this.parent[i])
return this.parent[i]
}
/**
* 合并操作
* @param x
* @param y
*/
union(x, y) {
// 找到x,y的根位置
// 这里可以确保x,y的item都为1
const xRoot = this.find(x)
const yRoot = this.find(y)
// xRoot === yRoot 代表已经合并了
if (xRoot === yRoot) return
// 合并操作
if (this.rank[xRoot] > this.rank[yRoot]) {
this.parent[yRoot] = xRoot
}
else if (this.rank[xRoot] < this.rank[yRoot]) {
this.parent[xRoot] = yRoot
}
else {
this.parent[yRoot] = xRoot
this.rank[xRoot] += 1
}
this.count--
}
}
|
072892154809e137aaab6caf54f08ef6b8fea2a4 | 13,022 | ts | TypeScript | research/geometry/vmf-parser/src/parse.ts | nrkn/bloodlines-tc | 0dbe23dee211afec8da94b8dc9079dfe088e2873 | [
"Unlicense"
] | 1 | 2022-03-22T04:13:24.000Z | 2022-03-22T04:13:24.000Z | research/geometry/vmf-parser/src/parse.ts | nrkn/bloodlines-tc | 0dbe23dee211afec8da94b8dc9079dfe088e2873 | [
"Unlicense"
] | null | null | null | research/geometry/vmf-parser/src/parse.ts | nrkn/bloodlines-tc | 0dbe23dee211afec8da94b8dc9079dfe088e2873 | [
"Unlicense"
] | null | null | null | // a simple parser for Valve's KeyValue format
// https://developer.valvesoftware.com/wiki/KeyValues
//
// authors:
// Rossen Popov, 2014-2016
// p0358, 2019-2021
const TYPEEX = {
INT: /^\-?\d+$/,
FLOAT: /^\-?\d+\.\d+$/,
BOOLEAN: /^(true|false)$/i,
}
export function parse(text: string, options?: any ) {
if (typeof text !== "string") {
throw new TypeError("VDF.parse: Expecting parameter to be a string");
}
options = {
types:
(typeof options === "boolean") ? options // backward compatibility with the old boolean param
: ((typeof options === "object" && "types" in options) ? options.types : true),
arrayify: (typeof options === "object" && "arrayify" in options) ? options.arrayify : true,
conditionals: (typeof options === "object" && "conditionals" in options) ? options.conditionals : undefined
};
if (options.conditionals && !Array.isArray(options.conditionals) && typeof options.conditionals === "string") options.conditionals = [options.conditionals];
let lines = text.split("\n");
var obj: any = {};
var stack = [obj];
var expect_bracket = false;
var odd = false;
var re_kv = new RegExp(
'^[ \\t]*' +
'("((?:\\\\.|[^\\\\"])+)"|([a-zA-Z0-9\\-\\_]+))' + // qkey, key
'([ \\t]*(' +
'"((?:\\\\.|[^\\\\"])*)(")?' + // qval, vq_end
'|([a-zA-Z0-9\\-\\_.]+)' + // val
'))?' +
'(?:[ \\t]*\\[(\\!?\\$[A-Z0-9]+(?:(?:[\\|]{2}|[\\&]{2})\\!?\\$[A-Z0-9]+)*)\\])?' // conditionals
);
var i = -1, j = lines.length, line, sublines;
var getNextLine = function() {
if (sublines && sublines.length)
{
var _subline = sublines.shift();
if (!odd) _subline = _subline.trim(); // we need to trim the line if outside of quoted value
return _subline;
}
var _line = lines[++i];
// skip empty and comment lines
// but only if we are not inside of a quote value
while ( !odd && _line !== undefined && (_line = _line.trim()) && (_line == "" || _line[0] == '/') )
_line = lines[++i];
if (_line === undefined)
return false; // this is the end
// make sure brackets are in separate lines, as this code assumes
// done separately to retain correct line numbers in errors
// skip tricky comments + add newlines around brackets, while making sure that slashes are not part of some key/value (inside quotes)
//var odd = false; // odd number of quotes encountered means we are inside of a quote value
var comment_slash_pos = -1;
sanitization: for (var l = 0; l < _line.length; l++) {
switch (_line.charAt(l)) {
case '"': if (_line.charAt(l-1) != '\\') odd = !odd; break;
case '/': if (!odd) { comment_slash_pos = l; break sanitization; } break;
case '{': if (!odd) { _line = _line.slice(0, l) + "\n{\n" + _line.slice(l+1); l+=2; } break;
case '}': if (!odd) { _line = _line.slice(0, l) + "\n}\n" + _line.slice(l+1); l+=2; } break;
}
}
if (comment_slash_pos > -1) _line = _line.substr(0, comment_slash_pos);
//if (!odd) _line = _line.trim(); // isn't that redundant?
sublines = _line.split("\n"); // no trim here
return getNextLine();
}
while ((line = getNextLine()) !== false) {
// skip empty and comment lines, again
if ( line == "" || line[0] == '/') { continue; }
// one level deeper
if ( line[0] == "{" ) {
expect_bracket = false;
continue;
}
if (expect_bracket) {
throw new SyntaxError("VDF.parse: invalid syntax on line " + (i+1) + " (expected opening bracket, empty unquoted values are not allowed):\n" + line);
}
// one level back
if ( line[0] == "}" ) {
if (Array.isArray(stack[stack.length-2])) stack.pop(); // if the element above is an array, we need to pop twice
stack.pop();
continue;
}
// parse keyvalue pairs
while (true) {
const m = re_kv.exec(line);
if (m === null) {
throw new SyntaxError("VDF.parse: invalid syntax on line " + (i+1) + ":\n" + line);
}
// qkey = 2
// key = 3
// qval = 6
// vq_end = 7
// val = 8
var key = (m[2] !== undefined) ? m[2] : m[3];
var val: any = (m[6] !== undefined) ? m[6] : m[8];
if (val === undefined) {
// parent key
// does not exist at all yet
if (stack[stack.length-1][key] === undefined /*|| typeof stack[stack.length-1][key] !== 'object'*/) {
stack[stack.length-1][key] = {};
stack.push(stack[stack.length-1][key]);
}
// exists already, is an object, but not an array
else if (stack[stack.length-1][key] !== undefined && !Array.isArray(stack[stack.length-1][key])) {
if (options.arrayify) {
// we turn it into an array to push the next object there
stack[stack.length-1][key] = [stack[stack.length-1][key], {}]; // turn current object into array with the object and new empty object
stack.push(stack[stack.length-1][key]); // push our array to stack
stack.push(stack[stack.length-1][1]); // push our newly created (2nd) object to stack
} else {
// push it on stack and let it get patched with new values
stack.push(stack[stack.length-1][key]);
}
}
// exists already, is an array of objects
else if (stack[stack.length-1][key] !== undefined && Array.isArray(stack[stack.length-1][key])) {
if (!options.arrayify)
throw new Error("VDF.parse: this code block should never be reached with arrayify set to false! [1]");
stack.push(stack[stack.length-1][key]); // push current array on stack
stack[stack.length-1].push({}); // append new object to that array
stack.push(stack[stack.length-1][ (stack[stack.length-1]).length-1 ]); // push that new (last) object on stack
}
expect_bracket = true;
}
else {
// value key
if (m[7] === undefined && m[8] === undefined) {
if (i + 1 >= j) {
throw new SyntaxError("VDF.parse: un-closed quotes at end of file");
}
line += "\n" + getNextLine();
continue;
}
if (options.conditionals !== undefined && Array.isArray(options.conditionals) && m[9]) {
var conditionals = m[9];
var single_cond_regex = new RegExp('^(\\|\\||&&)?(!)?\\$([A-Z0-9]+)');
var ok = false;
while (conditionals) {
var d = single_cond_regex.exec(conditionals);
if (d === null || !d[3])
throw new SyntaxError("VDF.parse: encountered an incorrect conditional: " + conditionals);
conditionals = conditionals.replace(d[0], '').trim(); // erase parsed fragment from the list
var op = d[1];
var not = d[2] && d[2] === '!';
var cond = d[3];
var includes = options.conditionals.indexOf(cond) !== -1;
var _ok = not ? !includes : includes;
if (!op || op === '||')
ok = ok || _ok;
else // &&
ok = ok && _ok;
}
//console.log('cond', key, val, _ok);
if (!ok) {
// conditions are not met
// continue processing the line (code duplicated from the bottom of our while loop)
line = line.replace(m[0], "");
if (!line || line[0] == '/') break; // break if there is nothing else (of interest) left in this line
continue;
}
}
if (options.types) {
if (TYPEEX.INT.test(val)) {
val = parseInt(val);
} else if (TYPEEX.FLOAT.test(val)) {
val = parseFloat(val);
} else if (TYPEEX.BOOLEAN.test(val)) {
val = val.toLowerCase() == "true";
}
}
// does not exist at all yet
if (stack[stack.length-1][key] === undefined) {
stack[stack.length-1][key] = val;
}
// exists already, but is not an array
else if (stack[stack.length-1][key] !== undefined && !Array.isArray(stack[stack.length-1][key])) {
if (options.arrayify) {
// we turn it into an array and push the next object there
stack[stack.length-1][key] = [stack[stack.length-1][key], val]; // turn current object into array with the old object and the new object
} else {
// replace it with the new value
stack[stack.length-1][key] = val;
}
}
// exists already, is an array
else if (stack[stack.length-1][key] !== undefined && Array.isArray(stack[stack.length-1][key])) {
if (!options.arrayify)
throw new Error("VDF.parse: this code block should never be reached with arrayify set to false! [2]");
stack[stack.length-1][key].push(val);
}
}
if (expect_bracket) break; // there was just key, no value, the next line should contain bracket (to go one level deeper)
line = line.replace(m[0], "").trim();
if (!line || line[0] == '/') break; // break if there is nothing else (of interest) left in this line
line = line.replace(/^\s*\[\!?\$[A-Z0-9]+(?:(?:[\|]{2}|[\&]{2})\!?\$[A-Z0-9]+)*\]/, "").trim(); // ignore conditionals
if (!line || line[0] == '/') break; // again; if there's nothing left after skipping the conditional
}
}
if (stack.length != 1) throw new SyntaxError("VDF.parse: open parentheses somewhere");
return obj;
}
function stringify(obj, options) {
if (typeof obj !== "object") {
throw new TypeError("VDF.stringify: First input parameter is not an object");
}
options = {
pretty:
(typeof options === "boolean") ? options // backward compatibility with the old boolean param
: ((typeof options === "object" && "pretty" in options) ? options.pretty : false),
indent: (typeof options === "object" && "indent" in options) ? options.indent : "\t"
};
return _dump(obj, options, 0);
}
function _dump(obj, options, level) {
if (typeof obj !== "object") {
throw new TypeError("VDF.stringify: a key has value of type other than string or object: " + typeof obj);
}
var indent = options.indent; // "\t"
var buf = "";
var line_indent = "";
if (options.pretty) {
for (var i = 0; i < level; i++ ) {
line_indent += indent;
}
}
for (var key in obj) {
if (typeof obj[key] === "object") {
if (Array.isArray(obj[key])) {
obj[key].forEach(function (element) {
if (typeof element !== "object") {
// de-arrayifying a non-object (strings etc)
// fake an object to write:
const _element = {};
_element[key] = element;
buf += _dump(_element,options,level);
}
else {
// de-arrayifying an object
buf += [line_indent, '"', key, '"\n', line_indent, '{\n', _dump(element,options,level+1), line_indent, "}\n"].join('');
}
});
}
else
buf += [line_indent, '"', key, '"\n', line_indent, '{\n', _dump(obj[key],options,level+1), line_indent, "}\n"].join('');
}
else {
buf += [line_indent, '"', key, '" "', String(obj[key]), '"\n'].join('');
}
}
return buf;
}
| 42.695082 | 161 | 0.472278 | 216 | 5 | 0 | 8 | 33 | 0 | 2 | 3 | 1 | 0 | 14 | 47.2 | 3,194 | 0.00407 | 0.010332 | 0 | 0 | 0.004383 | 0.065217 | 0.021739 | 0.212272 | // a simple parser for Valve's KeyValue format
// https://developer.valvesoftware.com/wiki/KeyValues
//
// authors:
// Rossen Popov, 2014-2016
// p0358, 2019-2021
const TYPEEX = {
INT: /^\-?\d+$/,
FLOAT: /^\-?\d+\.\d+$/,
BOOLEAN: /^(true|false)$/i,
}
export function parse(text, options? ) {
if (typeof text !== "string") {
throw new TypeError("VDF.parse: Expecting parameter to be a string");
}
options = {
types:
(typeof options === "boolean") ? options // backward compatibility with the old boolean param
: ((typeof options === "object" && "types" in options) ? options.types : true),
arrayify: (typeof options === "object" && "arrayify" in options) ? options.arrayify : true,
conditionals: (typeof options === "object" && "conditionals" in options) ? options.conditionals : undefined
};
if (options.conditionals && !Array.isArray(options.conditionals) && typeof options.conditionals === "string") options.conditionals = [options.conditionals];
let lines = text.split("\n");
var obj = {};
var stack = [obj];
var expect_bracket = false;
var odd = false;
var re_kv = new RegExp(
'^[ \\t]*' +
'("((?:\\\\.|[^\\\\"])+)"|([a-zA-Z0-9\\-\\_]+))' + // qkey, key
'([ \\t]*(' +
'"((?:\\\\.|[^\\\\"])*)(")?' + // qval, vq_end
'|([a-zA-Z0-9\\-\\_.]+)' + // val
'))?' +
'(?:[ \\t]*\\[(\\!?\\$[A-Z0-9]+(?:(?:[\\|]{2}|[\\&]{2})\\!?\\$[A-Z0-9]+)*)\\])?' // conditionals
);
var i = -1, j = lines.length, line, sublines;
/* Example usages of 'getNextLine' are shown below:
getNextLine();
line = getNextLine();
line += "\n" + getNextLine();
*/
var getNextLine = function() {
if (sublines && sublines.length)
{
var _subline = sublines.shift();
if (!odd) _subline = _subline.trim(); // we need to trim the line if outside of quoted value
return _subline;
}
var _line = lines[++i];
// skip empty and comment lines
// but only if we are not inside of a quote value
while ( !odd && _line !== undefined && (_line = _line.trim()) && (_line == "" || _line[0] == '/') )
_line = lines[++i];
if (_line === undefined)
return false; // this is the end
// make sure brackets are in separate lines, as this code assumes
// done separately to retain correct line numbers in errors
// skip tricky comments + add newlines around brackets, while making sure that slashes are not part of some key/value (inside quotes)
//var odd = false; // odd number of quotes encountered means we are inside of a quote value
var comment_slash_pos = -1;
sanitization: for (var l = 0; l < _line.length; l++) {
switch (_line.charAt(l)) {
case '"': if (_line.charAt(l-1) != '\\') odd = !odd; break;
case '/': if (!odd) { comment_slash_pos = l; break sanitization; } break;
case '{': if (!odd) { _line = _line.slice(0, l) + "\n{\n" + _line.slice(l+1); l+=2; } break;
case '}': if (!odd) { _line = _line.slice(0, l) + "\n}\n" + _line.slice(l+1); l+=2; } break;
}
}
if (comment_slash_pos > -1) _line = _line.substr(0, comment_slash_pos);
//if (!odd) _line = _line.trim(); // isn't that redundant?
sublines = _line.split("\n"); // no trim here
return getNextLine();
}
while ((line = getNextLine()) !== false) {
// skip empty and comment lines, again
if ( line == "" || line[0] == '/') { continue; }
// one level deeper
if ( line[0] == "{" ) {
expect_bracket = false;
continue;
}
if (expect_bracket) {
throw new SyntaxError("VDF.parse: invalid syntax on line " + (i+1) + " (expected opening bracket, empty unquoted values are not allowed):\n" + line);
}
// one level back
if ( line[0] == "}" ) {
if (Array.isArray(stack[stack.length-2])) stack.pop(); // if the element above is an array, we need to pop twice
stack.pop();
continue;
}
// parse keyvalue pairs
while (true) {
const m = re_kv.exec(line);
if (m === null) {
throw new SyntaxError("VDF.parse: invalid syntax on line " + (i+1) + ":\n" + line);
}
// qkey = 2
// key = 3
// qval = 6
// vq_end = 7
// val = 8
var key = (m[2] !== undefined) ? m[2] : m[3];
var val = (m[6] !== undefined) ? m[6] : m[8];
if (val === undefined) {
// parent key
// does not exist at all yet
if (stack[stack.length-1][key] === undefined /*|| typeof stack[stack.length-1][key] !== 'object'*/) {
stack[stack.length-1][key] = {};
stack.push(stack[stack.length-1][key]);
}
// exists already, is an object, but not an array
else if (stack[stack.length-1][key] !== undefined && !Array.isArray(stack[stack.length-1][key])) {
if (options.arrayify) {
// we turn it into an array to push the next object there
stack[stack.length-1][key] = [stack[stack.length-1][key], {}]; // turn current object into array with the object and new empty object
stack.push(stack[stack.length-1][key]); // push our array to stack
stack.push(stack[stack.length-1][1]); // push our newly created (2nd) object to stack
} else {
// push it on stack and let it get patched with new values
stack.push(stack[stack.length-1][key]);
}
}
// exists already, is an array of objects
else if (stack[stack.length-1][key] !== undefined && Array.isArray(stack[stack.length-1][key])) {
if (!options.arrayify)
throw new Error("VDF.parse: this code block should never be reached with arrayify set to false! [1]");
stack.push(stack[stack.length-1][key]); // push current array on stack
stack[stack.length-1].push({}); // append new object to that array
stack.push(stack[stack.length-1][ (stack[stack.length-1]).length-1 ]); // push that new (last) object on stack
}
expect_bracket = true;
}
else {
// value key
if (m[7] === undefined && m[8] === undefined) {
if (i + 1 >= j) {
throw new SyntaxError("VDF.parse: un-closed quotes at end of file");
}
line += "\n" + getNextLine();
continue;
}
if (options.conditionals !== undefined && Array.isArray(options.conditionals) && m[9]) {
var conditionals = m[9];
var single_cond_regex = new RegExp('^(\\|\\||&&)?(!)?\\$([A-Z0-9]+)');
var ok = false;
while (conditionals) {
var d = single_cond_regex.exec(conditionals);
if (d === null || !d[3])
throw new SyntaxError("VDF.parse: encountered an incorrect conditional: " + conditionals);
conditionals = conditionals.replace(d[0], '').trim(); // erase parsed fragment from the list
var op = d[1];
var not = d[2] && d[2] === '!';
var cond = d[3];
var includes = options.conditionals.indexOf(cond) !== -1;
var _ok = not ? !includes : includes;
if (!op || op === '||')
ok = ok || _ok;
else // &&
ok = ok && _ok;
}
//console.log('cond', key, val, _ok);
if (!ok) {
// conditions are not met
// continue processing the line (code duplicated from the bottom of our while loop)
line = line.replace(m[0], "");
if (!line || line[0] == '/') break; // break if there is nothing else (of interest) left in this line
continue;
}
}
if (options.types) {
if (TYPEEX.INT.test(val)) {
val = parseInt(val);
} else if (TYPEEX.FLOAT.test(val)) {
val = parseFloat(val);
} else if (TYPEEX.BOOLEAN.test(val)) {
val = val.toLowerCase() == "true";
}
}
// does not exist at all yet
if (stack[stack.length-1][key] === undefined) {
stack[stack.length-1][key] = val;
}
// exists already, but is not an array
else if (stack[stack.length-1][key] !== undefined && !Array.isArray(stack[stack.length-1][key])) {
if (options.arrayify) {
// we turn it into an array and push the next object there
stack[stack.length-1][key] = [stack[stack.length-1][key], val]; // turn current object into array with the old object and the new object
} else {
// replace it with the new value
stack[stack.length-1][key] = val;
}
}
// exists already, is an array
else if (stack[stack.length-1][key] !== undefined && Array.isArray(stack[stack.length-1][key])) {
if (!options.arrayify)
throw new Error("VDF.parse: this code block should never be reached with arrayify set to false! [2]");
stack[stack.length-1][key].push(val);
}
}
if (expect_bracket) break; // there was just key, no value, the next line should contain bracket (to go one level deeper)
line = line.replace(m[0], "").trim();
if (!line || line[0] == '/') break; // break if there is nothing else (of interest) left in this line
line = line.replace(/^\s*\[\!?\$[A-Z0-9]+(?:(?:[\|]{2}|[\&]{2})\!?\$[A-Z0-9]+)*\]/, "").trim(); // ignore conditionals
if (!line || line[0] == '/') break; // again; if there's nothing left after skipping the conditional
}
}
if (stack.length != 1) throw new SyntaxError("VDF.parse: open parentheses somewhere");
return obj;
}
function stringify(obj, options) {
if (typeof obj !== "object") {
throw new TypeError("VDF.stringify: First input parameter is not an object");
}
options = {
pretty:
(typeof options === "boolean") ? options // backward compatibility with the old boolean param
: ((typeof options === "object" && "pretty" in options) ? options.pretty : false),
indent: (typeof options === "object" && "indent" in options) ? options.indent : "\t"
};
return _dump(obj, options, 0);
}
/* Example usages of '_dump' are shown below:
_dump(obj, options, 0);
buf += _dump(_element, options, level);
_dump(element, options, level + 1);
_dump(obj[key], options, level + 1);
*/
function _dump(obj, options, level) {
if (typeof obj !== "object") {
throw new TypeError("VDF.stringify: a key has value of type other than string or object: " + typeof obj);
}
var indent = options.indent; // "\t"
var buf = "";
var line_indent = "";
if (options.pretty) {
for (var i = 0; i < level; i++ ) {
line_indent += indent;
}
}
for (var key in obj) {
if (typeof obj[key] === "object") {
if (Array.isArray(obj[key])) {
obj[key].forEach(function (element) {
if (typeof element !== "object") {
// de-arrayifying a non-object (strings etc)
// fake an object to write:
const _element = {};
_element[key] = element;
buf += _dump(_element,options,level);
}
else {
// de-arrayifying an object
buf += [line_indent, '"', key, '"\n', line_indent, '{\n', _dump(element,options,level+1), line_indent, "}\n"].join('');
}
});
}
else
buf += [line_indent, '"', key, '"\n', line_indent, '{\n', _dump(obj[key],options,level+1), line_indent, "}\n"].join('');
}
else {
buf += [line_indent, '"', key, '" "', String(obj[key]), '"\n'].join('');
}
}
return buf;
}
|
076f165471f1e1a9b2fb8318a6258fb2ae7d02bf | 6,952 | ts | TypeScript | packages/base/src/data/function/pipe.ts | 0x706b/fncts | 1685a0b1c94bdde35baf278fd7817b3e6c7f2e1d | [
"BSD-3-Clause"
] | 1 | 2022-03-30T23:44:15.000Z | 2022-03-30T23:44:15.000Z | packages/base/src/data/function/pipe.ts | 0x706b/fncts | 1685a0b1c94bdde35baf278fd7817b3e6c7f2e1d | [
"BSD-3-Clause"
] | null | null | null | packages/base/src/data/function/pipe.ts | 0x706b/fncts | 1685a0b1c94bdde35baf278fd7817b3e6c7f2e1d | [
"BSD-3-Clause"
] | null | null | null | /**
* @tsplus macro pipe
* @tsplus fluent fncts.global via
*/
export function pipe<A>(a: A): A;
export function pipe<A, B>(a: A, ab: (a: A) => B): B;
export function pipe<A, B, C>(a: A, ab: (a: A) => B, bc: (b: B) => C): C;
export function pipe<A, B, C, D>(a: A, ab: (a: A) => B, bc: (b: B) => C, cd: (c: C) => D): D;
export function pipe<A, B, C, D, E>(a: A, ab: (a: A) => B, bc: (b: B) => C, cd: (c: C) => D, de: (d: D) => E): E;
export function pipe<A, B, C, D, E, F>(
a: A,
ab: (a: A) => B,
bc: (b: B) => C,
cd: (c: C) => D,
de: (d: D) => E,
ef: (e: E) => F,
): F;
export function pipe<A, B, C, D, E, F, G>(
a: A,
ab: (a: A) => B,
bc: (b: B) => C,
cd: (c: C) => D,
de: (d: D) => E,
ef: (e: E) => F,
fg: (f: F) => G,
): G;
export function pipe<A, B, C, D, E, F, G, H>(
a: A,
ab: (a: A) => B,
bc: (b: B) => C,
cd: (c: C) => D,
de: (d: D) => E,
ef: (e: E) => F,
fg: (f: F) => G,
gh: (g: G) => H,
): H;
export function pipe<A, B, C, D, E, F, G, H, I>(
a: A,
ab: (a: A) => B,
bc: (b: B) => C,
cd: (c: C) => D,
de: (d: D) => E,
ef: (e: E) => F,
fg: (f: F) => G,
gh: (g: G) => H,
hi: (h: H) => I,
): I;
export function pipe<A, B, C, D, E, F, G, H, I, J>(
a: A,
ab: (a: A) => B,
bc: (b: B) => C,
cd: (c: C) => D,
de: (d: D) => E,
ef: (e: E) => F,
fg: (f: F) => G,
gh: (g: G) => H,
hi: (h: H) => I,
ij: (i: I) => J,
): J;
export function pipe<A, B, C, D, E, F, G, H, I, J, K>(
a: A,
ab: (a: A) => B,
bc: (b: B) => C,
cd: (c: C) => D,
de: (d: D) => E,
ef: (e: E) => F,
fg: (f: F) => G,
gh: (g: G) => H,
hi: (h: H) => I,
ij: (i: I) => J,
jk: (j: J) => K,
): K;
export function pipe<A, B, C, D, E, F, G, H, I, J, K, L>(
a: A,
ab: (a: A) => B,
bc: (b: B) => C,
cd: (c: C) => D,
de: (d: D) => E,
ef: (e: E) => F,
fg: (f: F) => G,
gh: (g: G) => H,
hi: (h: H) => I,
ij: (i: I) => J,
jk: (j: J) => K,
kl: (k: K) => L,
): L;
export function pipe<A, B, C, D, E, F, G, H, I, J, K, L, M>(
a: A,
ab: (a: A) => B,
bc: (b: B) => C,
cd: (c: C) => D,
de: (d: D) => E,
ef: (e: E) => F,
fg: (f: F) => G,
gh: (g: G) => H,
hi: (h: H) => I,
ij: (i: I) => J,
jk: (j: J) => K,
kl: (k: K) => L,
lm: (l: L) => M,
): M;
export function pipe<A, B, C, D, E, F, G, H, I, J, K, L, M, N>(
a: A,
ab: (a: A) => B,
bc: (b: B) => C,
cd: (c: C) => D,
de: (d: D) => E,
ef: (e: E) => F,
fg: (f: F) => G,
gh: (g: G) => H,
hi: (h: H) => I,
ij: (i: I) => J,
jk: (j: J) => K,
kl: (k: K) => L,
lm: (l: L) => M,
mn: (m: M) => N,
): N;
export function pipe<A, B, C, D, E, F, G, H, I, J, K, L, M, N, O>(
a: A,
ab: (a: A) => B,
bc: (b: B) => C,
cd: (c: C) => D,
de: (d: D) => E,
ef: (e: E) => F,
fg: (f: F) => G,
gh: (g: G) => H,
hi: (h: H) => I,
ij: (i: I) => J,
jk: (j: J) => K,
kl: (k: K) => L,
lm: (l: L) => M,
mn: (m: M) => N,
no: (n: N) => O,
): O;
export function pipe<A, B, C, D, E, F, G, H, I, J, K, L, M, N, O, P>(
a: A,
ab: (a: A) => B,
bc: (b: B) => C,
cd: (c: C) => D,
de: (d: D) => E,
ef: (e: E) => F,
fg: (f: F) => G,
gh: (g: G) => H,
hi: (h: H) => I,
ij: (i: I) => J,
jk: (j: J) => K,
kl: (k: K) => L,
lm: (l: L) => M,
mn: (m: M) => N,
no: (n: N) => O,
op: (o: O) => P,
): P;
export function pipe<A, B, C, D, E, F, G, H, I, J, K, L, M, N, O, P, Q>(
a: A,
ab: (a: A) => B,
bc: (b: B) => C,
cd: (c: C) => D,
de: (d: D) => E,
ef: (e: E) => F,
fg: (f: F) => G,
gh: (g: G) => H,
hi: (h: H) => I,
ij: (i: I) => J,
jk: (j: J) => K,
kl: (k: K) => L,
lm: (l: L) => M,
mn: (m: M) => N,
no: (n: N) => O,
op: (o: O) => P,
pq: (p: P) => Q,
): Q;
export function pipe<A, B, C, D, E, F, G, H, I, J, K, L, M, N, O, P, Q, R>(
a: A,
ab: (a: A) => B,
bc: (b: B) => C,
cd: (c: C) => D,
de: (d: D) => E,
ef: (e: E) => F,
fg: (f: F) => G,
gh: (g: G) => H,
hi: (h: H) => I,
ij: (i: I) => J,
jk: (j: J) => K,
kl: (k: K) => L,
lm: (l: L) => M,
mn: (m: M) => N,
no: (n: N) => O,
op: (o: O) => P,
pq: (p: P) => Q,
qr: (q: Q) => R,
): R;
export function pipe<A, B, C, D, E, F, G, H, I, J, K, L, M, N, O, P, Q, R, S>(
a: A,
ab: (a: A) => B,
bc: (b: B) => C,
cd: (c: C) => D,
de: (d: D) => E,
ef: (e: E) => F,
fg: (f: F) => G,
gh: (g: G) => H,
hi: (h: H) => I,
ij: (i: I) => J,
jk: (j: J) => K,
kl: (k: K) => L,
lm: (l: L) => M,
mn: (m: M) => N,
no: (n: N) => O,
op: (o: O) => P,
pq: (p: P) => Q,
qr: (q: Q) => R,
rs: (r: R) => S,
): S;
export function pipe<A, B, C, D, E, F, G, H, I, J, K, L, M, N, O, P, Q, R, S, T>(
a: A,
ab: (a: A) => B,
bc: (b: B) => C,
cd: (c: C) => D,
de: (d: D) => E,
ef: (e: E) => F,
fg: (f: F) => G,
gh: (g: G) => H,
hi: (h: H) => I,
ij: (i: I) => J,
jk: (j: J) => K,
kl: (k: K) => L,
lm: (l: L) => M,
mn: (m: M) => N,
no: (n: N) => O,
op: (o: O) => P,
pq: (p: P) => Q,
qr: (q: Q) => R,
rs: (r: R) => S,
st: (s: S) => T,
): T;
export function pipe(
a: unknown,
ab?: Function,
bc?: Function,
cd?: Function,
de?: Function,
ef?: Function,
fg?: Function,
gh?: Function,
hi?: Function,
ij?: Function,
jk?: Function,
kl?: Function,
lm?: Function,
mn?: Function,
no?: Function,
op?: Function,
pq?: Function,
qr?: Function,
rs?: Function,
st?: Function,
): unknown {
switch (arguments.length) {
case 1:
return a;
case 2:
return ab!(a);
case 3:
return bc!(ab!(a));
case 4:
return cd!(bc!(ab!(a)));
case 5:
return de!(cd!(bc!(ab!(a))));
case 6:
return ef!(de!(cd!(bc!(ab!(a)))));
case 7:
return fg!(ef!(de!(cd!(bc!(ab!(a))))));
case 8:
return gh!(fg!(ef!(de!(cd!(bc!(ab!(a)))))));
case 9:
return hi!(gh!(fg!(ef!(de!(cd!(bc!(ab!(a))))))));
case 10:
return ij!(hi!(gh!(fg!(ef!(de!(cd!(bc!(ab!(a)))))))));
case 11:
return jk!(ij!(hi!(gh!(fg!(ef!(de!(cd!(bc!(ab!(a))))))))));
case 12:
return kl!(jk!(ij!(hi!(gh!(fg!(ef!(de!(cd!(bc!(ab!(a)))))))))));
case 13:
return lm!(kl!(jk!(ij!(hi!(gh!(fg!(ef!(de!(cd!(bc!(ab!(a))))))))))));
case 14:
return mn!(lm!(kl!(jk!(ij!(hi!(gh!(fg!(ef!(de!(cd!(bc!(ab!(a)))))))))))));
case 15:
return no!(mn!(lm!(kl!(jk!(ij!(hi!(gh!(fg!(ef!(de!(cd!(bc!(ab!(a))))))))))))));
case 16:
return op!(no!(mn!(lm!(kl!(jk!(ij!(hi!(gh!(fg!(ef!(de!(cd!(bc!(ab!(a)))))))))))))));
case 17:
return pq!(op!(no!(mn!(lm!(kl!(jk!(ij!(hi!(gh!(fg!(ef!(de!(cd!(bc!(ab!(a))))))))))))))));
case 18:
return qr!(pq!(op!(no!(mn!(lm!(kl!(jk!(ij!(hi!(gh!(fg!(ef!(de!(cd!(bc!(ab!(a)))))))))))))))));
case 19:
return rs!(qr!(pq!(op!(no!(mn!(lm!(kl!(jk!(ij!(hi!(gh!(fg!(ef!(de!(cd!(bc!(ab!(a))))))))))))))))));
case 20:
return st!(rs!(qr!(pq!(op!(no!(mn!(lm!(kl!(jk!(ij!(hi!(gh!(fg!(ef!(de!(cd!(bc!(ab!(a)))))))))))))))))));
default:
throw new Error("BUG");
}
}
| 23.019868 | 113 | 0.362342 | 297 | 1 | 20 | 230 | 0 | 0 | 0 | 19 | 2 | 0 | 0 | 44 | 3,727 | 0.06198 | 0 | 0 | 0 | 0 | 0.075697 | 0.007968 | 0.314057 | /**
* @tsplus macro pipe
* @tsplus fluent fncts.global via
*/
export function pipe<A>(a);
export function pipe<A, B>(a, ab);
export function pipe<A, B, C>(a, ab, bc);
export function pipe<A, B, C, D>(a, ab, bc, cd);
export function pipe<A, B, C, D, E>(a, ab, bc, cd, de);
export function pipe<A, B, C, D, E, F>(
a,
ab,
bc,
cd,
de,
ef,
);
export function pipe<A, B, C, D, E, F, G>(
a,
ab,
bc,
cd,
de,
ef,
fg,
);
export function pipe<A, B, C, D, E, F, G, H>(
a,
ab,
bc,
cd,
de,
ef,
fg,
gh,
);
export function pipe<A, B, C, D, E, F, G, H, I>(
a,
ab,
bc,
cd,
de,
ef,
fg,
gh,
hi,
);
export function pipe<A, B, C, D, E, F, G, H, I, J>(
a,
ab,
bc,
cd,
de,
ef,
fg,
gh,
hi,
ij,
);
export function pipe<A, B, C, D, E, F, G, H, I, J, K>(
a,
ab,
bc,
cd,
de,
ef,
fg,
gh,
hi,
ij,
jk,
);
export function pipe<A, B, C, D, E, F, G, H, I, J, K, L>(
a,
ab,
bc,
cd,
de,
ef,
fg,
gh,
hi,
ij,
jk,
kl,
);
export function pipe<A, B, C, D, E, F, G, H, I, J, K, L, M>(
a,
ab,
bc,
cd,
de,
ef,
fg,
gh,
hi,
ij,
jk,
kl,
lm,
);
export function pipe<A, B, C, D, E, F, G, H, I, J, K, L, M, N>(
a,
ab,
bc,
cd,
de,
ef,
fg,
gh,
hi,
ij,
jk,
kl,
lm,
mn,
);
export function pipe<A, B, C, D, E, F, G, H, I, J, K, L, M, N, O>(
a,
ab,
bc,
cd,
de,
ef,
fg,
gh,
hi,
ij,
jk,
kl,
lm,
mn,
no,
);
export function pipe<A, B, C, D, E, F, G, H, I, J, K, L, M, N, O, P>(
a,
ab,
bc,
cd,
de,
ef,
fg,
gh,
hi,
ij,
jk,
kl,
lm,
mn,
no,
op,
);
export function pipe<A, B, C, D, E, F, G, H, I, J, K, L, M, N, O, P, Q>(
a,
ab,
bc,
cd,
de,
ef,
fg,
gh,
hi,
ij,
jk,
kl,
lm,
mn,
no,
op,
pq,
);
export function pipe<A, B, C, D, E, F, G, H, I, J, K, L, M, N, O, P, Q, R>(
a,
ab,
bc,
cd,
de,
ef,
fg,
gh,
hi,
ij,
jk,
kl,
lm,
mn,
no,
op,
pq,
qr,
);
export function pipe<A, B, C, D, E, F, G, H, I, J, K, L, M, N, O, P, Q, R, S>(
a,
ab,
bc,
cd,
de,
ef,
fg,
gh,
hi,
ij,
jk,
kl,
lm,
mn,
no,
op,
pq,
qr,
rs,
);
export function pipe<A, B, C, D, E, F, G, H, I, J, K, L, M, N, O, P, Q, R, S, T>(
a,
ab,
bc,
cd,
de,
ef,
fg,
gh,
hi,
ij,
jk,
kl,
lm,
mn,
no,
op,
pq,
qr,
rs,
st,
);
export function pipe(
a,
ab?,
bc?,
cd?,
de?,
ef?,
fg?,
gh?,
hi?,
ij?,
jk?,
kl?,
lm?,
mn?,
no?,
op?,
pq?,
qr?,
rs?,
st?,
) {
switch (arguments.length) {
case 1:
return a;
case 2:
return ab!(a);
case 3:
return bc!(ab!(a));
case 4:
return cd!(bc!(ab!(a)));
case 5:
return de!(cd!(bc!(ab!(a))));
case 6:
return ef!(de!(cd!(bc!(ab!(a)))));
case 7:
return fg!(ef!(de!(cd!(bc!(ab!(a))))));
case 8:
return gh!(fg!(ef!(de!(cd!(bc!(ab!(a)))))));
case 9:
return hi!(gh!(fg!(ef!(de!(cd!(bc!(ab!(a))))))));
case 10:
return ij!(hi!(gh!(fg!(ef!(de!(cd!(bc!(ab!(a)))))))));
case 11:
return jk!(ij!(hi!(gh!(fg!(ef!(de!(cd!(bc!(ab!(a))))))))));
case 12:
return kl!(jk!(ij!(hi!(gh!(fg!(ef!(de!(cd!(bc!(ab!(a)))))))))));
case 13:
return lm!(kl!(jk!(ij!(hi!(gh!(fg!(ef!(de!(cd!(bc!(ab!(a))))))))))));
case 14:
return mn!(lm!(kl!(jk!(ij!(hi!(gh!(fg!(ef!(de!(cd!(bc!(ab!(a)))))))))))));
case 15:
return no!(mn!(lm!(kl!(jk!(ij!(hi!(gh!(fg!(ef!(de!(cd!(bc!(ab!(a))))))))))))));
case 16:
return op!(no!(mn!(lm!(kl!(jk!(ij!(hi!(gh!(fg!(ef!(de!(cd!(bc!(ab!(a)))))))))))))));
case 17:
return pq!(op!(no!(mn!(lm!(kl!(jk!(ij!(hi!(gh!(fg!(ef!(de!(cd!(bc!(ab!(a))))))))))))))));
case 18:
return qr!(pq!(op!(no!(mn!(lm!(kl!(jk!(ij!(hi!(gh!(fg!(ef!(de!(cd!(bc!(ab!(a)))))))))))))))));
case 19:
return rs!(qr!(pq!(op!(no!(mn!(lm!(kl!(jk!(ij!(hi!(gh!(fg!(ef!(de!(cd!(bc!(ab!(a))))))))))))))))));
case 20:
return st!(rs!(qr!(pq!(op!(no!(mn!(lm!(kl!(jk!(ij!(hi!(gh!(fg!(ef!(de!(cd!(bc!(ab!(a)))))))))))))))))));
default:
throw new Error("BUG");
}
}
|
07887adf09fdbc32f282cb4bb99d5f22ed767db3 | 2,224 | ts | TypeScript | src/views/geometry/RectF.ts | lightningkite/butterfly-web | a369b6aa8e243e6a8f1894cbb97f945206367260 | [
"MIT"
] | 1 | 2022-01-06T14:33:58.000Z | 2022-01-06T14:33:58.000Z | src/views/geometry/RectF.ts | lightningkite/butterfly-web | a369b6aa8e243e6a8f1894cbb97f945206367260 | [
"MIT"
] | null | null | null | src/views/geometry/RectF.ts | lightningkite/butterfly-web | a369b6aa8e243e6a8f1894cbb97f945206367260 | [
"MIT"
] | null | null | null | // Generated by Butterfly TypeScript converter
// File: views/geometry/RectF.kt
// Package: com.lightningkite.butterfly.views.geometry
/* SHARED DECLARATIONS
class RectF {
var right: Float
var bottom: Float
var top: Float
var left: Float
fun set(left: Float, top: Float, right: Float, bottom: Float)
fun set(rect: RectF)
fun centerX(): Float
fun centerY(): Float
fun width(): Float
fun height(): Float
fun inset(dx: Float, dy: Float)
}
*/
//! Declares android.graphics.RectF
export class RectF {
right: number;
bottom: number;
top: number;
left: number;
public constructor(left?: number | RectF, top?: number, right?: number, bottom?: number) {
if(left !== undefined){
if(left instanceof RectF){
this.right = left.right;
this.bottom = left.bottom;
this.top = left.top;
this.left = left.left;
} else {
this.right = right as number;
this.bottom = bottom as number;
this.top = top as number;
this.left = left as number;
}
} else {
this.right = 0;
this.bottom = 0;
this.top = 0;
this.left = 0;
}
}
set(left: number | RectF, top?: number, right?: number, bottom?: number) {
if(left instanceof RectF){
this.right = left.right;
this.bottom = left.bottom;
this.top = left.top;
this.left = left.left;
} else {
this.right = right as number;
this.bottom = bottom as number;
this.top = top as number;
this.left = left as number;
}
}
centerX(): number { return (this.left + this.right) / 2 }
centerY(): number { return (this.top + this.bottom) / 2 }
width(): number { return this.right - this.left }
height(): number { return this.bottom - this.top }
inset(dx: number, dy: number): RectF {
const r = new RectF();
r.left = this.left + dx;
r.right = this.right - dx;
r.top = this.top + dy;
r.bottom = this.bottom - dy;
return r
}
} | 30.465753 | 94 | 0.534622 | 51 | 7 | 0 | 10 | 1 | 4 | 0 | 0 | 26 | 1 | 10 | 5.571429 | 572 | 0.02972 | 0.001748 | 0.006993 | 0.001748 | 0.017483 | 0 | 1.181818 | 0.243955 | // Generated by Butterfly TypeScript converter
// File: views/geometry/RectF.kt
// Package: com.lightningkite.butterfly.views.geometry
/* SHARED DECLARATIONS
class RectF {
var right: Float
var bottom: Float
var top: Float
var left: Float
fun set(left: Float, top: Float, right: Float, bottom: Float)
fun set(rect: RectF)
fun centerX(): Float
fun centerY(): Float
fun width(): Float
fun height(): Float
fun inset(dx: Float, dy: Float)
}
*/
//! Declares android.graphics.RectF
export class RectF {
right;
bottom;
top;
left;
public constructor(left?, top?, right?, bottom?) {
if(left !== undefined){
if(left instanceof RectF){
this.right = left.right;
this.bottom = left.bottom;
this.top = left.top;
this.left = left.left;
} else {
this.right = right as number;
this.bottom = bottom as number;
this.top = top as number;
this.left = left as number;
}
} else {
this.right = 0;
this.bottom = 0;
this.top = 0;
this.left = 0;
}
}
set(left, top?, right?, bottom?) {
if(left instanceof RectF){
this.right = left.right;
this.bottom = left.bottom;
this.top = left.top;
this.left = left.left;
} else {
this.right = right as number;
this.bottom = bottom as number;
this.top = top as number;
this.left = left as number;
}
}
centerX() { return (this.left + this.right) / 2 }
centerY() { return (this.top + this.bottom) / 2 }
width() { return this.right - this.left }
height() { return this.bottom - this.top }
inset(dx, dy) {
const r = new RectF();
r.left = this.left + dx;
r.right = this.right - dx;
r.top = this.top + dy;
r.bottom = this.bottom - dy;
return r
}
} |
07dca6e5eac4011cf377c46065d55486f7b1ec63 | 1,550 | ts | TypeScript | front/src/app/util/array-util.ts | kernevez/sutom | d3c4bd45235191f531990e2d4461c63121991f19 | [
"BSD-3-Clause"
] | 1 | 2022-03-10T22:15:25.000Z | 2022-03-10T22:15:25.000Z | front/src/app/util/array-util.ts | kernevez/sutom | d3c4bd45235191f531990e2d4461c63121991f19 | [
"BSD-3-Clause"
] | null | null | null | front/src/app/util/array-util.ts | kernevez/sutom | d3c4bd45235191f531990e2d4461c63121991f19 | [
"BSD-3-Clause"
] | 1 | 2022-03-10T22:14:36.000Z | 2022-03-10T22:14:36.000Z | export class ArrayUtil {
public static get_index<T>(array: Array<T>, obj: T): number {
let index = -1;
let i = 0;
while (index === -1 && i < array.length) {
if (array[i] === obj) {
index = i;
}
i++;
}
return index;
}
public static remove_from_array<T>(array: Array<T>, obj: T): boolean {
if (array.indexOf(obj) >= 0) {
array.splice(this.get_index(array, obj), 1);
return true;
}
return false;
}
public static add_first_no_duplicate<T>(array: Array<T>, obj: T): boolean {
if (!(array.indexOf(obj) >= 0)) {
array.unshift(obj);
return true;
}
return false;
}
public static diff<T>(array1: Array<T>, array2: Array<T>): Array<T> {
return array1.filter(item => array2.indexOf(item) < 0);
}
public static find_nb_connected(x: number, y: number, array: Array<Array<number>>): number {
const canUp = (x - 1 >= 0);
const canDown = (x + 1 < array.length);
const canRight = (y + 1 < array[0].length);
const canLeft = (y - 1 >= 0);
const value = array[x][y];
let up = 0;
let down = 0;
let right = 0;
let left = 0;
array[x][y] = 2;
if (canUp && array[x - 1][y] === value) {
up = this.find_nb_connected(x - 1, y, array);
}
if (canDown && array[x + 1][y] === value) {
down = this.find_nb_connected(x + 1, y, array);
}
if (canLeft && array[x][y - 1] === value) {
left = this.find_nb_connected(x, y - 1, array);
}
if (canRight && array[x][y + 1] === value) {
right = this.find_nb_connected(x, y + 1, array);
}
return up + left + right + down + 1;
}
} | 24.21875 | 93 | 0.57871 | 55 | 6 | 0 | 12 | 11 | 0 | 2 | 0 | 7 | 1 | 0 | 7.333333 | 629 | 0.028617 | 0.017488 | 0 | 0.00159 | 0 | 0 | 0.241379 | 0.296916 | export class ArrayUtil {
public static get_index<T>(array, obj) {
let index = -1;
let i = 0;
while (index === -1 && i < array.length) {
if (array[i] === obj) {
index = i;
}
i++;
}
return index;
}
public static remove_from_array<T>(array, obj) {
if (array.indexOf(obj) >= 0) {
array.splice(this.get_index(array, obj), 1);
return true;
}
return false;
}
public static add_first_no_duplicate<T>(array, obj) {
if (!(array.indexOf(obj) >= 0)) {
array.unshift(obj);
return true;
}
return false;
}
public static diff<T>(array1, array2) {
return array1.filter(item => array2.indexOf(item) < 0);
}
public static find_nb_connected(x, y, array) {
const canUp = (x - 1 >= 0);
const canDown = (x + 1 < array.length);
const canRight = (y + 1 < array[0].length);
const canLeft = (y - 1 >= 0);
const value = array[x][y];
let up = 0;
let down = 0;
let right = 0;
let left = 0;
array[x][y] = 2;
if (canUp && array[x - 1][y] === value) {
up = this.find_nb_connected(x - 1, y, array);
}
if (canDown && array[x + 1][y] === value) {
down = this.find_nb_connected(x + 1, y, array);
}
if (canLeft && array[x][y - 1] === value) {
left = this.find_nb_connected(x, y - 1, array);
}
if (canRight && array[x][y + 1] === value) {
right = this.find_nb_connected(x, y + 1, array);
}
return up + left + right + down + 1;
}
} |
6b0a3d05e0066843e057e556c01384fcd7d91b33 | 2,542 | ts | TypeScript | src/clockwiseSpiral/index.ts | snelling-a/codewars | 54d568dab42a5112240932429dc38763481c1131 | [
"MIT"
] | null | null | null | src/clockwiseSpiral/index.ts | snelling-a/codewars | 54d568dab42a5112240932429dc38763481c1131 | [
"MIT"
] | 1 | 2022-02-15T08:23:56.000Z | 2022-02-15T08:29:40.000Z | src/clockwiseSpiral/index.ts | snelling-a/codewars | 54d568dab42a5112240932429dc38763481c1131 | [
"MIT"
] | null | null | null | /*
https://www.codewars.com/kata/536a155256eb459b8700077e
Do you know how to make a spiral? Let's test it!
Classic definition: A spiral is a curve which emanates from a central point, getting progressively farther away
as it revolves around the point.
Your objective is to complete a function createSpiral(N) that receives an integer N and returns an NxN two-dimensional
array with numbers 1 through NxN represented as a clockwise spiral.
Return an empty array if N < 1 or N is not int / number
Examples:
N = 3 Output: [[1,2,3],[8,9,4],[7,6,5]]
1 2 3
8 9 4
7 6 5
N = 4 Output: [[1,2,3,4],[12,13,14,5],[11,16,15,6],[10,9,8,7]]
1 2 3 4
12 13 14 5
11 16 15 6
10 9 8 7
N = 5 Output: [[1,2,3,4,5],[16,17,18,19,6],[15,24,25,20,7],[14,23,22,21,8],[13,12,11,10,9]]
1 2 3 4 5
16 17 18 19 6
15 24 25 20 7
14 23 22 21 8
13 12 11 10 9
*/
const create2dArray = (height: number, width = height, fill: unknown = 0) =>
Array.from({ length: height }, () => new Array(width).fill(fill));
export function createSpiral(N: unknown) {
if (!Number.isInteger(N) || typeof N !== 'number' || N < 1) {
return [];
}
const returnArray = create2dArray(N);
const counter = { x: 0, y: 0, count: 1, direction: 'right' };
let { x, y, count, direction } = counter;
while (count <= N ** 2) {
returnArray[x][y] = count;
switch (direction) {
case 'right':
if (y + 1 < N && returnArray[x][y + 1] === 0) {
y += 1;
} else {
direction = 'down';
x += 1;
}
break;
case 'down':
if (x + 1 < N && returnArray[x + 1][y] === 0) {
x += 1;
} else {
direction = 'left';
y -= 1;
}
break;
case 'left':
if (y - 1 >= 0 && returnArray[x][y - 1] === 0) {
y -= 1;
} else {
direction = 'up';
x -= 1;
}
break;
case 'up':
if (x - 1 >= 0 && returnArray[x - 1][y] === 0) {
x -= 1;
} else {
direction = 'right';
y += 1;
}
break;
default:
break;
}
count += 1;
}
return returnArray;
}
| 27.042553 | 118 | 0.442958 | 51 | 3 | 0 | 4 | 4 | 0 | 1 | 0 | 3 | 0 | 1 | 16.333333 | 850 | 0.008235 | 0.004706 | 0 | 0 | 0.001176 | 0 | 0.272727 | 0.204434 | /*
https://www.codewars.com/kata/536a155256eb459b8700077e
Do you know how to make a spiral? Let's test it!
Classic definition: A spiral is a curve which emanates from a central point, getting progressively farther away
as it revolves around the point.
Your objective is to complete a function createSpiral(N) that receives an integer N and returns an NxN two-dimensional
array with numbers 1 through NxN represented as a clockwise spiral.
Return an empty array if N < 1 or N is not int / number
Examples:
N = 3 Output: [[1,2,3],[8,9,4],[7,6,5]]
1 2 3
8 9 4
7 6 5
N = 4 Output: [[1,2,3,4],[12,13,14,5],[11,16,15,6],[10,9,8,7]]
1 2 3 4
12 13 14 5
11 16 15 6
10 9 8 7
N = 5 Output: [[1,2,3,4,5],[16,17,18,19,6],[15,24,25,20,7],[14,23,22,21,8],[13,12,11,10,9]]
1 2 3 4 5
16 17 18 19 6
15 24 25 20 7
14 23 22 21 8
13 12 11 10 9
*/
/* Example usages of 'create2dArray' are shown below:
create2dArray(N);
*/
const create2dArray = (height, width = height, fill = 0) =>
Array.from({ length: height }, () => new Array(width).fill(fill));
export function createSpiral(N) {
if (!Number.isInteger(N) || typeof N !== 'number' || N < 1) {
return [];
}
const returnArray = create2dArray(N);
const counter = { x: 0, y: 0, count: 1, direction: 'right' };
let { x, y, count, direction } = counter;
while (count <= N ** 2) {
returnArray[x][y] = count;
switch (direction) {
case 'right':
if (y + 1 < N && returnArray[x][y + 1] === 0) {
y += 1;
} else {
direction = 'down';
x += 1;
}
break;
case 'down':
if (x + 1 < N && returnArray[x + 1][y] === 0) {
x += 1;
} else {
direction = 'left';
y -= 1;
}
break;
case 'left':
if (y - 1 >= 0 && returnArray[x][y - 1] === 0) {
y -= 1;
} else {
direction = 'up';
x -= 1;
}
break;
case 'up':
if (x - 1 >= 0 && returnArray[x - 1][y] === 0) {
x -= 1;
} else {
direction = 'right';
y += 1;
}
break;
default:
break;
}
count += 1;
}
return returnArray;
}
|
6b0c8a9d842c664f516c2e26372a2db60384ba9f | 1,872 | ts | TypeScript | src/index.ts | Cacivy/matching.js | b5535e81711a9b8ae25451433fdbfed49057c9b1 | [
"MIT"
] | null | null | null | src/index.ts | Cacivy/matching.js | b5535e81711a9b8ae25451433fdbfed49057c9b1 | [
"MIT"
] | 1 | 2022-01-22T11:18:05.000Z | 2022-01-22T11:18:05.000Z | src/index.ts | Cacivy/matching.js | b5535e81711a9b8ae25451433fdbfed49057c9b1 | [
"MIT"
] | null | null | null | export interface Option<T> {
/**
* start chartacter
*/
startChar: string
/**
* end chartacter
*/
endChar: string
/**
* matching map
*/
cb?: (str: string) => T
/**
* greedy mode
*/
isGreedy?: boolean
}
export type Matching<T = any> = (str: string, option: Option<T>) => T[]
/**
* step: init => start => init...
*
* @enum {number}
*/
export enum Status {
init,
start
}
const matching: Matching = (str = '', option) => {
const { startChar = '', endChar = '', cb, isGreedy = false } = option
let strList: string[] = []
let tempStrArr: string[] = []
let status = Status.init
const push = (trigger = false) => {
let str = tempStrArr.join('')
if (!str) {
return
}
if (trigger && cb) {
str = cb(str)
}
strList.push(str)
tempStrArr = []
}
for (let i = 0; i < str.length; i++) {
const length = status === Status.init ? startChar.length : endChar.length
const val = str.slice(i, i + length)
if (val === startChar && status === Status.init) {
status = Status.start
push()
i+=(length - 1)
continue
}
if (val === endChar && status === Status.start) {
if (isGreedy) {
push(true)
const [ first, ...content ] = strList
strList = [first, content.join('')]
tempStrArr.push(val)
} else {
push(true)
status = Status.init
}
i+=(length - 1)
continue
}
tempStrArr.push(str[i])
}
if (isGreedy) {
tempStrArr.splice(0, 1)
}
push()
return strList
}
/*
export const matchingByRegExp: Matching = (str = '', option) => {
const { startChar = '', endChar = '', cb, isGreedy = false } = option
const regexp = new RegExp(`${startChar}(\\S*${isGreedy ? '?' : ''})${endChar}`)
return str.split(regexp).filter(x => !!x)
}
*/
export default matching
| 20.347826 | 81 | 0.537927 | 58 | 2 | 0 | 3 | 11 | 4 | 1 | 1 | 7 | 2 | 0 | 26.5 | 573 | 0.008726 | 0.019197 | 0.006981 | 0.00349 | 0 | 0.05 | 0.35 | 0.257906 | export interface Option<T> {
/**
* start chartacter
*/
startChar
/**
* end chartacter
*/
endChar
/**
* matching map
*/
cb?
/**
* greedy mode
*/
isGreedy?
}
export type Matching<T = any> = (str, option) => T[]
/**
* step: init => start => init...
*
* @enum {number}
*/
export enum Status {
init,
start
}
/* Example usages of 'matching' are shown below:
export const matchingByRegExp: Matching = (str = '', option) => {
const { startChar = '', endChar = '', cb, isGreedy = false } = option
const regexp = new RegExp(`${startChar}(\\S*${isGreedy ? '?' : ''})${endChar}`)
return str.split(regexp).filter(x => !!x)
}
;
*/
const matching = (str = '', option) => {
const { startChar = '', endChar = '', cb, isGreedy = false } = option
let strList = []
let tempStrArr = []
let status = Status.init
/* Example usages of 'push' are shown below:
strList.push(str);
push();
push(true);
tempStrArr.push(val);
tempStrArr.push(str[i]);
*/
const push = (trigger = false) => {
let str = tempStrArr.join('')
if (!str) {
return
}
if (trigger && cb) {
str = cb(str)
}
strList.push(str)
tempStrArr = []
}
for (let i = 0; i < str.length; i++) {
const length = status === Status.init ? startChar.length : endChar.length
const val = str.slice(i, i + length)
if (val === startChar && status === Status.init) {
status = Status.start
push()
i+=(length - 1)
continue
}
if (val === endChar && status === Status.start) {
if (isGreedy) {
push(true)
const [ first, ...content ] = strList
strList = [first, content.join('')]
tempStrArr.push(val)
} else {
push(true)
status = Status.init
}
i+=(length - 1)
continue
}
tempStrArr.push(str[i])
}
if (isGreedy) {
tempStrArr.splice(0, 1)
}
push()
return strList
}
/*
export const matchingByRegExp: Matching = (str = '', option) => {
const { startChar = '', endChar = '', cb, isGreedy = false } = option
const regexp = new RegExp(`${startChar}(\\S*${isGreedy ? '?' : ''})${endChar}`)
return str.split(regexp).filter(x => !!x)
}
*/
export default matching
|
6b2e48994d25dfb77d9f951487af828409217c22 | 2,523 | ts | TypeScript | src/workflows/generator-based.ts | artemeknyazev/ts-experiments | 76f09b108bbfe81283d8e93691250859fd1ca00e | [
"MIT"
] | 2 | 2022-01-01T22:08:39.000Z | 2022-01-31T17:22:24.000Z | src/workflows/generator-based.ts | artemeknyazev/ts-experiments | 76f09b108bbfe81283d8e93691250859fd1ca00e | [
"MIT"
] | null | null | null | src/workflows/generator-based.ts | artemeknyazev/ts-experiments | 76f09b108bbfe81283d8e93691250859fd1ca00e | [
"MIT"
] | 1 | 2022-01-01T22:08:42.000Z | 2022-01-01T22:08:42.000Z | /* Types */
type Tx<T> = () => Promise<T>;
type Cx = () => Promise<unknown>;
export class ReadOnly<T> {
constructor(public tx: Tx<T>) {}
}
export class Mutating<T> {
constructor(public tx: Tx<T>, public cx: Cx) {}
}
export class Pivot<T> {
constructor(public tx: Tx<T>) {}
}
type Step<T> = ReadOnly<T> | Mutating<T> | Pivot<T>;
export type Workflow = Generator<Step<any>, void, any>;
/* Constructors */
export const readOnly = <T>(tx: Tx<T>): ReadOnly<T> => new ReadOnly<T>(tx);
export const mutating = <T>(tx: Tx<T>, cx: Cx): Mutating<T> =>
new Mutating<T>(tx, cx);
export const pivot = <T>(tx: Tx<T>): Pivot<T> => new Pivot<T>(tx);
/* Workflow executor */
export async function run(workflow: Workflow): Promise<void> {
// a list of compensating functions
let cxs: Cx[] = [];
// a number of pivot operations happened during the workflow
let nPivots: number = 0;
// should the workflow be unrolled
let unrollReason: unknown;
let next: IteratorResult<Step<unknown>>;
let res: unknown;
try {
next = workflow.next();
} catch (e) {
unrollReason = e;
}
while (!unrollReason && !next!.done) {
const flow = next!.value;
try {
// execute async operation
res = await flow.tx();
} catch (e1) {
// async exception caught
try {
// try rethrowing into workflow -- this acquires a next workflow step;
// compensating operation is not added, because the atomic forward
// operation didn't succeed, so nothing to compensate
next = workflow.throw(e1);
continue;
} catch (e2) {
// rethrowing didn't succeed, unroll
unrollReason = e2;
break;
}
}
// async operation succeeds, register its aftereffects
if (flow instanceof Mutating) {
cxs.push(flow.cx);
} else if (flow instanceof Pivot) {
nPivots++;
}
// try acquiring next workflow step
try {
next = workflow.next(res);
continue;
} catch (e) {
// caught a sync exception that is not caught inside workflow, unroll
unrollReason = e;
break;
}
}
// unroll if error happened
if (unrollReason) {
// workflow is not revertible if there were completed pivot operations
if (nPivots) {
throw unrollReason;
}
for (const cx of cxs.reverse()) {
// compensating function error means the state is unknown
// this can only be handled by a caller, so no try-catch
await cx();
}
throw unrollReason;
}
}
| 24.259615 | 78 | 0.612366 | 64 | 7 | 0 | 9 | 9 | 0 | 0 | 2 | 7 | 7 | 2 | 6.857143 | 719 | 0.022253 | 0.012517 | 0 | 0.009736 | 0.002782 | 0.08 | 0.28 | 0.276667 | /* Types */
type Tx<T> = () => Promise<T>;
type Cx = () => Promise<unknown>;
export class ReadOnly<T> {
constructor(public tx) {}
}
export class Mutating<T> {
constructor(public tx, public cx) {}
}
export class Pivot<T> {
constructor(public tx) {}
}
type Step<T> = ReadOnly<T> | Mutating<T> | Pivot<T>;
export type Workflow = Generator<Step<any>, void, any>;
/* Constructors */
export const readOnly = <T>(tx) => new ReadOnly<T>(tx);
export const mutating = <T>(tx, cx) =>
new Mutating<T>(tx, cx);
export const pivot = <T>(tx) => new Pivot<T>(tx);
/* Workflow executor */
export async function run(workflow) {
// a list of compensating functions
let cxs = [];
// a number of pivot operations happened during the workflow
let nPivots = 0;
// should the workflow be unrolled
let unrollReason;
let next;
let res;
try {
next = workflow.next();
} catch (e) {
unrollReason = e;
}
while (!unrollReason && !next!.done) {
const flow = next!.value;
try {
// execute async operation
res = await flow.tx();
} catch (e1) {
// async exception caught
try {
// try rethrowing into workflow -- this acquires a next workflow step;
// compensating operation is not added, because the atomic forward
// operation didn't succeed, so nothing to compensate
next = workflow.throw(e1);
continue;
} catch (e2) {
// rethrowing didn't succeed, unroll
unrollReason = e2;
break;
}
}
// async operation succeeds, register its aftereffects
if (flow instanceof Mutating) {
cxs.push(flow.cx);
} else if (flow instanceof Pivot) {
nPivots++;
}
// try acquiring next workflow step
try {
next = workflow.next(res);
continue;
} catch (e) {
// caught a sync exception that is not caught inside workflow, unroll
unrollReason = e;
break;
}
}
// unroll if error happened
if (unrollReason) {
// workflow is not revertible if there were completed pivot operations
if (nPivots) {
throw unrollReason;
}
for (const cx of cxs.reverse()) {
// compensating function error means the state is unknown
// this can only be handled by a caller, so no try-catch
await cx();
}
throw unrollReason;
}
}
|
6b8614c1b21d612dd7db06070cf5e0493e8f5a9d | 6,193 | ts | TypeScript | src/sha1.ts | liammoat/hashapass-core | 85c26f10de10dd493385d4836797946528ffee89 | [
"MIT"
] | null | null | null | src/sha1.ts | liammoat/hashapass-core | 85c26f10de10dd493385d4836797946528ffee89 | [
"MIT"
] | 1 | 2022-01-29T15:17:22.000Z | 2022-01-29T15:17:22.000Z | src/sha1.ts | liammoat/hashapass-core | 85c26f10de10dd493385d4836797946528ffee89 | [
"MIT"
] | null | null | null | /*
* A JavaScript implementation of the Secure Hash Algorithm, SHA-1, as defined
* in FIPS PUB 180-1
* Version 2.1 Copyright Paul Johnston 2000 - 2002.
* Other contributors: Greg Holt, Andrew Kepert, Ydnar, Lostinet
* Distributed under the BSD License
* See http://pajhome.org.uk/crypt/md5 for details.
*/
/*
* Configurable letiables. You may need to tweak these to be compatible with
* the server-side, but the defaults work in most cases.
*/
let hexcase = 0; /* hex output format. 0 - lowercase; 1 - uppercase */
let b64pad = ""; /* base-64 pad character. "=" for strict RFC compliance */
let chrsz = 8; /* bits per input character. 8 - ASCII; 16 - Unicode */
/*
* These are the functions you'll usually want to call
* They take string arguments and return either hex or base-64 encoded strings
*/
export function hex_sha1(s: string): string { return binb2hex(core_sha1(str2binb(s), s.length * chrsz)); }
export function b64_sha1(s: string): string { return binb2b64(core_sha1(str2binb(s), s.length * chrsz)); }
export function str_sha1(s: string): string { return binb2str(core_sha1(str2binb(s), s.length * chrsz)); }
export function hex_hmac_sha1(key: string, data: string): string { return binb2hex(core_hmac_sha1(key, data)); }
export function b64_hmac_sha1(key: string, data: string): string { return binb2b64(core_hmac_sha1(key, data)); }
export function str_hmac_sha1(key: string, data: string): string { return binb2str(core_hmac_sha1(key, data)); }
/*
* Perform a simple self-test to see if the VM is working
*/
function sha1_vm_test(): boolean {
return hex_sha1("abc") == "a9993e364706816aba3e25717850c26c9cd0d89d";
}
/*
* Calculate the SHA-1 of an array of big-endian words, and a bit length
*/
function core_sha1(x: number[], len: number): number[] {
/* append padding */
x[len >> 5] |= 0x80 << (24 - len % 32);
x[((len + 64 >> 9) << 4) + 15] = len;
let w = Array(80);
let a = 1732584193;
let b = -271733879;
let c = -1732584194;
let d = 271733878;
let e = -1009589776;
for (let i = 0; i < x.length; i += 16) {
let olda = a;
let oldb = b;
let oldc = c;
let oldd = d;
let olde = e;
for (let j = 0; j < 80; j++) {
if (j < 16) w[j] = x[i + j];
else w[j] = rol(w[j - 3] ^ w[j - 8] ^ w[j - 14] ^ w[j - 16], 1);
let t = safe_add(safe_add(rol(a, 5), sha1_ft(j, b, c, d)),
safe_add(safe_add(e, w[j]), sha1_kt(j)));
e = d;
d = c;
c = rol(b, 30);
b = a;
a = t;
}
a = safe_add(a, olda);
b = safe_add(b, oldb);
c = safe_add(c, oldc);
d = safe_add(d, oldd);
e = safe_add(e, olde);
}
return Array(a, b, c, d, e);
}
/*
* Perform the appropriate triplet combination function for the current
* iteration
*/
function sha1_ft(t: number, b: number, c: number, d: number): number {
if (t < 20) return (b & c) | ((~b) & d);
if (t < 40) return b ^ c ^ d;
if (t < 60) return (b & c) | (b & d) | (c & d);
return b ^ c ^ d;
}
/*
* Determine the appropriate additive constant for the current iteration
*/
function sha1_kt(t: number): number {
return (t < 20) ? 1518500249 : (t < 40) ? 1859775393 :
(t < 60) ? -1894007588 : -899497514;
}
/*
* Calculate the HMAC-SHA1 of a key and some data
*/
function core_hmac_sha1(key: string, data: string): number[] {
let bkey = str2binb(key);
if (bkey.length > 16) bkey = core_sha1(bkey, key.length * chrsz);
let ipad = Array(16), opad = Array(16);
for (let i = 0; i < 16; i++) {
ipad[i] = bkey[i] ^ 0x36363636;
opad[i] = bkey[i] ^ 0x5C5C5C5C;
}
let hash = core_sha1(ipad.concat(str2binb(data)), 512 + data.length * chrsz);
return core_sha1(opad.concat(hash), 512 + 160);
}
/*
* Add integers, wrapping at 2^32. This uses 16-bit operations internally
* to work around bugs in some JS interpreters.
*/
function safe_add(x: number, y: number): number {
let lsw = (x & 0xFFFF) + (y & 0xFFFF);
let msw = (x >> 16) + (y >> 16) + (lsw >> 16);
return (msw << 16) | (lsw & 0xFFFF);
}
/*
* Bitwise rotate a 32-bit number to the left.
*/
function rol(num: number, cnt: number): number {
return (num << cnt) | (num >>> (32 - cnt));
}
/*
* Convert an 8-bit or 16-bit string to an array of big-endian words
* In 8-bit function, characters >255 have their hi-byte silently ignored.
*/
function str2binb(str: string): number[] {
let bin = Array();
let mask = (1 << chrsz) - 1;
for (let i = 0; i < str.length * chrsz; i += chrsz)
bin[i >> 5] |= (str.charCodeAt(i / chrsz) & mask) << (24 - i % 32);
return bin;
}
/*
* Convert an array of big-endian words to a string
*/
function binb2str(bin: number[]): string {
let str = "";
let mask = (1 << chrsz) - 1;
for (let i = 0; i < bin.length * 32; i += chrsz)
str += String.fromCharCode((bin[i >> 5] >>> (24 - i % 32)) & mask);
return str;
}
/*
* Convert an array of big-endian words to a hex string.
*/
function binb2hex(binarray: any[]): string {
let hex_tab = hexcase ? "0123456789ABCDEF" : "0123456789abcdef";
let str = "";
for (let i = 0; i < binarray.length * 4; i++) {
str += hex_tab.charAt((binarray[i >> 2] >> ((3 - i % 4) * 8 + 4)) & 0xF) +
hex_tab.charAt((binarray[i >> 2] >> ((3 - i % 4) * 8)) & 0xF);
}
return str;
}
/*
* Convert an array of big-endian words to a base-64 string
*/
function binb2b64(binarray: any[]): string {
let tab = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
let str = "";
for (let i = 0; i < binarray.length * 4; i += 3) {
let triplet = (((binarray[i >> 2] >> 8 * (3 - i % 4)) & 0xFF) << 16)
| (((binarray[i + 1 >> 2] >> 8 * (3 - (i + 1) % 4)) & 0xFF) << 8)
| ((binarray[i + 2 >> 2] >> 8 * (3 - (i + 2) % 4)) & 0xFF);
for (let j = 0; j < 4; j++) {
if (i * 8 + j * 6 > binarray.length * 32) str += b64pad;
else str += tab.charAt((triplet >> 6 * (3 - j)) & 0x3F);
}
}
return str;
} | 33.475676 | 112 | 0.572259 | 112 | 17 | 0 | 26 | 38 | 0 | 11 | 2 | 41 | 0 | 0 | 5.117647 | 2,424 | 0.017739 | 0.015677 | 0 | 0 | 0 | 0.024691 | 0.506173 | 0.264526 | /*
* A JavaScript implementation of the Secure Hash Algorithm, SHA-1, as defined
* in FIPS PUB 180-1
* Version 2.1 Copyright Paul Johnston 2000 - 2002.
* Other contributors: Greg Holt, Andrew Kepert, Ydnar, Lostinet
* Distributed under the BSD License
* See http://pajhome.org.uk/crypt/md5 for details.
*/
/*
* Configurable letiables. You may need to tweak these to be compatible with
* the server-side, but the defaults work in most cases.
*/
let hexcase = 0; /* hex output format. 0 - lowercase; 1 - uppercase */
let b64pad = ""; /* base-64 pad character. "=" for strict RFC compliance */
let chrsz = 8; /* bits per input character. 8 - ASCII; 16 - Unicode */
/*
* These are the functions you'll usually want to call
* They take string arguments and return either hex or base-64 encoded strings
*/
export /* Example usages of 'hex_sha1' are shown below:
hex_sha1("abc") == "a9993e364706816aba3e25717850c26c9cd0d89d";
*/
function hex_sha1(s) { return binb2hex(core_sha1(str2binb(s), s.length * chrsz)); }
export function b64_sha1(s) { return binb2b64(core_sha1(str2binb(s), s.length * chrsz)); }
export function str_sha1(s) { return binb2str(core_sha1(str2binb(s), s.length * chrsz)); }
export function hex_hmac_sha1(key, data) { return binb2hex(core_hmac_sha1(key, data)); }
export function b64_hmac_sha1(key, data) { return binb2b64(core_hmac_sha1(key, data)); }
export function str_hmac_sha1(key, data) { return binb2str(core_hmac_sha1(key, data)); }
/*
* Perform a simple self-test to see if the VM is working
*/
function sha1_vm_test() {
return hex_sha1("abc") == "a9993e364706816aba3e25717850c26c9cd0d89d";
}
/*
* Calculate the SHA-1 of an array of big-endian words, and a bit length
*/
/* Example usages of 'core_sha1' are shown below:
binb2hex(core_sha1(str2binb(s), s.length * chrsz));
binb2b64(core_sha1(str2binb(s), s.length * chrsz));
binb2str(core_sha1(str2binb(s), s.length * chrsz));
bkey = core_sha1(bkey, key.length * chrsz);
core_sha1(ipad.concat(str2binb(data)), 512 + data.length * chrsz);
core_sha1(opad.concat(hash), 512 + 160);
*/
function core_sha1(x, len) {
/* append padding */
x[len >> 5] |= 0x80 << (24 - len % 32);
x[((len + 64 >> 9) << 4) + 15] = len;
let w = Array(80);
let a = 1732584193;
let b = -271733879;
let c = -1732584194;
let d = 271733878;
let e = -1009589776;
for (let i = 0; i < x.length; i += 16) {
let olda = a;
let oldb = b;
let oldc = c;
let oldd = d;
let olde = e;
for (let j = 0; j < 80; j++) {
if (j < 16) w[j] = x[i + j];
else w[j] = rol(w[j - 3] ^ w[j - 8] ^ w[j - 14] ^ w[j - 16], 1);
let t = safe_add(safe_add(rol(a, 5), sha1_ft(j, b, c, d)),
safe_add(safe_add(e, w[j]), sha1_kt(j)));
e = d;
d = c;
c = rol(b, 30);
b = a;
a = t;
}
a = safe_add(a, olda);
b = safe_add(b, oldb);
c = safe_add(c, oldc);
d = safe_add(d, oldd);
e = safe_add(e, olde);
}
return Array(a, b, c, d, e);
}
/*
* Perform the appropriate triplet combination function for the current
* iteration
*/
/* Example usages of 'sha1_ft' are shown below:
safe_add(safe_add(rol(a, 5), sha1_ft(j, b, c, d)), safe_add(safe_add(e, w[j]), sha1_kt(j)));
*/
function sha1_ft(t, b, c, d) {
if (t < 20) return (b & c) | ((~b) & d);
if (t < 40) return b ^ c ^ d;
if (t < 60) return (b & c) | (b & d) | (c & d);
return b ^ c ^ d;
}
/*
* Determine the appropriate additive constant for the current iteration
*/
/* Example usages of 'sha1_kt' are shown below:
safe_add(safe_add(rol(a, 5), sha1_ft(j, b, c, d)), safe_add(safe_add(e, w[j]), sha1_kt(j)));
*/
function sha1_kt(t) {
return (t < 20) ? 1518500249 : (t < 40) ? 1859775393 :
(t < 60) ? -1894007588 : -899497514;
}
/*
* Calculate the HMAC-SHA1 of a key and some data
*/
/* Example usages of 'core_hmac_sha1' are shown below:
binb2hex(core_hmac_sha1(key, data));
binb2b64(core_hmac_sha1(key, data));
binb2str(core_hmac_sha1(key, data));
*/
function core_hmac_sha1(key, data) {
let bkey = str2binb(key);
if (bkey.length > 16) bkey = core_sha1(bkey, key.length * chrsz);
let ipad = Array(16), opad = Array(16);
for (let i = 0; i < 16; i++) {
ipad[i] = bkey[i] ^ 0x36363636;
opad[i] = bkey[i] ^ 0x5C5C5C5C;
}
let hash = core_sha1(ipad.concat(str2binb(data)), 512 + data.length * chrsz);
return core_sha1(opad.concat(hash), 512 + 160);
}
/*
* Add integers, wrapping at 2^32. This uses 16-bit operations internally
* to work around bugs in some JS interpreters.
*/
/* Example usages of 'safe_add' are shown below:
safe_add(safe_add(rol(a, 5), sha1_ft(j, b, c, d)), safe_add(safe_add(e, w[j]), sha1_kt(j)));
a = safe_add(a, olda);
b = safe_add(b, oldb);
c = safe_add(c, oldc);
d = safe_add(d, oldd);
e = safe_add(e, olde);
*/
function safe_add(x, y) {
let lsw = (x & 0xFFFF) + (y & 0xFFFF);
let msw = (x >> 16) + (y >> 16) + (lsw >> 16);
return (msw << 16) | (lsw & 0xFFFF);
}
/*
* Bitwise rotate a 32-bit number to the left.
*/
/* Example usages of 'rol' are shown below:
w[j] = rol(w[j - 3] ^ w[j - 8] ^ w[j - 14] ^ w[j - 16], 1);
safe_add(safe_add(rol(a, 5), sha1_ft(j, b, c, d)), safe_add(safe_add(e, w[j]), sha1_kt(j)));
c = rol(b, 30);
*/
function rol(num, cnt) {
return (num << cnt) | (num >>> (32 - cnt));
}
/*
* Convert an 8-bit or 16-bit string to an array of big-endian words
* In 8-bit function, characters >255 have their hi-byte silently ignored.
*/
/* Example usages of 'str2binb' are shown below:
binb2hex(core_sha1(str2binb(s), s.length * chrsz));
binb2b64(core_sha1(str2binb(s), s.length * chrsz));
binb2str(core_sha1(str2binb(s), s.length * chrsz));
str2binb(key);
core_sha1(ipad.concat(str2binb(data)), 512 + data.length * chrsz);
*/
function str2binb(str) {
let bin = Array();
let mask = (1 << chrsz) - 1;
for (let i = 0; i < str.length * chrsz; i += chrsz)
bin[i >> 5] |= (str.charCodeAt(i / chrsz) & mask) << (24 - i % 32);
return bin;
}
/*
* Convert an array of big-endian words to a string
*/
/* Example usages of 'binb2str' are shown below:
binb2str(core_sha1(str2binb(s), s.length * chrsz));
binb2str(core_hmac_sha1(key, data));
*/
function binb2str(bin) {
let str = "";
let mask = (1 << chrsz) - 1;
for (let i = 0; i < bin.length * 32; i += chrsz)
str += String.fromCharCode((bin[i >> 5] >>> (24 - i % 32)) & mask);
return str;
}
/*
* Convert an array of big-endian words to a hex string.
*/
/* Example usages of 'binb2hex' are shown below:
binb2hex(core_sha1(str2binb(s), s.length * chrsz));
binb2hex(core_hmac_sha1(key, data));
*/
function binb2hex(binarray) {
let hex_tab = hexcase ? "0123456789ABCDEF" : "0123456789abcdef";
let str = "";
for (let i = 0; i < binarray.length * 4; i++) {
str += hex_tab.charAt((binarray[i >> 2] >> ((3 - i % 4) * 8 + 4)) & 0xF) +
hex_tab.charAt((binarray[i >> 2] >> ((3 - i % 4) * 8)) & 0xF);
}
return str;
}
/*
* Convert an array of big-endian words to a base-64 string
*/
/* Example usages of 'binb2b64' are shown below:
binb2b64(core_sha1(str2binb(s), s.length * chrsz));
binb2b64(core_hmac_sha1(key, data));
*/
function binb2b64(binarray) {
let tab = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
let str = "";
for (let i = 0; i < binarray.length * 4; i += 3) {
let triplet = (((binarray[i >> 2] >> 8 * (3 - i % 4)) & 0xFF) << 16)
| (((binarray[i + 1 >> 2] >> 8 * (3 - (i + 1) % 4)) & 0xFF) << 8)
| ((binarray[i + 2 >> 2] >> 8 * (3 - (i + 2) % 4)) & 0xFF);
for (let j = 0; j < 4; j++) {
if (i * 8 + j * 6 > binarray.length * 32) str += b64pad;
else str += tab.charAt((triplet >> 6 * (3 - j)) & 0x3F);
}
}
return str;
} |
4e0101374b9ed16a03bd794fbb67ac927c7f589a | 8,793 | ts | TypeScript | basic-calculator/index.ts | masx200/leetcode-test | bec83c7bc30fe3387a19bf8ae0c8685ed0aba2f4 | [
"MulanPSL-1.0"
] | 1 | 2022-03-30T11:10:14.000Z | 2022-03-30T11:10:14.000Z | basic-calculator/index.ts | masx200/leetcode-test | bec83c7bc30fe3387a19bf8ae0c8685ed0aba2f4 | [
"MulanPSL-1.0"
] | null | null | null | basic-calculator/index.ts | masx200/leetcode-test | bec83c7bc30fe3387a19bf8ae0c8685ed0aba2f4 | [
"MulanPSL-1.0"
] | null | null | null | function buildParenthesizedExpression(token: Token) {
if (!Array.isArray(token)) {
throw Error("accident token type");
}
const inner_expression = buildExpression(token);
if (!inner_expression) {
throw Error("empty expression");
}
const current_expression: Expression = {
type: "ParenthesizedExpression",
expression: inner_expression,
};
return current_expression;
}
function buildNumericLiteralExpression(token: Token) {
if (typeof token !== "number") {
throw Error("accident token type");
}
const current_expression: Expression = {
type: "NumericLiteral",
value: token,
};
return current_expression;
}
export default function calculate(s: string): number {
const tokens = tokenize(s);
const ast = buildExpression(tokens);
return evaluate(ast);
}
export function evaluate(ast: Expression): number {
if (ast.type === "NumericLiteral") {
return ast.value;
}
if (ast.type === "UnaryExpression") {
if (ast.operator === "-") {
return -1 * evaluate(ast.argument);
}
}
if (ast.type === "BinaryExpression") {
if (ast.operator === "-") {
return evaluate(ast.left) - evaluate(ast.right);
}
if (ast.operator === "*") {
return evaluate(ast.left) * evaluate(ast.right);
}
if (ast.operator === "+") {
return evaluate(ast.left) + evaluate(ast.right);
}
if (ast.operator === "/") {
const num1 = evaluate(ast.left);
const num2 = evaluate(ast.right);
const sign = Math.sign(num2) * Math.sign(num1);
return sign * Math.floor(Math.abs(num1) / Math.abs(num2));
//整数除法
}
}
if (ast.type === "ParenthesizedExpression") {
return evaluate(ast.expression);
}
throw Error("not support expression");
}
type Token = Tokens extends (infer P)[] ? P : never;
type Tokens = Array<string | number | Tokens>;
function getTokenType(token: Token) {
const tokentype: TokenType = typeof token === "number"
? TokenType["number"]
: typeof token === "string"
? TokenType["operator"]
: Array.isArray(token)
? TokenType["parentheses"]
: TokenType["unknown"];
return tokentype;
}
export function tokenize(s: string): Tokens {
const tokens: Tokens = [];
const stack: Tokens[] = [tokens];
for (let i = 0; i < s.length; i++) {
const value = s[i];
if (/\d/.test(value)) {
//只处理整数
const digits: string[] = [value];
while (/\d/.test(s[i + 1])) {
digits.push(s[i + 1]);
i++;
}
const num = Number(digits.join(""));
stack[stack.length - 1].push(num);
}
if (["+", "-", "/", "*"].includes(value)) {
stack[stack.length - 1].push(value);
}
if (value === "(") {
stack.push([]);
}
if (value === ")") {
if (stack.length <= 0) throw Error("parentheses mismatch");
const last = stack[stack.length - 1];
stack.pop();
stack[stack.length - 1].push(last);
}
}
if (stack.length !== 1) throw Error("parentheses mismatch");
return tokens;
}
export function buildExpression(tokens: Tokens): Expression {
if (tokens.length === 0) {
throw Error("empty expression");
}
let state = State.initial;
const pendingtype: ExpressionType[] = [];
const pendingoperator: ExpressionOperator[] = [];
const pendingleft: Expression[] = [];
for (const token of tokens) {
const tokentype: TokenType = getTokenType(token);
if (tokentype === TokenType.unknown) throw Error("unknown token");
state = transform[state][tokentype] ?? State.unknown;
if (state === State.unknown) throw Error("unknown state");
if (state === State.unary) {
pendingtype.push("UnaryExpression");
if (typeof token === "string") {
pendingoperator.push(token as ExpressionOperator);
} else {
throw Error("accident token type");
}
}
if ([State.parentheses, State.number].includes(state)) {
const current_expression: Expression = State.number === state
? buildNumericLiteralExpression(token)
: buildParenthesizedExpression(token);
if (pendingtype.length === 0 && pendingoperator.length === 0) {
pendingleft.push(current_expression);
} else {
const type = pendingtype[pendingtype.length - 1];
pendingtype.pop();
const operator = pendingoperator[pendingoperator.length - 1];
pendingoperator.pop();
if (type === "BinaryExpression") {
//优先级更高
const left = pendingleft[pendingleft.length - 1];
if (
left.type === "BinaryExpression" &&
["*", "/"].includes(operator) &&
["+", "-"].includes(left.operator)
) {
left.right = {
type: "BinaryExpression",
operator: operator as BinaryExpression["operator"],
left: left.right,
right: current_expression,
};
} else {
pendingleft.pop();
pendingleft.push({
operator: operator as BinaryExpression["operator"],
type: "BinaryExpression",
left,
right: current_expression,
});
}
}
if (type === "UnaryExpression") {
pendingleft.push({
operator: operator as UnaryExpression["operator"],
type: "UnaryExpression",
argument: current_expression,
});
}
}
}
if (state === State.binary) {
pendingtype.push("BinaryExpression");
if (typeof token === "string") {
pendingoperator.push(token as ExpressionOperator);
} else {
throw Error("accident token type");
}
}
}
if (valid_end_states.includes(state) && pendingleft.length) {
return pendingleft[0];
} else {
throw new Error("unexpected end state or empty expression");
}
}
const enum State {
"initial",
"unary",
"parentheses",
"number",
"binary",
"unknown",
}
const valid_end_states = [State["parentheses"], State["number"]];
const enum TokenType {
"number",
"operator",
"parentheses",
"unknown",
}
const transform: Record<State, Record<TokenType, State>> = {
[State.initial]: {
[TokenType.operator]: State.unary,
[TokenType.number]: State.number,
[TokenType.parentheses]: State.parentheses,
},
[State.unary]: {
[TokenType.number]: State.number,
[TokenType.parentheses]: State.parentheses,
},
[State.binary]: {
[TokenType.number]: State.number,
[TokenType.parentheses]: State.parentheses,
},
[State.parentheses]: {
[TokenType.operator]: State.binary,
},
[State.number]: {
[TokenType.operator]: State.binary,
},
} as Record<State, Record<TokenType, State>>;
type ExpressionType = Expression["type"];
type ExpressionOperator =
| UnaryExpression["operator"]
| BinaryExpression["operator"];
type Expression =
| BinaryExpression
| NumericLiteral
| UnaryExpression
| ParenthesizedExpression;
interface ParenthesizedExpression {
type: "ParenthesizedExpression";
expression: Expression;
}
interface NumericLiteral {
type: "NumericLiteral";
value: number;
}
interface UnaryExpression {
type: "UnaryExpression";
operator: "void" | "throw" | "delete" | "!" | "+" | "-" | "~" | "typeof";
argument: Expression;
}
interface BinaryExpression {
type: "BinaryExpression";
operator:
| "+"
| "-"
| "/"
| "%"
| "*"
| "**"
| "&"
| "|"
| ">>"
| ">>>"
| "<<"
| "^"
| "=="
| "==="
| "!="
| "!=="
| "in"
| "instanceof"
| ">"
| "<"
| ">="
| "<="
| "|>";
left: Expression;
right: Expression;
}
| 31.070671 | 79 | 0.511998 | 268 | 7 | 0 | 7 | 27 | 11 | 6 | 0 | 9 | 9 | 11 | 23.571429 | 1,995 | 0.007018 | 0.013534 | 0.005514 | 0.004511 | 0.005514 | 0 | 0.173077 | 0.238502 | /* Example usages of 'buildParenthesizedExpression' are shown below:
State.number === state
? buildNumericLiteralExpression(token)
: buildParenthesizedExpression(token);
*/
function buildParenthesizedExpression(token) {
if (!Array.isArray(token)) {
throw Error("accident token type");
}
const inner_expression = buildExpression(token);
if (!inner_expression) {
throw Error("empty expression");
}
const current_expression = {
type: "ParenthesizedExpression",
expression: inner_expression,
};
return current_expression;
}
/* Example usages of 'buildNumericLiteralExpression' are shown below:
State.number === state
? buildNumericLiteralExpression(token)
: buildParenthesizedExpression(token);
*/
function buildNumericLiteralExpression(token) {
if (typeof token !== "number") {
throw Error("accident token type");
}
const current_expression = {
type: "NumericLiteral",
value: token,
};
return current_expression;
}
export default function calculate(s) {
const tokens = tokenize(s);
const ast = buildExpression(tokens);
return evaluate(ast);
}
export /* Example usages of 'evaluate' are shown below:
evaluate(ast);
-1 * evaluate(ast.argument);
evaluate(ast.left) - evaluate(ast.right);
evaluate(ast.left) * evaluate(ast.right);
evaluate(ast.left) + evaluate(ast.right);
evaluate(ast.left);
evaluate(ast.right);
evaluate(ast.expression);
*/
function evaluate(ast) {
if (ast.type === "NumericLiteral") {
return ast.value;
}
if (ast.type === "UnaryExpression") {
if (ast.operator === "-") {
return -1 * evaluate(ast.argument);
}
}
if (ast.type === "BinaryExpression") {
if (ast.operator === "-") {
return evaluate(ast.left) - evaluate(ast.right);
}
if (ast.operator === "*") {
return evaluate(ast.left) * evaluate(ast.right);
}
if (ast.operator === "+") {
return evaluate(ast.left) + evaluate(ast.right);
}
if (ast.operator === "/") {
const num1 = evaluate(ast.left);
const num2 = evaluate(ast.right);
const sign = Math.sign(num2) * Math.sign(num1);
return sign * Math.floor(Math.abs(num1) / Math.abs(num2));
//整数除法
}
}
if (ast.type === "ParenthesizedExpression") {
return evaluate(ast.expression);
}
throw Error("not support expression");
}
type Token = Tokens extends (infer P)[] ? P : never;
type Tokens = Array<string | number | Tokens>;
/* Example usages of 'getTokenType' are shown below:
getTokenType(token);
*/
function getTokenType(token) {
const tokentype = typeof token === "number"
? TokenType["number"]
: typeof token === "string"
? TokenType["operator"]
: Array.isArray(token)
? TokenType["parentheses"]
: TokenType["unknown"];
return tokentype;
}
export /* Example usages of 'tokenize' are shown below:
tokenize(s);
*/
function tokenize(s) {
const tokens = [];
const stack = [tokens];
for (let i = 0; i < s.length; i++) {
const value = s[i];
if (/\d/.test(value)) {
//只处理整数
const digits = [value];
while (/\d/.test(s[i + 1])) {
digits.push(s[i + 1]);
i++;
}
const num = Number(digits.join(""));
stack[stack.length - 1].push(num);
}
if (["+", "-", "/", "*"].includes(value)) {
stack[stack.length - 1].push(value);
}
if (value === "(") {
stack.push([]);
}
if (value === ")") {
if (stack.length <= 0) throw Error("parentheses mismatch");
const last = stack[stack.length - 1];
stack.pop();
stack[stack.length - 1].push(last);
}
}
if (stack.length !== 1) throw Error("parentheses mismatch");
return tokens;
}
export /* Example usages of 'buildExpression' are shown below:
buildExpression(token);
buildExpression(tokens);
*/
function buildExpression(tokens) {
if (tokens.length === 0) {
throw Error("empty expression");
}
let state = State.initial;
const pendingtype = [];
const pendingoperator = [];
const pendingleft = [];
for (const token of tokens) {
const tokentype = getTokenType(token);
if (tokentype === TokenType.unknown) throw Error("unknown token");
state = transform[state][tokentype] ?? State.unknown;
if (state === State.unknown) throw Error("unknown state");
if (state === State.unary) {
pendingtype.push("UnaryExpression");
if (typeof token === "string") {
pendingoperator.push(token as ExpressionOperator);
} else {
throw Error("accident token type");
}
}
if ([State.parentheses, State.number].includes(state)) {
const current_expression = State.number === state
? buildNumericLiteralExpression(token)
: buildParenthesizedExpression(token);
if (pendingtype.length === 0 && pendingoperator.length === 0) {
pendingleft.push(current_expression);
} else {
const type = pendingtype[pendingtype.length - 1];
pendingtype.pop();
const operator = pendingoperator[pendingoperator.length - 1];
pendingoperator.pop();
if (type === "BinaryExpression") {
//优先级更高
const left = pendingleft[pendingleft.length - 1];
if (
left.type === "BinaryExpression" &&
["*", "/"].includes(operator) &&
["+", "-"].includes(left.operator)
) {
left.right = {
type: "BinaryExpression",
operator: operator as BinaryExpression["operator"],
left: left.right,
right: current_expression,
};
} else {
pendingleft.pop();
pendingleft.push({
operator: operator as BinaryExpression["operator"],
type: "BinaryExpression",
left,
right: current_expression,
});
}
}
if (type === "UnaryExpression") {
pendingleft.push({
operator: operator as UnaryExpression["operator"],
type: "UnaryExpression",
argument: current_expression,
});
}
}
}
if (state === State.binary) {
pendingtype.push("BinaryExpression");
if (typeof token === "string") {
pendingoperator.push(token as ExpressionOperator);
} else {
throw Error("accident token type");
}
}
}
if (valid_end_states.includes(state) && pendingleft.length) {
return pendingleft[0];
} else {
throw new Error("unexpected end state or empty expression");
}
}
const enum State {
"initial",
"unary",
"parentheses",
"number",
"binary",
"unknown",
}
const valid_end_states = [State["parentheses"], State["number"]];
const enum TokenType {
"number",
"operator",
"parentheses",
"unknown",
}
const transform = {
[State.initial]: {
[TokenType.operator]: State.unary,
[TokenType.number]: State.number,
[TokenType.parentheses]: State.parentheses,
},
[State.unary]: {
[TokenType.number]: State.number,
[TokenType.parentheses]: State.parentheses,
},
[State.binary]: {
[TokenType.number]: State.number,
[TokenType.parentheses]: State.parentheses,
},
[State.parentheses]: {
[TokenType.operator]: State.binary,
},
[State.number]: {
[TokenType.operator]: State.binary,
},
} as Record<State, Record<TokenType, State>>;
type ExpressionType = Expression["type"];
type ExpressionOperator =
| UnaryExpression["operator"]
| BinaryExpression["operator"];
type Expression =
| BinaryExpression
| NumericLiteral
| UnaryExpression
| ParenthesizedExpression;
interface ParenthesizedExpression {
type;
expression;
}
interface NumericLiteral {
type;
value;
}
interface UnaryExpression {
type;
operator;
argument;
}
interface BinaryExpression {
type;
operator;
left;
right;
}
|
4e1f0cb83350e1f46cf247f1020bd3b7fe617f2a | 2,076 | ts | TypeScript | sdk-modules/src/lib/tea-sdk-runner/src/modules/capi.ts | TencentCloud/cls-console-sdk | faf99ec3b47a3b9692e296979a2c77eca31a1f40 | [
"Apache-2.0"
] | 1 | 2022-03-28T11:53:43.000Z | 2022-03-28T11:53:43.000Z | sdk-modules/src/lib/tea-sdk-runner/src/modules/capi.ts | TencentCloud/cls-console-sdk | faf99ec3b47a3b9692e296979a2c77eca31a1f40 | [
"Apache-2.0"
] | null | null | null | sdk-modules/src/lib/tea-sdk-runner/src/modules/capi.ts | TencentCloud/cls-console-sdk | faf99ec3b47a3b9692e296979a2c77eca31a1f40 | [
"Apache-2.0"
] | null | null | null | export const getCapiModules = (capi: CAPIRequest) => ({
"models/api": {
request: async (body: RequestBody, options: any = {}) => {
const { global, ...restOptions } = options;
let result = await capi(body, {
tipLoading: global,
...restOptions,
});
if (result.Response && result.code === undefined) {
const error = result.Response.Error || {};
result = {
code: error.Code || 0,
cgwerrorCode: error.Code || 0,
data: result,
message: error.Message,
};
}
return result;
},
},
"models/iaas": {
apiRequest: async (body: any, options: any = {}) => {
const { action, ...restBody } = body;
const { global, ...restOptions } = options;
let result = await capi(
{
cmd: action,
...restBody,
},
{
tipLoading: global,
...restOptions,
}
);
return result;
},
},
});
export type CAPIRequest = (
body: RequestBody,
options?: RequestOptions
) => Promise<any>;
export interface RequestBody {
/**
* 请求的云 API 地域
*/
regionId: number;
/**
* 请求的云 API 业务
*/
serviceType: string;
/**
* 请求的云 API 名称
*/
cmd: string;
/**
* 请求的云 API 数据
*/
data?: any;
}
export interface RequestOptions {
/**
* 是否使用安全的临时密钥 API 方案,建议使用 true
* @default true
*/
secure?: boolean;
/**
* 使用的云 API 版本,该参数配合 secure 使用
*
* - `secure == false`,该参数无意义
* - `secure == true && version = 1`,将使用老的临时密钥服务进行密钥申请,否则使用新的密钥服务
* - `secure == true && version = 3`,使用云 API v3 域名请求,不同地域域名不同
*/
version?: number;
/**
* 是否将客户端 IP 附加在云 API 的 `clientIP` 参数中
*/
withClientIP?: boolean;
/**
* 是否将客户端 UA 附加在云 API 的 `clientUA` 参数中
*/
withClientUA?: boolean;
/**
* 是否在顶部显示接口错误
* 默认为 true,会提示云 API 调用错误信息,如果自己处理异常,请设置该配置为 false
* @default true
*/
tipErr?: boolean;
/**
* 请求时是否在顶部显示 Loading 提示
* @default true
*/
tipLoading?: boolean;
}
export interface CAPIResponse {}
| 18.702703 | 69 | 0.533719 | 57 | 3 | 0 | 5 | 7 | 10 | 0 | 5 | 9 | 4 | 0 | 22 | 645 | 0.012403 | 0.010853 | 0.015504 | 0.006202 | 0 | 0.2 | 0.36 | 0.240944 | export const getCapiModules = (capi) => ({
"models/api": {
request: async (body, options = {}) => {
const { global, ...restOptions } = options;
let result = await capi(body, {
tipLoading: global,
...restOptions,
});
if (result.Response && result.code === undefined) {
const error = result.Response.Error || {};
result = {
code: error.Code || 0,
cgwerrorCode: error.Code || 0,
data: result,
message: error.Message,
};
}
return result;
},
},
"models/iaas": {
apiRequest: async (body, options = {}) => {
const { action, ...restBody } = body;
const { global, ...restOptions } = options;
let result = await capi(
{
cmd: action,
...restBody,
},
{
tipLoading: global,
...restOptions,
}
);
return result;
},
},
});
export type CAPIRequest = (
body,
options?
) => Promise<any>;
export interface RequestBody {
/**
* 请求的云 API 地域
*/
regionId;
/**
* 请求的云 API 业务
*/
serviceType;
/**
* 请求的云 API 名称
*/
cmd;
/**
* 请求的云 API 数据
*/
data?;
}
export interface RequestOptions {
/**
* 是否使用安全的临时密钥 API 方案,建议使用 true
* @default true
*/
secure?;
/**
* 使用的云 API 版本,该参数配合 secure 使用
*
* - `secure == false`,该参数无意义
* - `secure == true && version = 1`,将使用老的临时密钥服务进行密钥申请,否则使用新的密钥服务
* - `secure == true && version = 3`,使用云 API v3 域名请求,不同地域域名不同
*/
version?;
/**
* 是否将客户端 IP 附加在云 API 的 `clientIP` 参数中
*/
withClientIP?;
/**
* 是否将客户端 UA 附加在云 API 的 `clientUA` 参数中
*/
withClientUA?;
/**
* 是否在顶部显示接口错误
* 默认为 true,会提示云 API 调用错误信息,如果自己处理异常,请设置该配置为 false
* @default true
*/
tipErr?;
/**
* 请求时是否在顶部显示 Loading 提示
* @default true
*/
tipLoading?;
}
export interface CAPIResponse {}
|
4e2b270c451bb8e8d41646dfcd34e412bfa126e2 | 2,286 | ts | TypeScript | server/src/domain/Players.ts | manoloesparta/dothidden | c212d93baccfbf1c58303cda56d28f6b2540c2c3 | [
"MIT"
] | 1 | 2022-03-23T16:15:42.000Z | 2022-03-23T16:15:42.000Z | server/src/domain/Players.ts | manoloesparta/dothidden | c212d93baccfbf1c58303cda56d28f6b2540c2c3 | [
"MIT"
] | 1 | 2022-03-04T20:53:06.000Z | 2022-03-04T20:53:06.000Z | server/src/domain/Players.ts | manoloesparta/dothidden | c212d93baccfbf1c58303cda56d28f6b2540c2c3 | [
"MIT"
] | 5 | 2022-03-04T02:26:43.000Z | 2022-03-18T03:39:23.000Z | export class Player {
public name: string;
public x: number;
public y: number;
constructor(name: string, x: number, y: number) {
this.name = name;
this.x = x;
this.y = y;
}
protected proximity(player: Player): number {
const first = (player.x - this.x) ** 2;
const second = (player.y - this.y) ** 2;
return Math.sqrt(first + second);
}
public moveTo(x: number, y: number) {
this.x = x;
this.y = y;
}
}
export class Hider extends Player {
public alive: boolean;
public nickname: string;
private playerEmitter: any;
private rooEmitter: any;
constructor(name: string, x: number, y: number, playerEmitter: any, roomEmitter: any, nickname: string) {
super(name, x, y);
this.alive = true;
this.playerEmitter = playerEmitter;
this.rooEmitter = roomEmitter;
this.nickname = nickname;
}
public update(seeker: Seeker) {
const distance = this.proximity(seeker);
if (distance < 0.01) {
this.alive = false;
this.rooEmitter('client.hider.dead', { name: this.name })
}
this.playerEmitter(this.name, 'client.hider.update', { seeker: distance.toFixed(3) })
}
public static fromPlayer(player: Player, nickname: string, rooEmitter: any, playerEmitter: any): Hider {
return new Hider(
player.name,
player.x,
player.y,
playerEmitter,
rooEmitter,
nickname,
);
}
}
export class Seeker extends Player {
private playerEmitter: any;
private rooEmitter: any;
constructor(name: string, x: number, y: number, playerEmitter: any, roomEmitter: any) {
super(name, x, y);
this.playerEmitter = playerEmitter;
this.rooEmitter = roomEmitter;
}
public update(hiders: Array<Hider>) {
const message: any = []
for(const hider of hiders) {
message.push({
name: hider.name,
nickname: hider.nickname,
alive: hider.alive,
distance: this.proximity(hider).toFixed(3),
});
}
this.playerEmitter(this.name, 'client.seeker.update', { hiders: message })
}
public static fromPlayer(player: Player, roomEmitter: any, playerEmitter: any): Seeker {
return new Seeker(
player.name,
player.x,
player.y,
playerEmitter,
roomEmitter,
);
}
}
| 24.319149 | 107 | 0.630796 | 80 | 9 | 0 | 26 | 4 | 9 | 1 | 13 | 19 | 3 | 0 | 5.222222 | 663 | 0.05279 | 0.006033 | 0.013575 | 0.004525 | 0 | 0.270833 | 0.395833 | 0.316037 | export class Player {
public name;
public x;
public y;
constructor(name, x, y) {
this.name = name;
this.x = x;
this.y = y;
}
protected proximity(player) {
const first = (player.x - this.x) ** 2;
const second = (player.y - this.y) ** 2;
return Math.sqrt(first + second);
}
public moveTo(x, y) {
this.x = x;
this.y = y;
}
}
export class Hider extends Player {
public alive;
public nickname;
private playerEmitter;
private rooEmitter;
constructor(name, x, y, playerEmitter, roomEmitter, nickname) {
super(name, x, y);
this.alive = true;
this.playerEmitter = playerEmitter;
this.rooEmitter = roomEmitter;
this.nickname = nickname;
}
public update(seeker) {
const distance = this.proximity(seeker);
if (distance < 0.01) {
this.alive = false;
this.rooEmitter('client.hider.dead', { name: this.name })
}
this.playerEmitter(this.name, 'client.hider.update', { seeker: distance.toFixed(3) })
}
public static fromPlayer(player, nickname, rooEmitter, playerEmitter) {
return new Hider(
player.name,
player.x,
player.y,
playerEmitter,
rooEmitter,
nickname,
);
}
}
export class Seeker extends Player {
private playerEmitter;
private rooEmitter;
constructor(name, x, y, playerEmitter, roomEmitter) {
super(name, x, y);
this.playerEmitter = playerEmitter;
this.rooEmitter = roomEmitter;
}
public update(hiders) {
const message = []
for(const hider of hiders) {
message.push({
name: hider.name,
nickname: hider.nickname,
alive: hider.alive,
distance: this.proximity(hider).toFixed(3),
});
}
this.playerEmitter(this.name, 'client.seeker.update', { hiders: message })
}
public static fromPlayer(player, roomEmitter, playerEmitter) {
return new Seeker(
player.name,
player.x,
player.y,
playerEmitter,
roomEmitter,
);
}
}
|
4e37dd74b59ee466274764f0564ceb399e82ef94 | 2,220 | ts | TypeScript | src/packages/DaysPicker/time/interface.ts | hanbingxu82/tinkerbell-ui-react | 522ead95c735c3990cda9ba7566f4e54646b734b | [
"MIT"
] | 3 | 2022-03-03T02:08:09.000Z | 2022-03-26T10:52:19.000Z | src/packages/DaysPicker/time/interface.ts | hanbingxu82/tinkerbell-ui-react | 522ead95c735c3990cda9ba7566f4e54646b734b | [
"MIT"
] | null | null | null | src/packages/DaysPicker/time/interface.ts | hanbingxu82/tinkerbell-ui-react | 522ead95c735c3990cda9ba7566f4e54646b734b | [
"MIT"
] | null | null | null | /*
* @Author: your name
* @Date: 2022-04-24 10:11:24
* @LastEditTime: 2022-04-24 16:15:10
* @LastEditors: Please set LastEditors
* @Description: 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
* @FilePath: /tinkerbell-ui-react/src/packages/DaysPicker/time/interface.ts
*/
// props 小时
export type hourProps = {
active: number;
change: Function;
year: number;
month: number;
day: number;
limit: boolean;
};
// props 分钟
export type minuteProps = {
active: number;
change: Function;
year: number;
month: number;
day: number;
hour: number;
limit: boolean;
};
export type ListItem = {
label: string;
value: number;
};
// 小时/分 -数据列表生成
export function getTimeList(
max: number,
year: number,
month: number,
day: number,
hour: number,
minute: number,
limit: boolean
) {
let list: Array<ListItem> = [];
for (let i = max; i > -1; i--) {
if (
checkDisabled(
max < 24,
year,
month,
day,
max > 23 ? hour : i,
max < 24 ? minute : i
) ||
!limit
) {
let label = i < 10 ? `0${i.toString()}` : i.toString();
list.push({
label: label,
value: i,
});
} else {
break;
}
}
return list.reverse();
}
// 时/分-禁用判定
function checkDisabled(
ishour: boolean,
prevYear: number,
prevMonth: number,
prevDay: number,
prevHour: number,
prevMinute: number
) {
const prevTime = new Date(
`${prevYear}/${prevMonth}/${prevDay} ${prevHour}:${prevMinute}`
).getTime();
const newDate = new Date();
const year: number = newDate.getFullYear();
let month: number = newDate.getMonth() + 1;
let day: number = newDate.getDate();
let hour: number = newDate.getHours();
let minute: number = newDate.getMinutes();
const newTime = new Date(
`${year}/${month}/${day} ${hour}:${ishour ? 0 : minute}`
).getTime();
return prevTime >= newTime;
}
// 秒 -数据列表生成
export function getSecondList(max: number) {
let list: Array<ListItem> = [];
for (let i = max; i > -1; i--) {
let label = i < 10 ? `0${i.toString()}` : i.toString();
list.push({
label: label,
value: i,
});
}
return list.reverse();
}
| 20.943396 | 111 | 0.598198 | 87 | 3 | 0 | 14 | 14 | 15 | 1 | 2 | 32 | 3 | 0 | 15 | 833 | 0.020408 | 0.016807 | 0.018007 | 0.003601 | 0 | 0.043478 | 0.695652 | 0.277227 | /*
* @Author: your name
* @Date: 2022-04-24 10:11:24
* @LastEditTime: 2022-04-24 16:15:10
* @LastEditors: Please set LastEditors
* @Description: 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
* @FilePath: /tinkerbell-ui-react/src/packages/DaysPicker/time/interface.ts
*/
// props 小时
export type hourProps = {
active;
change;
year;
month;
day;
limit;
};
// props 分钟
export type minuteProps = {
active;
change;
year;
month;
day;
hour;
limit;
};
export type ListItem = {
label;
value;
};
// 小时/分 -数据列表生成
export function getTimeList(
max,
year,
month,
day,
hour,
minute,
limit
) {
let list = [];
for (let i = max; i > -1; i--) {
if (
checkDisabled(
max < 24,
year,
month,
day,
max > 23 ? hour : i,
max < 24 ? minute : i
) ||
!limit
) {
let label = i < 10 ? `0${i.toString()}` : i.toString();
list.push({
label: label,
value: i,
});
} else {
break;
}
}
return list.reverse();
}
// 时/分-禁用判定
/* Example usages of 'checkDisabled' are shown below:
checkDisabled(max < 24, year, month, day, max > 23 ? hour : i, max < 24 ? minute : i) ||
!limit;
*/
function checkDisabled(
ishour,
prevYear,
prevMonth,
prevDay,
prevHour,
prevMinute
) {
const prevTime = new Date(
`${prevYear}/${prevMonth}/${prevDay} ${prevHour}:${prevMinute}`
).getTime();
const newDate = new Date();
const year = newDate.getFullYear();
let month = newDate.getMonth() + 1;
let day = newDate.getDate();
let hour = newDate.getHours();
let minute = newDate.getMinutes();
const newTime = new Date(
`${year}/${month}/${day} ${hour}:${ishour ? 0 : minute}`
).getTime();
return prevTime >= newTime;
}
// 秒 -数据列表生成
export function getSecondList(max) {
let list = [];
for (let i = max; i > -1; i--) {
let label = i < 10 ? `0${i.toString()}` : i.toString();
list.push({
label: label,
value: i,
});
}
return list.reverse();
}
|
4e77d6fefc465d02bbfde5576d003dda41ab6508 | 1,469 | ts | TypeScript | src/common/pitch.ts | voho/armony | 8c5a95c588945deb4bb34af462c00792ac287706 | [
"MIT"
] | null | null | null | src/common/pitch.ts | voho/armony | 8c5a95c588945deb4bb34af462c00792ac287706 | [
"MIT"
] | 2 | 2022-02-13T12:17:39.000Z | 2022-02-27T04:01:42.000Z | src/common/pitch.ts | voho/armony | 8c5a95c588945deb4bb34af462c00792ac287706 | [
"MIT"
] | null | null | null | export type Pitch = number;
export const C = 0 as Pitch;
export const CIS = 1 as Pitch;
export const D = 2 as Pitch;
export const DIS = 3 as Pitch;
export const E = 4 as Pitch;
export const F = 5 as Pitch;
export const FIS = 6 as Pitch;
export const G = 7 as Pitch;
export const GIS = 8 as Pitch;
export const A = 9 as Pitch;
export const AIS = 10 as Pitch;
export const B = 11 as Pitch;
export const NUM_PITCHES = 12;
export const PITCHES = Array.from(Array(NUM_PITCHES).keys()) as Pitch[];
export function getPitchWithOctave(index: Pitch, octave: number): string {
const pitch = getPitch(index);
const octaveFixed = octave + (index / NUM_PITCHES);
return pitch + octaveFixed;
}
export function getPitch(index: number): string {
switch (index % NUM_PITCHES) {
case C:
return "C";
case CIS:
return "C#";
case D:
return "D";
case DIS:
return "D#";
case E:
return "E";
case F:
return "F";
case FIS:
return "F#";
case G:
return "G";
case GIS:
return "G#";
case A:
return "A";
case AIS:
return "A#";
case B:
return "B";
default:
throw new Error("Invalid pitch");
}
}
export function isBlack(index: number): boolean {
return [CIS, DIS, FIS, GIS, AIS].includes(index % NUM_PITCHES);
}
| 24.483333 | 74 | 0.561607 | 53 | 3 | 0 | 4 | 16 | 0 | 1 | 0 | 7 | 1 | 13 | 10.666667 | 445 | 0.01573 | 0.035955 | 0 | 0.002247 | 0.029213 | 0 | 0.304348 | 0.323437 | export type Pitch = number;
export const C = 0 as Pitch;
export const CIS = 1 as Pitch;
export const D = 2 as Pitch;
export const DIS = 3 as Pitch;
export const E = 4 as Pitch;
export const F = 5 as Pitch;
export const FIS = 6 as Pitch;
export const G = 7 as Pitch;
export const GIS = 8 as Pitch;
export const A = 9 as Pitch;
export const AIS = 10 as Pitch;
export const B = 11 as Pitch;
export const NUM_PITCHES = 12;
export const PITCHES = Array.from(Array(NUM_PITCHES).keys()) as Pitch[];
export function getPitchWithOctave(index, octave) {
const pitch = getPitch(index);
const octaveFixed = octave + (index / NUM_PITCHES);
return pitch + octaveFixed;
}
export /* Example usages of 'getPitch' are shown below:
getPitch(index);
*/
function getPitch(index) {
switch (index % NUM_PITCHES) {
case C:
return "C";
case CIS:
return "C#";
case D:
return "D";
case DIS:
return "D#";
case E:
return "E";
case F:
return "F";
case FIS:
return "F#";
case G:
return "G";
case GIS:
return "G#";
case A:
return "A";
case AIS:
return "A#";
case B:
return "B";
default:
throw new Error("Invalid pitch");
}
}
export function isBlack(index) {
return [CIS, DIS, FIS, GIS, AIS].includes(index % NUM_PITCHES);
}
|
4ecebdfe2a83e32ca2665144d05b64c53181178a | 1,448 | ts | TypeScript | src/weakCache.ts | saasquatch/jotai-molecules | fd441bc796809ee0c5c0c620258a6e00d0164809 | [
"MIT"
] | null | null | null | src/weakCache.ts | saasquatch/jotai-molecules | fd441bc796809ee0c5c0c620258a6e00d0164809 | [
"MIT"
] | 1 | 2022-03-31T23:13:39.000Z | 2022-03-31T23:13:39.000Z | src/weakCache.ts | saasquatch/jotai-molecules | fd441bc796809ee0c5c0c620258a6e00d0164809 | [
"MIT"
] | null | null | null | /**
*
*
* Copied direcly from: https://github.com/pmndrs/jotai/blob/main/src/utils/weakCache.ts
*
* Eventually just import it from Jotai if it's exported.
*
*
*
*/
export type WeakCache<T> = WeakMap<object, [WeakCache<T>] | [WeakCache<T>, T]>;
const getWeakCacheItem = <T>(
cache: WeakCache<T>,
deps: readonly object[]
): T | undefined => {
while (true) {
const [dep, ...rest] = deps;
const entry = cache.get(dep as object);
if (!entry) {
return;
}
if (!rest.length) {
return entry[1];
}
cache = entry[0];
deps = rest;
}
};
const setWeakCacheItem = <T>(
cache: WeakCache<T>,
deps: readonly object[],
item: T
): void => {
while (true) {
const [dep, ...rest] = deps;
let entry = cache.get(dep as object);
if (!entry) {
entry = [new WeakMap()];
cache.set(dep as object, entry);
}
if (!rest.length) {
entry[1] = item;
return;
}
cache = entry[0];
deps = rest;
}
};
export const createMemoizeAtom = () => {
const cache: WeakCache<{}> = new WeakMap();
const memoizeAtom = <T extends {}, Deps extends readonly object[]>(
createAtom: () => T,
deps: Deps
) => {
const cachedAtom = getWeakCacheItem(cache, deps);
if (cachedAtom) {
return cachedAtom as T;
}
const createdAtom = createAtom();
setWeakCacheItem(cache, deps, createdAtom);
return createdAtom;
};
return memoizeAtom;
};
| 21.294118 | 88 | 0.582182 | 54 | 4 | 0 | 7 | 11 | 0 | 2 | 0 | 8 | 1 | 4 | 11.75 | 451 | 0.02439 | 0.02439 | 0 | 0.002217 | 0.008869 | 0 | 0.363636 | 0.309119 | /**
*
*
* Copied direcly from: https://github.com/pmndrs/jotai/blob/main/src/utils/weakCache.ts
*
* Eventually just import it from Jotai if it's exported.
*
*
*
*/
export type WeakCache<T> = WeakMap<object, [WeakCache<T>] | [WeakCache<T>, T]>;
/* Example usages of 'getWeakCacheItem' are shown below:
getWeakCacheItem(cache, deps);
*/
const getWeakCacheItem = <T>(
cache,
deps
) => {
while (true) {
const [dep, ...rest] = deps;
const entry = cache.get(dep as object);
if (!entry) {
return;
}
if (!rest.length) {
return entry[1];
}
cache = entry[0];
deps = rest;
}
};
/* Example usages of 'setWeakCacheItem' are shown below:
setWeakCacheItem(cache, deps, createdAtom);
*/
const setWeakCacheItem = <T>(
cache,
deps,
item
) => {
while (true) {
const [dep, ...rest] = deps;
let entry = cache.get(dep as object);
if (!entry) {
entry = [new WeakMap()];
cache.set(dep as object, entry);
}
if (!rest.length) {
entry[1] = item;
return;
}
cache = entry[0];
deps = rest;
}
};
export const createMemoizeAtom = () => {
const cache = new WeakMap();
/* Example usages of 'memoizeAtom' are shown below:
return memoizeAtom;
*/
const memoizeAtom = <T extends {}, Deps extends readonly object[]>(
createAtom,
deps
) => {
const cachedAtom = getWeakCacheItem(cache, deps);
if (cachedAtom) {
return cachedAtom as T;
}
const createdAtom = createAtom();
setWeakCacheItem(cache, deps, createdAtom);
return createdAtom;
};
return memoizeAtom;
};
|
4ee7d20ac48268190aac25c9401ee78171edb854 | 2,422 | ts | TypeScript | src/component/renderer/cytoscape/config-mapper.ts | jharris4/react-graph-viz-engine | a6b0d725886765fe129f7c8969bf75fcf13f8d10 | [
"Apache-2.0"
] | 6 | 2022-03-30T06:06:09.000Z | 2022-03-30T17:14:56.000Z | src/component/renderer/cytoscape/config-mapper.ts | jharris4/react-graph-viz-engine | a6b0d725886765fe129f7c8969bf75fcf13f8d10 | [
"Apache-2.0"
] | 1 | 2022-03-31T17:56:41.000Z | 2022-03-31T17:56:41.000Z | src/component/renderer/cytoscape/config-mapper.ts | jharris4/react-graph-viz-engine | a6b0d725886765fe129f7c8969bf75fcf13f8d10 | [
"Apache-2.0"
] | 1 | 2022-03-31T17:48:43.000Z | 2022-03-31T17:48:43.000Z | /**
* For cytoscape, we map the configuration dict into a dict of styling options.
*/
export function mapConfig(config: object) {
var mappedConfig = Object.keys(config).map(key => {
switch(key) {
case "nodeCaption":
return Object.keys(config[key]).map(label => {
return {
selector: 'node[label="' + label + '"]',
style: {
label: 'data(' + config[key][label] + ')'
}
}
})
case "nodeColor":
return Object.keys(config[key]).map(label => {
return {
selector: 'node[label="' + label + '"]',
style: {
'background-color': getOrDeriveValue(config[key][label])
}
}
})
case "nodeSize":
return Object.keys(config[key]).map(label => {
return {
selector: 'node[label="' + label + '"]',
style: {
'width': getOrDeriveValue(config[key][label]),
'height': getOrDeriveValue(config[key][label])
}
}
})
case "nodeCaptionSize":
return Object.keys(config[key]).map(label => {
return {
selector: 'node[label="' + label + '"]',
style: {
'font-size': getOrDeriveValue(config[key][label])
}
}
})
}
})
return [
{
selector: 'node[title]',
style: {
label: 'data(title)'
}
},
{
selector: 'node[name]',
style: {
label: 'data(name)'
}
},
...mappedConfig.flat(), {
selector: ".center-center",
style: {
"background": "black",
"text-valign": "center",
"text-halign": "center"
}
}]
}
function getOrDeriveValue(value){
if (value instanceof Function) {
return (e) => value(e._private.data);
}
return value;
} | 32.72973 | 84 | 0.370355 | 70 | 8 | 0 | 8 | 1 | 0 | 1 | 0 | 1 | 0 | 1 | 16.375 | 480 | 0.033333 | 0.002083 | 0 | 0 | 0.002083 | 0 | 0.058824 | 0.254754 | /**
* For cytoscape, we map the configuration dict into a dict of styling options.
*/
export function mapConfig(config) {
var mappedConfig = Object.keys(config).map(key => {
switch(key) {
case "nodeCaption":
return Object.keys(config[key]).map(label => {
return {
selector: 'node[label="' + label + '"]',
style: {
label: 'data(' + config[key][label] + ')'
}
}
})
case "nodeColor":
return Object.keys(config[key]).map(label => {
return {
selector: 'node[label="' + label + '"]',
style: {
'background-color': getOrDeriveValue(config[key][label])
}
}
})
case "nodeSize":
return Object.keys(config[key]).map(label => {
return {
selector: 'node[label="' + label + '"]',
style: {
'width': getOrDeriveValue(config[key][label]),
'height': getOrDeriveValue(config[key][label])
}
}
})
case "nodeCaptionSize":
return Object.keys(config[key]).map(label => {
return {
selector: 'node[label="' + label + '"]',
style: {
'font-size': getOrDeriveValue(config[key][label])
}
}
})
}
})
return [
{
selector: 'node[title]',
style: {
label: 'data(title)'
}
},
{
selector: 'node[name]',
style: {
label: 'data(name)'
}
},
...mappedConfig.flat(), {
selector: ".center-center",
style: {
"background": "black",
"text-valign": "center",
"text-halign": "center"
}
}]
}
/* Example usages of 'getOrDeriveValue' are shown below:
getOrDeriveValue(config[key][label]);
*/
function getOrDeriveValue(value){
if (value instanceof Function) {
return (e) => value(e._private.data);
}
return value;
} |
4ef875146bf91d02a43b946ba072a27eeddf80b2 | 2,167 | ts | TypeScript | src/utils/dateUtils.ts | D2Phoenix/ton-swap | 0f7a8b4d41f8f031e56a14647440e9230bd9f3af | [
"MIT"
] | 1 | 2022-01-31T11:03:50.000Z | 2022-01-31T11:03:50.000Z | src/utils/dateUtils.ts | D2Phoenix/ton-swap | 0f7a8b4d41f8f031e56a14647440e9230bd9f3af | [
"MIT"
] | null | null | null | src/utils/dateUtils.ts | D2Phoenix/ton-swap | 0f7a8b4d41f8f031e56a14647440e9230bd9f3af | [
"MIT"
] | 1 | 2022-01-31T15:36:34.000Z | 2022-01-31T15:36:34.000Z | class DateUtils {
static monthNames = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'];
static toDayMonthFormat(date: Date) {
const day = date.getDate();
const monthIndex = date.getMonth();
const monthName = DateUtils.monthNames[monthIndex];
return `${day}-${monthName}`;
}
static toShortFormat(date: Date) {
const day = date.getDate();
const monthIndex = date.getMonth();
const monthName = DateUtils.monthNames[monthIndex];
const year = date.getFullYear();
return `${day} ${monthName} ${year}`;
}
static timeSince(time: Date) {
const time_formats = [
[60, 'seconds', 1], // 60
[120, '1 minute ago', '1 minute from now'], // 60*2
[3600, 'minutes', 60], // 60*60, 60
[7200, '1 hour ago', '1 hour from now'], // 60*60*2
[86400, 'hours', 3600], // 60*60*24, 60*60
[172800, 'Yesterday', 'Tomorrow'], // 60*60*24*2
[604800, 'days', 86400], // 60*60*24*7, 60*60*24
[1209600, 'Last week', 'Next week'], // 60*60*24*7*4*2
[2419200, 'weeks', 604800], // 60*60*24*7*4, 60*60*24*7
[4838400, 'Last month', 'Next month'], // 60*60*24*7*4*2
[29030400, 'months', 2419200], // 60*60*24*7*4*12, 60*60*24*7*4
[58060800, 'Last year', 'Next year'], // 60*60*24*7*4*12*2
[2903040000, 'years', 29030400], // 60*60*24*7*4*12*100, 60*60*24*7*4*12
[5806080000, 'Last century', 'Next century'], // 60*60*24*7*4*12*100*2
[58060800000, 'centuries', 2903040000], // 60*60*24*7*4*12*100*20, 60*60*24*7*4*12*100
];
let seconds = (+new Date().valueOf() - time.valueOf()) / 1000,
token = 'ago',
list_choice = 1;
if (seconds === 0) {
return 'Just now';
}
if (seconds < 0) {
seconds = Math.abs(seconds);
token = 'from now';
list_choice = 2;
}
let i = 0,
format;
while ((format = time_formats[i++]))
if (seconds < format[0]) {
if (typeof format[2] == 'string') return format[list_choice];
else return Math.floor(seconds / format[2]) + ' ' + format[1] + ' ' + token;
}
return time;
}
}
export default DateUtils;
| 34.951613 | 107 | 0.557914 | 55 | 3 | 0 | 3 | 13 | 1 | 0 | 0 | 0 | 1 | 1 | 15 | 948 | 0.006329 | 0.013713 | 0.001055 | 0.001055 | 0.001055 | 0 | 0 | 0.231216 | class DateUtils {
static monthNames = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'];
static toDayMonthFormat(date) {
const day = date.getDate();
const monthIndex = date.getMonth();
const monthName = DateUtils.monthNames[monthIndex];
return `${day}-${monthName}`;
}
static toShortFormat(date) {
const day = date.getDate();
const monthIndex = date.getMonth();
const monthName = DateUtils.monthNames[monthIndex];
const year = date.getFullYear();
return `${day} ${monthName} ${year}`;
}
static timeSince(time) {
const time_formats = [
[60, 'seconds', 1], // 60
[120, '1 minute ago', '1 minute from now'], // 60*2
[3600, 'minutes', 60], // 60*60, 60
[7200, '1 hour ago', '1 hour from now'], // 60*60*2
[86400, 'hours', 3600], // 60*60*24, 60*60
[172800, 'Yesterday', 'Tomorrow'], // 60*60*24*2
[604800, 'days', 86400], // 60*60*24*7, 60*60*24
[1209600, 'Last week', 'Next week'], // 60*60*24*7*4*2
[2419200, 'weeks', 604800], // 60*60*24*7*4, 60*60*24*7
[4838400, 'Last month', 'Next month'], // 60*60*24*7*4*2
[29030400, 'months', 2419200], // 60*60*24*7*4*12, 60*60*24*7*4
[58060800, 'Last year', 'Next year'], // 60*60*24*7*4*12*2
[2903040000, 'years', 29030400], // 60*60*24*7*4*12*100, 60*60*24*7*4*12
[5806080000, 'Last century', 'Next century'], // 60*60*24*7*4*12*100*2
[58060800000, 'centuries', 2903040000], // 60*60*24*7*4*12*100*20, 60*60*24*7*4*12*100
];
let seconds = (+new Date().valueOf() - time.valueOf()) / 1000,
token = 'ago',
list_choice = 1;
if (seconds === 0) {
return 'Just now';
}
if (seconds < 0) {
seconds = Math.abs(seconds);
token = 'from now';
list_choice = 2;
}
let i = 0,
format;
while ((format = time_formats[i++]))
if (seconds < format[0]) {
if (typeof format[2] == 'string') return format[list_choice];
else return Math.floor(seconds / format[2]) + ' ' + format[1] + ' ' + token;
}
return time;
}
}
export default DateUtils;
|
15b8db192fc5ac36ac290289da3f8a7f39a0fb7b | 5,199 | ts | TypeScript | controllers/GameController.ts | liorp/milan | e76411c7eb1ba8fbf1facd4ebd72636667aca96f | [
"MIT"
] | 2 | 2022-01-14T11:38:33.000Z | 2022-02-07T20:06:06.000Z | controllers/GameController.ts | liorp/milan | e76411c7eb1ba8fbf1facd4ebd72636667aca96f | [
"MIT"
] | 1 | 2022-01-18T09:36:56.000Z | 2022-01-18T19:46:42.000Z | controllers/GameController.ts | liorp/milan | e76411c7eb1ba8fbf1facd4ebd72636667aca96f | [
"MIT"
] | 1 | 2022-02-07T20:03:18.000Z | 2022-02-07T20:03:18.000Z | export type Board = string[][]
export const numberOfLetters = 5
export const numberOfRows = 6
export const word = 'לחמים'
export const empty = '-'
export const endOfWordToRegularLetters = {
ם: 'מ',
ן: 'נ',
ץ: 'צ',
ף: 'פ',
ך: 'כ',
}
export const regularToEndOfWordLetters = {
מ: 'ם',
נ: 'ן',
צ: 'ץ',
פ: 'ף',
כ: 'ך',
}
// The enum ordering is used in order to always push a better result into the dict
export enum LetterType {
Unevaluated,
Miss,
Present,
Correct,
}
export const letterTypeToBgColor = {
[LetterType.Unevaluated]: 'hg-unevaluated',
[LetterType.Miss]: 'bg-zinc-400',
[LetterType.Present]: 'bg-orange-400',
[LetterType.Correct]: 'bg-green-400',
}
export const letterTypeToEmoji = {
[LetterType.Miss]: '⬛',
[LetterType.Present]: '🟨',
[LetterType.Correct]: '🟩',
}
export const keyboardLettersFromGuesses = (word: string, guesses: Board) => {
let letters = {
א: LetterType.Unevaluated,
ב: LetterType.Unevaluated,
ג: LetterType.Unevaluated,
ד: LetterType.Unevaluated,
ה: LetterType.Unevaluated,
ו: LetterType.Unevaluated,
ז: LetterType.Unevaluated,
ח: LetterType.Unevaluated,
ט: LetterType.Unevaluated,
י: LetterType.Unevaluated,
כ: LetterType.Unevaluated,
ל: LetterType.Unevaluated,
מ: LetterType.Unevaluated,
נ: LetterType.Unevaluated,
ס: LetterType.Unevaluated,
ע: LetterType.Unevaluated,
פ: LetterType.Unevaluated,
צ: LetterType.Unevaluated,
ק: LetterType.Unevaluated,
ר: LetterType.Unevaluated,
ש: LetterType.Unevaluated,
ת: LetterType.Unevaluated,
ם: LetterType.Unevaluated,
ן: LetterType.Unevaluated,
ץ: LetterType.Unevaluated,
ף: LetterType.Unevaluated,
ך: LetterType.Unevaluated,
}
for (const i in guesses) {
let line = guesses[i]
let r = getCorrectAndPresent(word, line)
for (const t in r) {
// Using the enum ordering in order to always push a better result into the dict
if (r[t] > letters[line[t]]) letters[line[t]] = r[t]
}
}
return letters
}
export const emojiFromGuesses = (
word: string,
guesses: Board,
rtl = false
): string => {
let content = []
for (let i = 0; i < guesses.length; i++) {
if (rtl) {
content.push(
getCorrectAndPresent(word, guesses[i])
.map((l) => letterTypeToEmoji[l])
.reverse()
.join('')
)
} else {
content.push(
getCorrectAndPresent(word, guesses[i])
.map((l) => letterTypeToEmoji[l])
.join('')
)
}
}
return content.join('\n')
}
export const wordInGuesses = (word: string, guesses: Board): boolean => {
for (let i = 0; i < guesses.length; i++) {
if (word === guesses[i].join('')) return true
}
return false
}
export const sanitizeString = (str: string): string => {
let r = []
for (let i = 0; i < str.length; i++) {
if (str[i] in endOfWordToRegularLetters) {
r.push(endOfWordToRegularLetters[str[i]])
} else {
r.push(str[i])
}
}
return r.join('')
}
export const getCorrectAndPresent = (
word: string,
guess: string[]
): LetterType[] => {
const cleanWord = sanitizeString(word)
const cleanGuess = guess
.map((e) => (e === '' && empty) || e)
.map(sanitizeString)
.join('')
let correctAndPresent = {
cleanWord: Array(cleanWord.length).fill(LetterType.Unevaluated),
cleanGuess: Array(cleanGuess.length).fill(LetterType.Unevaluated),
}
// For each letter of guess, check if it's correct
for (let i = 0; i < cleanWord.length; i++) {
if (cleanWord[i] === cleanGuess[i])
correctAndPresent.cleanGuess[i] = correctAndPresent.cleanWord[i] =
LetterType.Correct
}
// Now the tricky part is to find the present
// A letter is present iff it appears in the word somewhere that is not already present or correct
for (let i = 0; i < cleanGuess.length; i++) {
for (let j = 0; j < cleanWord.length; j++) {
if (
cleanGuess[i] === cleanWord[j] &&
correctAndPresent.cleanGuess[i] !== LetterType.Correct &&
correctAndPresent.cleanWord[j] !== LetterType.Correct &&
correctAndPresent.cleanGuess[i] !== LetterType.Present &&
correctAndPresent.cleanWord[j] !== LetterType.Present
)
correctAndPresent.cleanGuess[i] = correctAndPresent.cleanWord[
j
] = LetterType.Present
}
if (
correctAndPresent.cleanGuess[i] === LetterType.Unevaluated &&
cleanGuess[i] !== empty
) {
// Finally, set the character to miss
correctAndPresent.cleanGuess[i] = LetterType.Miss
}
}
return correctAndPresent.cleanGuess
}
| 29.372881 | 102 | 0.567994 | 156 | 8 | 0 | 13 | 27 | 0 | 2 | 0 | 10 | 1 | 0 | 13.25 | 1,514 | 0.013871 | 0.017834 | 0 | 0.000661 | 0 | 0 | 0.208333 | 0.262095 | export type Board = string[][]
export const numberOfLetters = 5
export const numberOfRows = 6
export const word = 'לחמים'
export const empty = '-'
export const endOfWordToRegularLetters = {
ם: 'מ',
ן: 'נ',
ץ: 'צ',
ף: 'פ',
ך: 'כ',
}
export const regularToEndOfWordLetters = {
מ: 'ם',
נ: 'ן',
צ: 'ץ',
פ: 'ף',
כ: 'ך',
}
// The enum ordering is used in order to always push a better result into the dict
export enum LetterType {
Unevaluated,
Miss,
Present,
Correct,
}
export const letterTypeToBgColor = {
[LetterType.Unevaluated]: 'hg-unevaluated',
[LetterType.Miss]: 'bg-zinc-400',
[LetterType.Present]: 'bg-orange-400',
[LetterType.Correct]: 'bg-green-400',
}
export const letterTypeToEmoji = {
[LetterType.Miss]: '⬛',
[LetterType.Present]: '🟨',
[LetterType.Correct]: '🟩',
}
export const keyboardLettersFromGuesses = (word, guesses) => {
let letters = {
א: LetterType.Unevaluated,
ב: LetterType.Unevaluated,
ג: LetterType.Unevaluated,
ד: LetterType.Unevaluated,
ה: LetterType.Unevaluated,
ו: LetterType.Unevaluated,
ז: LetterType.Unevaluated,
ח: LetterType.Unevaluated,
ט: LetterType.Unevaluated,
י: LetterType.Unevaluated,
כ: LetterType.Unevaluated,
ל: LetterType.Unevaluated,
מ: LetterType.Unevaluated,
נ: LetterType.Unevaluated,
ס: LetterType.Unevaluated,
ע: LetterType.Unevaluated,
פ: LetterType.Unevaluated,
צ: LetterType.Unevaluated,
ק: LetterType.Unevaluated,
ר: LetterType.Unevaluated,
ש: LetterType.Unevaluated,
ת: LetterType.Unevaluated,
ם: LetterType.Unevaluated,
ן: LetterType.Unevaluated,
ץ: LetterType.Unevaluated,
ף: LetterType.Unevaluated,
ך: LetterType.Unevaluated,
}
for (const i in guesses) {
let line = guesses[i]
let r = getCorrectAndPresent(word, line)
for (const t in r) {
// Using the enum ordering in order to always push a better result into the dict
if (r[t] > letters[line[t]]) letters[line[t]] = r[t]
}
}
return letters
}
export const emojiFromGuesses = (
word,
guesses,
rtl = false
) => {
let content = []
for (let i = 0; i < guesses.length; i++) {
if (rtl) {
content.push(
getCorrectAndPresent(word, guesses[i])
.map((l) => letterTypeToEmoji[l])
.reverse()
.join('')
)
} else {
content.push(
getCorrectAndPresent(word, guesses[i])
.map((l) => letterTypeToEmoji[l])
.join('')
)
}
}
return content.join('\n')
}
export const wordInGuesses = (word, guesses) => {
for (let i = 0; i < guesses.length; i++) {
if (word === guesses[i].join('')) return true
}
return false
}
export /* Example usages of 'sanitizeString' are shown below:
sanitizeString(word);
guess
.map((e) => (e === '' && empty) || e)
.map(sanitizeString)
.join('');
*/
const sanitizeString = (str) => {
let r = []
for (let i = 0; i < str.length; i++) {
if (str[i] in endOfWordToRegularLetters) {
r.push(endOfWordToRegularLetters[str[i]])
} else {
r.push(str[i])
}
}
return r.join('')
}
export /* Example usages of 'getCorrectAndPresent' are shown below:
getCorrectAndPresent(word, line);
content.push(getCorrectAndPresent(word, guesses[i])
.map((l) => letterTypeToEmoji[l])
.reverse()
.join(''));
content.push(getCorrectAndPresent(word, guesses[i])
.map((l) => letterTypeToEmoji[l])
.join(''));
*/
const getCorrectAndPresent = (
word,
guess
) => {
const cleanWord = sanitizeString(word)
const cleanGuess = guess
.map((e) => (e === '' && empty) || e)
.map(sanitizeString)
.join('')
let correctAndPresent = {
cleanWord: Array(cleanWord.length).fill(LetterType.Unevaluated),
cleanGuess: Array(cleanGuess.length).fill(LetterType.Unevaluated),
}
// For each letter of guess, check if it's correct
for (let i = 0; i < cleanWord.length; i++) {
if (cleanWord[i] === cleanGuess[i])
correctAndPresent.cleanGuess[i] = correctAndPresent.cleanWord[i] =
LetterType.Correct
}
// Now the tricky part is to find the present
// A letter is present iff it appears in the word somewhere that is not already present or correct
for (let i = 0; i < cleanGuess.length; i++) {
for (let j = 0; j < cleanWord.length; j++) {
if (
cleanGuess[i] === cleanWord[j] &&
correctAndPresent.cleanGuess[i] !== LetterType.Correct &&
correctAndPresent.cleanWord[j] !== LetterType.Correct &&
correctAndPresent.cleanGuess[i] !== LetterType.Present &&
correctAndPresent.cleanWord[j] !== LetterType.Present
)
correctAndPresent.cleanGuess[i] = correctAndPresent.cleanWord[
j
] = LetterType.Present
}
if (
correctAndPresent.cleanGuess[i] === LetterType.Unevaluated &&
cleanGuess[i] !== empty
) {
// Finally, set the character to miss
correctAndPresent.cleanGuess[i] = LetterType.Miss
}
}
return correctAndPresent.cleanGuess
}
|
15eac60bc5ee9f99e1fb49780f95943067f79077 | 2,464 | ts | TypeScript | src/compiler/inliner.ts | GoogleFeud/objvl | 292d398d958c3faf8a9be2996869568018d4b63e | [
"MIT"
] | 2 | 2022-01-29T16:00:31.000Z | 2022-01-29T19:20:32.000Z | src/compiler/inliner.ts | GoogleFeud/objvl | 292d398d958c3faf8a9be2996869568018d4b63e | [
"MIT"
] | null | null | null | src/compiler/inliner.ts | GoogleFeud/objvl | 292d398d958c3faf8a9be2996869568018d4b63e | [
"MIT"
] | null | null | null |
export const enum ParseState {
Params,
Exp
}
// eslint-disable-next-line @typescript-eslint/ban-types
export function inlineFunc(fn: string|Function, replacements: Array<string>) : string {
if (typeof fn === "function") fn = fn.toString();
if (fn.startsWith("function")) return `(${fn})(${replacements.join(",")})`;
fn += " ";
const fnLen = fn.length;
let res = "";
// The current token
let current = "";
// If the parser is currently in a string
let inStr = false;
// If the parser is currently in a template literal
let inTempLiteral = false;
// The state the parser is in - whether it's reading parameters or the expresion itself
let state = ParseState.Params;
// The function params
const params: string[] = [];
let isPrevArrow = false;
for (let i=0; i < fnLen + 1; i++) {
const char = fn[i];
// If the next token is => and the state is params, transition to the other state
if (char === "=" && fn[i + 1] === ">" && state === ParseState.Params) {
state = ParseState.Exp;
isPrevArrow = true;
// Skip over the =>
i++;
continue;
}
if (char === "{") {
if (inTempLiteral && fn[i - 1] === "$") inStr = false;
else if (isPrevArrow) return `(${fn})(${replacements.join(",")})`;
}
if (char === "}" && inTempLiteral && !inStr) inStr = true;
// Toggle string mode
if (char === "\"" || char === "'") inStr = !inStr;
if (char === "`") {
inStr = !inStr;
inTempLiteral = inStr;
}
// If the current character is valid in an identifier, add it to the current identifier
if (/[a-zA-Z0-9_$]/.test(char) && (!inStr)) {
current += char;
continue;
}
// If not...
if (state === ParseState.Params && current) params.push(current);
else {
const param = params.indexOf(current);
if (param !== -1) res += replacements[param];
else res += current;
}
current = "";
if (char) {
if (inStr) res += char;
else {
if (state !== ParseState.Params && (char !== " " && char !== "\n" && char !== ";")) {
res += char;
isPrevArrow = false;
}
}
}
}
return res;
} | 30.8 | 101 | 0.492289 | 57 | 1 | 0 | 2 | 11 | 0 | 0 | 1 | 4 | 0 | 1 | 51 | 611 | 0.00491 | 0.018003 | 0 | 0 | 0.001637 | 0.071429 | 0.285714 | 0.238792 |
export const enum ParseState {
Params,
Exp
}
// eslint-disable-next-line @typescript-eslint/ban-types
export function inlineFunc(fn, replacements) {
if (typeof fn === "function") fn = fn.toString();
if (fn.startsWith("function")) return `(${fn})(${replacements.join(",")})`;
fn += " ";
const fnLen = fn.length;
let res = "";
// The current token
let current = "";
// If the parser is currently in a string
let inStr = false;
// If the parser is currently in a template literal
let inTempLiteral = false;
// The state the parser is in - whether it's reading parameters or the expresion itself
let state = ParseState.Params;
// The function params
const params = [];
let isPrevArrow = false;
for (let i=0; i < fnLen + 1; i++) {
const char = fn[i];
// If the next token is => and the state is params, transition to the other state
if (char === "=" && fn[i + 1] === ">" && state === ParseState.Params) {
state = ParseState.Exp;
isPrevArrow = true;
// Skip over the =>
i++;
continue;
}
if (char === "{") {
if (inTempLiteral && fn[i - 1] === "$") inStr = false;
else if (isPrevArrow) return `(${fn})(${replacements.join(",")})`;
}
if (char === "}" && inTempLiteral && !inStr) inStr = true;
// Toggle string mode
if (char === "\"" || char === "'") inStr = !inStr;
if (char === "`") {
inStr = !inStr;
inTempLiteral = inStr;
}
// If the current character is valid in an identifier, add it to the current identifier
if (/[a-zA-Z0-9_$]/.test(char) && (!inStr)) {
current += char;
continue;
}
// If not...
if (state === ParseState.Params && current) params.push(current);
else {
const param = params.indexOf(current);
if (param !== -1) res += replacements[param];
else res += current;
}
current = "";
if (char) {
if (inStr) res += char;
else {
if (state !== ParseState.Params && (char !== " " && char !== "\n" && char !== ";")) {
res += char;
isPrevArrow = false;
}
}
}
}
return res;
} |
ae4bf13ffdb33e13ff8e5275c3d38ccbb5a58a33 | 3,403 | ts | TypeScript | src/utils/pixel.ts | x6ud/pixel-skeletal-animation-editor | 7e681275347653ec02ccf29b0864e439e3ae6a79 | [
"MIT"
] | 2 | 2022-01-01T01:23:25.000Z | 2022-01-09T06:29:52.000Z | src/utils/pixel.ts | x6ud/pixel-skeletal-animation-editor | 7e681275347653ec02ccf29b0864e439e3ae6a79 | [
"MIT"
] | null | null | null | src/utils/pixel.ts | x6ud/pixel-skeletal-animation-editor | 7e681275347653ec02ccf29b0864e439e3ae6a79 | [
"MIT"
] | null | null | null | export function pixelLine(
x0: number, y0: number,
x1: number, y1: number,
draw: (x: number, y: number) => void
) {
let x, y, xe, ye;
let dx = x1 - x0;
let dy = y1 - y0;
let dx1 = Math.abs(dx);
let dy1 = Math.abs(dy);
let px = 2 * dy1 - dx1;
let py = 2 * dx1 - dy1;
if (dy1 <= dx1) {
if (dx >= 0) {
x = x0;
y = y0;
xe = x1;
} else {
x = x1;
y = y1;
xe = x0;
}
draw(x, y);
for (let i = 0; x < xe; i++) {
x = x + 1;
if (px < 0) {
px = px + 2 * dy1;
} else {
if ((dx < 0 && dy < 0) || (dx > 0 && dy > 0)) {
y = y + 1;
} else {
y = y - 1;
}
px = px + 2 * (dy1 - dx1);
}
draw(x, y);
}
} else {
if (dy >= 0) {
x = x0;
y = y0;
ye = y1;
} else {
x = x1;
y = y1;
ye = y0;
}
draw(x, y);
for (let i = 0; y < ye; i++) {
y = y + 1;
if (py <= 0) {
py = py + 2 * dx1;
} else {
if ((dx < 0 && dy < 0) || (dx > 0 && dy > 0)) {
x = x + 1;
} else {
x = x - 1;
}
py = py + 2 * (dx1 - dy1);
}
draw(x, y);
}
}
}
export function pixelRect(width: number, height: number, fill: boolean, draw: (x: number, y: number) => void) {
if (fill) {
for (let x = 0; x < width; ++x) {
for (let y = 0; y < height; ++y) {
draw(x, y);
}
}
} else {
for (let x = 0; x < width; ++x) {
draw(x, 0);
draw(x, height - 1);
}
for (let y = 1; y < height - 1; ++y) {
draw(0, y);
draw(width - 1, y);
}
}
}
export function pixelCircle(
size: number,
fill: boolean,
fillCorner: boolean,
draw: (x: number, y: number) => void
) {
const r = size / 2;
const r2 = (r - 0.25) ** 2;
let x = Math.floor(r);
let y = 0;
let fillX = false;
while (x >= y) {
const dx0 = r - (x + 0.5);
const dy0 = r - (y + 0.5);
const fx = Math.floor(r + dx0);
const fy = Math.floor(r + dy0);
draw(fx, fy);
draw(+x, fy);
draw(fx, +y);
draw(+x, +y);
draw(fy, fx);
draw(+y, fx);
draw(fy, +x);
draw(+y, +x);
if (fill) {
if (fillX) {
fillX = false;
for (let px = x + 1; px < fx; ++px) {
draw(px, +y);
draw(px, fy);
}
}
for (let py = y + 1; py < fy; ++py) {
draw(py, +x);
draw(py, fx);
}
}
const dx1 = r - (x - 1 + 0.5);
if (dx1 ** 2 + dy0 ** 2 <= r2) {
x -= 1;
} else {
if (fill || !fillCorner) {
const dy1 = r - (y + 1 + 0.5);
if (dx1 ** 2 + dy1 ** 2 <= r2) {
x -= 1;
}
}
fillX = true;
y += 1;
}
}
}
| 24.307143 | 111 | 0.29856 | 134 | 3 | 0 | 13 | 29 | 0 | 0 | 0 | 19 | 0 | 0 | 39.666667 | 1,106 | 0.014467 | 0.026221 | 0 | 0 | 0 | 0 | 0.422222 | 0.289173 | export function pixelLine(
x0, y0,
x1, y1,
draw
) {
let x, y, xe, ye;
let dx = x1 - x0;
let dy = y1 - y0;
let dx1 = Math.abs(dx);
let dy1 = Math.abs(dy);
let px = 2 * dy1 - dx1;
let py = 2 * dx1 - dy1;
if (dy1 <= dx1) {
if (dx >= 0) {
x = x0;
y = y0;
xe = x1;
} else {
x = x1;
y = y1;
xe = x0;
}
draw(x, y);
for (let i = 0; x < xe; i++) {
x = x + 1;
if (px < 0) {
px = px + 2 * dy1;
} else {
if ((dx < 0 && dy < 0) || (dx > 0 && dy > 0)) {
y = y + 1;
} else {
y = y - 1;
}
px = px + 2 * (dy1 - dx1);
}
draw(x, y);
}
} else {
if (dy >= 0) {
x = x0;
y = y0;
ye = y1;
} else {
x = x1;
y = y1;
ye = y0;
}
draw(x, y);
for (let i = 0; y < ye; i++) {
y = y + 1;
if (py <= 0) {
py = py + 2 * dx1;
} else {
if ((dx < 0 && dy < 0) || (dx > 0 && dy > 0)) {
x = x + 1;
} else {
x = x - 1;
}
py = py + 2 * (dx1 - dy1);
}
draw(x, y);
}
}
}
export function pixelRect(width, height, fill, draw) {
if (fill) {
for (let x = 0; x < width; ++x) {
for (let y = 0; y < height; ++y) {
draw(x, y);
}
}
} else {
for (let x = 0; x < width; ++x) {
draw(x, 0);
draw(x, height - 1);
}
for (let y = 1; y < height - 1; ++y) {
draw(0, y);
draw(width - 1, y);
}
}
}
export function pixelCircle(
size,
fill,
fillCorner,
draw
) {
const r = size / 2;
const r2 = (r - 0.25) ** 2;
let x = Math.floor(r);
let y = 0;
let fillX = false;
while (x >= y) {
const dx0 = r - (x + 0.5);
const dy0 = r - (y + 0.5);
const fx = Math.floor(r + dx0);
const fy = Math.floor(r + dy0);
draw(fx, fy);
draw(+x, fy);
draw(fx, +y);
draw(+x, +y);
draw(fy, fx);
draw(+y, fx);
draw(fy, +x);
draw(+y, +x);
if (fill) {
if (fillX) {
fillX = false;
for (let px = x + 1; px < fx; ++px) {
draw(px, +y);
draw(px, fy);
}
}
for (let py = y + 1; py < fy; ++py) {
draw(py, +x);
draw(py, fx);
}
}
const dx1 = r - (x - 1 + 0.5);
if (dx1 ** 2 + dy0 ** 2 <= r2) {
x -= 1;
} else {
if (fill || !fillCorner) {
const dy1 = r - (y + 1 + 0.5);
if (dx1 ** 2 + dy1 ** 2 <= r2) {
x -= 1;
}
}
fillX = true;
y += 1;
}
}
}
|
ae59518ca52d42ca894f50a2fd0c4c6f9d5061f3 | 18,522 | ts | TypeScript | src/assets/ts/SlimColor.ts | chnkarl/slim_color_picker | a9c0e74bf36598525e951efdfd588d619ac4bb33 | [
"MIT"
] | 1 | 2022-03-09T15:20:59.000Z | 2022-03-09T15:20:59.000Z | src/assets/ts/SlimColor.ts | chnkarl/slim-color-picker | a9c0e74bf36598525e951efdfd588d619ac4bb33 | [
"MIT"
] | null | null | null | src/assets/ts/SlimColor.ts | chnkarl/slim-color-picker | a9c0e74bf36598525e951efdfd588d619ac4bb33 | [
"MIT"
] | null | null | null | let trimLeft = /^\s+/;
let trimRight = /\s+$/;
let mathRound = Math.round;
let mathMin = Math.min;
let mathMax = Math.max;
let names = {
aliceblue: 'f0f8ff',
antiquewhite: 'faebd7',
aqua: '0ff',
aquamarine: '7fffd4',
azure: 'f0ffff',
beige: 'f5f5dc',
bisque: 'ffe4c4',
black: '000',
blanchedalmond: 'ffebcd',
blue: '00f',
blueviolet: '8a2be2',
brown: 'a52a2a',
burlywood: 'deb887',
burntsienna: 'ea7e5d',
cadetblue: '5f9ea0',
chartreuse: '7fff00',
chocolate: 'd2691e',
coral: 'ff7f50',
cornflowerblue: '6495ed',
cornsilk: 'fff8dc',
crimson: 'dc143c',
cyan: '0ff',
darkblue: '00008b',
darkcyan: '008b8b',
darkgoldenrod: 'b8860b',
darkgray: 'a9a9a9',
darkgreen: '006400',
darkgrey: 'a9a9a9',
darkkhaki: 'bdb76b',
darkmagenta: '8b008b',
darkolivegreen: '556b2f',
darkorange: 'ff8c00',
darkorchid: '9932cc',
darkred: '8b0000',
darksalmon: 'e9967a',
darkseagreen: '8fbc8f',
darkslateblue: '483d8b',
darkslategray: '2f4f4f',
darkslategrey: '2f4f4f',
darkturquoise: '00ced1',
darkviolet: '9400d3',
deeppink: 'ff1493',
deepskyblue: '00bfff',
dimgray: '696969',
dimgrey: '696969',
dodgerblue: '1e90ff',
firebrick: 'b22222',
floralwhite: 'fffaf0',
forestgreen: '228b22',
fuchsia: 'f0f',
gainsboro: 'dcdcdc',
ghostwhite: 'f8f8ff',
gold: 'ffd700',
goldenrod: 'daa520',
gray: '808080',
green: '008000',
greenyellow: 'adff2f',
grey: '808080',
honeydew: 'f0fff0',
hotpink: 'ff69b4',
indianred: 'cd5c5c',
indigo: '4b0082',
ivory: 'fffff0',
khaki: 'f0e68c',
lavender: 'e6e6fa',
lavenderblush: 'fff0f5',
lawngreen: '7cfc00',
lemonchiffon: 'fffacd',
lightblue: 'add8e6',
lightcoral: 'f08080',
lightcyan: 'e0ffff',
lightgoldenrodyellow: 'fafad2',
lightgray: 'd3d3d3',
lightgreen: '90ee90',
lightgrey: 'd3d3d3',
lightpink: 'ffb6c1',
lightsalmon: 'ffa07a',
lightseagreen: '20b2aa',
lightskyblue: '87cefa',
lightslategray: '789',
lightslategrey: '789',
lightsteelblue: 'b0c4de',
lightyellow: 'ffffe0',
lime: '0f0',
limegreen: '32cd32',
linen: 'faf0e6',
magenta: 'f0f',
maroon: '800000',
mediumaquamarine: '66cdaa',
mediumblue: '0000cd',
mediumorchid: 'ba55d3',
mediumpurple: '9370db',
mediumseagreen: '3cb371',
mediumslateblue: '7b68ee',
mediumspringgreen: '00fa9a',
mediumturquoise: '48d1cc',
mediumvioletred: 'c71585',
midnightblue: '191970',
mintcream: 'f5fffa',
mistyrose: 'ffe4e1',
moccasin: 'ffe4b5',
navajowhite: 'ffdead',
navy: '000080',
oldlace: 'fdf5e6',
olive: '808000',
olivedrab: '6b8e23',
orange: 'ffa500',
orangered: 'ff4500',
orchid: 'da70d6',
palegoldenrod: 'eee8aa',
palegreen: '98fb98',
paleturquoise: 'afeeee',
palevioletred: 'db7093',
papayawhip: 'ffefd5',
peachpuff: 'ffdab9',
peru: 'cd853f',
pink: 'ffc0cb',
plum: 'dda0dd',
powderblue: 'b0e0e6',
purple: '800080',
rebeccapurple: '663399',
red: 'f00',
rosybrown: 'bc8f8f',
royalblue: '4169e1',
saddlebrown: '8b4513',
salmon: 'fa8072',
sandybrown: 'f4a460',
seagreen: '2e8b57',
seashell: 'fff5ee',
sienna: 'a0522d',
silver: 'c0c0c0',
skyblue: '87ceeb',
slateblue: '6a5acd',
slategray: '708090',
slategrey: '708090',
snow: 'fffafa',
springgreen: '00ff7f',
steelblue: '4682b4',
tan: 'd2b48c',
teal: '008080',
thistle: 'd8bfd8',
tomato: 'ff6347',
turquoise: '40e0d0',
violet: 'ee82ee',
wheat: 'f5deb3',
white: 'fff',
whitesmoke: 'f5f5f5',
yellow: 'ff0',
yellowgreen: '9acd32',
};
class SlimColor {
_originalInput: any;
_r: any;
_g: any;
_b: any;
_a: any;
_roundA: any;
_ok: boolean = false;
rgb: any
_format: any
matchers: any
init (color: any = '') {
this.matchers = this.getMathers()
let rgb = this.inputToRGB(color);
this._originalInput = color
this._r = rgb.r
this._g = rgb.g
this._b = rgb.b
this._a = rgb.a
this._roundA = mathRound((100 * this._a) / 100);
this._format = rgb.format;
// Don't let the range of [0,255] come back in [0,1].
// Potentially lose a little bit of precision here, but will fix issues where
// .5 gets interpreted as half of the total, instead of half of 1
// If it was supposed to be 128, this was already taken care of by `inputToRgb`
if (this._r < 1) {
this._r = mathRound(this._r);
}
if (this._g < 1) {
this._g = mathRound(this._g);
}
if (this._b < 1) {
this._b = mathRound(this._b);
}
this._ok = rgb.ok;
}
// Given a string or object, convert that input to RGB
// Possible string inputs:
//
// "red"
// "#f00" or "f00"
// "#ff0000" or "ff0000"
// "#ff000000" or "ff000000"
// "rgb 255 0 0" or "rgb (255, 0, 0)"
// "rgb 1.0 0 0" or "rgb (1, 0, 0)"
// "rgba (255, 0, 0, 1)" or "rgba 255, 0, 0, 1"
// "rgba (1.0, 0, 0, 1)" or "rgba 1.0, 0, 0, 1"
// "hsl(0, 100%, 50%)" or "hsl 0 100% 50%"
// "hsla(0, 100%, 50%, 1)" or "hsla 0 100% 50%, 1"
// "hsv(0, 100%, 100%)" or "hsv 0 100% 100%"
inputToRGB(color) {
let rgb = { r: 0, g: 0, b: 0 };
let a:any = 1;
let s:any = null;
let v:any = null;
let l:any = null;
let ok = false;
let format = '';
if (typeof color == 'string') {
color = this.stringInputToObject(color);
}
if (typeof color == 'object') {
if (
this.isValidCSSUnit(color.r) &&
this.isValidCSSUnit(color.g) &&
this.isValidCSSUnit(color.b)
) {
rgb = this.rgbToRgb(color.r, color.g, color.b);
ok = true;
format = String(color.r).substring(-1) === '%' ? 'prgb' : 'rgb';
} else if (
this.isValidCSSUnit(color.h) &&
this.isValidCSSUnit(color.s) &&
this.isValidCSSUnit(color.v)
) {
s = this.convertToPercentage(color.s);
v = this.convertToPercentage(color.v);
rgb = this.hsvToRgb(color.h, s, v);
ok = true;
format = 'hsv';
} else if (
this.isValidCSSUnit(color.h) &&
this.isValidCSSUnit(color.s) &&
this.isValidCSSUnit(color.l)
) {
s = this.convertToPercentage(color.s);
l = this.convertToPercentage(color.l);
rgb = this.hslToRgb(color.h, s, l);
ok = true;
format = 'hsl';
}
if (color.hasOwnProperty('a')) {
a = color.a;
}
}
a = this.boundAlpha(a);
return {
ok: ok,
format: color.format || format,
r: mathMin(255, mathMax(rgb.r, 0)),
g: mathMin(255, mathMax(rgb.g, 0)),
b: mathMin(255, mathMax(rgb.b, 0)),
a: a,
};
}
getMathers () {
// <http://www.w3.org/TR/css3-values/#integers>
let CSS_INTEGER = "[-\\+]?\\d+%?";
// <http://www.w3.org/TR/css3-values/#number-value>
let CSS_NUMBER = "[-\\+]?\\d*\\.\\d+%?";
// Allow positive/negative integer/number. Don't capture the either/or, just the entire outcome.
let CSS_UNIT = "(?:" + CSS_NUMBER + ")|(?:" + CSS_INTEGER + ")";
// Actual matching.
// Parentheses and commas are optional, but not required.
// Whitespace can take the place of commas or opening paren
let PERMISSIVE_MATCH3 = "[\\s|\\(]+(" + CSS_UNIT + ")[,|\\s]+(" + CSS_UNIT + ")[,|\\s]+(" + CSS_UNIT + ")\\s*\\)?";
let PERMISSIVE_MATCH4 = "[\\s|\\(]+(" + CSS_UNIT + ")[,|\\s]+(" + CSS_UNIT + ")[,|\\s]+(" + CSS_UNIT + ")[,|\\s]+(" + CSS_UNIT + ")\\s*\\)?";
return {
CSS_UNIT: new RegExp(CSS_UNIT),
rgb: new RegExp("rgb" + PERMISSIVE_MATCH3),
rgba: new RegExp("rgba" + PERMISSIVE_MATCH4),
hsl: new RegExp("hsl" + PERMISSIVE_MATCH3),
hsla: new RegExp("hsla" + PERMISSIVE_MATCH4),
hsv: new RegExp("hsv" + PERMISSIVE_MATCH3),
hsva: new RegExp("hsva" + PERMISSIVE_MATCH4),
hex3: /^#?([0-9a-fA-F]{1})([0-9a-fA-F]{1})([0-9a-fA-F]{1})$/,
hex6: /^#?([0-9a-fA-F]{2})([0-9a-fA-F]{2})([0-9a-fA-F]{2})$/,
hex4: /^#?([0-9a-fA-F]{1})([0-9a-fA-F]{1})([0-9a-fA-F]{1})([0-9a-fA-F]{1})$/,
hex8: /^#?([0-9a-fA-F]{2})([0-9a-fA-F]{2})([0-9a-fA-F]{2})([0-9a-fA-F]{2})$/
}
}
// `stringInputToObject`
// Permissive string parsing. Take in a number of formats, and output an object
// based on detected format. Returns `{ r, g, b }` or `{ h, s, l }` or `{ h, s, v}`
stringInputToObject(color) {
color = color.replace(trimLeft, '').replace(trimRight, '').toLowerCase();
let named = false;
if (names[color]) {
color = names[color];
named = true;
} else if (color == 'transparent') {
return { r: 0, g: 0, b: 0, a: 0, format: 'name' };
}
// Try to match string input using regular expressions.
// Keep most of the number bounding out of this function - don't worry about [0,1] or [0,100] or [0,360]
// Just return an object and let the conversion functions handle that.
// This way the result will be the same whether the tinycolor is initialized with string or object.
let match: any;
if ((match = this.matchers.rgb.exec(color))) {
return { r: match[1], g: match[2], b: match[3] };
}
if ((match = this.matchers.rgba.exec(color))) {
return { r: match[1], g: match[2], b: match[3], a: match[4] };
}
if ((match = this.matchers.hsl.exec(color))) {
return { h: match[1], s: match[2], l: match[3] };
}
if ((match = this.matchers.hsla.exec(color))) {
return { h: match[1], s: match[2], l: match[3], a: match[4] };
}
if ((match = this.matchers.hsv.exec(color))) {
return { h: match[1], s: match[2], v: match[3] };
}
if ((match = this.matchers.hsva.exec(color))) {
return { h: match[1], s: match[2], v: match[3], a: match[4] };
}
if ((match = this.matchers.hex8.exec(color))) {
return {
r: this.parseIntFromHex(match[1]),
g: this.parseIntFromHex(match[2]),
b: this.parseIntFromHex(match[3]),
a: this.convertHexToDecimal(match[4]),
format: named ? "name" : "hex8"
};
}
if ((match = this.matchers.hex6.exec(color))) {
return {
r: this.parseIntFromHex(match[1]),
g: this.parseIntFromHex(match[2]),
b: this.parseIntFromHex(match[3]),
format: named ? "name" : "hex"
};
}
if ((match = this.matchers.hex4.exec(color))) {
return {
r: this.parseIntFromHex(match[1] + '' + match[1]),
g: this.parseIntFromHex(match[2] + '' + match[2]),
b: this.parseIntFromHex(match[3] + '' + match[3]),
a: this.convertHexToDecimal(match[4] + '' + match[4]),
format: named ? "name" : "hex8"
};
}
if ((match = this.matchers.hex3.exec(color))) {
return {
r: this.parseIntFromHex(match[1] + '' + match[1]),
g: this.parseIntFromHex(match[2] + '' + match[2]),
b: this.parseIntFromHex(match[3] + '' + match[3]),
format: named ? "name" : "hex"
};
}
return false;
}
// `isValidCSSUnit`
// Take in a single string / number and check to see if it looks like a CSS unit
// (see `matchers` above for definition).
isValidCSSUnit(color: any) {
return !!this.matchers.CSS_UNIT.exec(color);
}
// Conversion Functions
// --------------------
// `rgbToHsl`, `rgbToHsv`, `hslToRgb`, `hsvToRgb` modified from:
// <http://mjijackson.com/2008/02/rgb-to-hsl-and-rgb-to-hsv-color-model-conversion-algorithms-in-javascript>
// `rgbToRgb`
// Handle bounds / percentage checking to conform to CSS color spec
// <http://www.w3.org/TR/css3-color/>
// *Assumes:* r, g, b in [0, 255] or [0, 1]
// *Returns:* { r, g, b } in [0, 255]
rgbToRgb(r: number, g: number, b: number) {
return {
r: this.bound01(r, 255) * 255,
g: this.bound01(g, 255) * 255,
b: this.bound01(b, 255) * 255,
};
}
// Replace a decimal with it's percentage value
convertToPercentage(n: any) {
if (n <= 1) {
n = n * 100 + '%';
}
return n;
}
// `hsvToRgb`
// Converts an HSV color value to RGB.
// *Assumes:* h is contained in [0, 1] or [0, 360] and s and v are contained in [0, 1] or [0, 100]
// *Returns:* { r, g, b } in the set [0, 255]
hsvToRgb(h: number, s: number, v: number) {
h = this.bound01(h, 360) * 6;
s = this.bound01(s, 100);
v = this.bound01(v, 100);
let i = Math.floor(h),
f = h - i,
p = v * (1 - s),
q = v * (1 - f * s),
t = v * (1 - (1 - f) * s),
mod = i % 6,
r = [v, q, p, p, t, v][mod],
g = [t, v, v, q, p, p][mod],
b = [p, p, t, v, v, q][mod];
return { r: r * 255, g: g * 255, b: b * 255 };
}
// Return a valid alpha value [0,1] with all invalid values being set to 1
boundAlpha(a) {
a = parseFloat(a);
if (isNaN(a) || a < 0 || a > 1) {
a = 1;
}
return a;
}
// `hslToRgb`
// Converts an HSL color value to RGB.
// *Assumes:* h is contained in [0, 1] or [0, 360] and s and l are contained [0, 1] or [0, 100]
// *Returns:* { r, g, b } in the set [0, 255]
hslToRgb(h, s, l) {
let r, g, b;
h = this.bound01(h, 360);
s = this.bound01(s, 100);
l = this.bound01(l, 100);
function hue2rgb(p, q, t) {
if (t < 0) t += 1;
if (t > 1) t -= 1;
if (t < 1 / 6) return p + (q - p) * 6 * t;
if (t < 1 / 2) return q;
if (t < 2 / 3) return p + (q - p) * (2 / 3 - t) * 6;
return p;
}
if (s === 0) {
r = g = b = l; // achromatic
} else {
let q = l < 0.5 ? l * (1 + s) : l + s - l * s;
let p = 2 * l - q;
r = hue2rgb(p, q, h + 1 / 3);
g = hue2rgb(p, q, h);
b = hue2rgb(p, q, h - 1 / 3);
}
return { r: r * 255, g: g * 255, b: b * 255 };
}
// Parse a base-16 hex value into a base-10 integer
parseIntFromHex(val) {
return parseInt(val, 16);
}
// Converts a hex value to a decimal
convertHexToDecimal(h) {
return (this.parseIntFromHex(h) / 255);
}
// Take input from [0, n] and return it as [0, 1]
bound01(n: any, max: any) {
if (this.isOnePointZero(n)) { n = "100%"; }
let processPercent = this.isPercentage(n);
n = mathMin(max, mathMax(0, parseFloat(n)));
// Automatically convert percentage into number
if (processPercent) {
n = parseInt((n * max).toString(), 10) / 100;
}
// Handle floating point rounding errors
if ((Math.abs(n - max) < 0.000001)) {
return 1;
}
// Convert into [0, 1] range if it isn't already
return (n % max) / parseFloat(max);
}
// Need to handle 1.0 as 100%, since once it is a number, there is no difference between it and 1
// <http://stackoverflow.com/questions/7422072/javascript-how-to-detect-number-as-a-decimal-including-1-0>
isOnePointZero(n) {
return typeof n == "string" && n.indexOf('.') != -1 && parseFloat(n) === 1;
}
// Check to see if string passed in is a percentage
isPercentage(n) {
return typeof n === "string" && n.indexOf('%') != -1;
}
toHsl () {
let hsl = this.rgbToHsl(this._r, this._g, this._b);
return { h: hsl.h * 360, s: hsl.s, l: hsl.l, a: this._a };
}
// `rgbToHsl`
// Converts an RGB color value to HSL.
// *Assumes:* r, g, and b are contained in [0, 255] or [0, 1]
// *Returns:* { h, s, l } in [0,1]
rgbToHsl(r, g, b) {
r = this.bound01(r, 255);
g = this.bound01(g, 255);
b = this.bound01(b, 255);
let max = mathMax(r, g, b), min = mathMin(r, g, b);
let h, s, l = (max + min) / 2;
if(max == min) {
h = s = 0; // achromatic
}
else {
let d = max - min;
s = l > 0.5 ? d / (2 - max - min) : d / (max + min);
switch(max) {
case r: h = (g - b) / d + (g < b ? 6 : 0); break;
case g: h = (b - r) / d + 2; break;
case b: h = (r - g) / d + 4; break;
}
h /= 6;
}
return { h: h, s: s, l: l };
}
setAlpha (value) {
this._a = this.boundAlpha(value);
this._roundA = mathRound(100*this._a) / 100;
return this;
}
toHex (allow3Char: boolean = false) {
return this.rgbToHex(this._r, this._g, this._b, allow3Char);
}
// `rgbToHex`
// Converts an RGB color to hex
// Assumes r, g, and b are contained in the set [0, 255]
// Returns a 3 or 6 character hex
rgbToHex(r, g, b, allow3Char) {
let hex = [
this.pad2(mathRound(r).toString(16)),
this.pad2(mathRound(g).toString(16)),
this.pad2(mathRound(b).toString(16))
];
// Return a 3 character hex if possible
if (allow3Char && hex[0].charAt(0) == hex[0].charAt(1) && hex[1].charAt(0) == hex[1].charAt(1) && hex[2].charAt(0) == hex[2].charAt(1)) {
return hex[0].charAt(0) + hex[1].charAt(0) + hex[2].charAt(0);
}
return hex.join("");
}
// Force a hex value to have 2 characters
pad2(c) {
return c.length == 1 ? '0' + c : '' + c;
}
toRgbString () {
return (this._a == 1) ?
"rgb(" + mathRound(this._r) + ", " + mathRound(this._g) + ", " + mathRound(this._b) + ")" :
"rgba(" + mathRound(this._r) + ", " + mathRound(this._g) + ", " + mathRound(this._b) + ", " + this._roundA + ")";
}
toHslString () {
let hsl = this.rgbToHsl(this._r, this._g, this._b);
let h = mathRound(hsl.h * 360), s = mathRound(hsl.s * 100), l = mathRound(hsl.l * 100);
return (this._a == 1) ?
"hsl(" + h + ", " + s + "%, " + l + "%)" :
"hsla(" + h + ", " + s + "%, " + l + "%, "+ this._roundA + ")";
}
getAlpha () {
return this._a;
}
toHsv () {
let hsv = this.rgbToHsv(this._r, this._g, this._b);
return { h: hsv.h * 360, s: hsv.s, v: hsv.v, a: this._a };
}
// `rgbToHsv`
// Converts an RGB color value to HSV
// *Assumes:* r, g, and b are contained in the set [0, 255] or [0, 1]
// *Returns:* { h, s, v } in [0,1]
rgbToHsv (r, g, b) {
r = this.bound01(r, 255);
g = this.bound01(g, 255);
b = this.bound01(b, 255);
let max = mathMax(r, g, b), min = mathMin(r, g, b);
let h, s, v = max;
let d = max - min;
s = max === 0 ? 0 : d / max;
if(max == min) {
h = 0; // achromatic
}
else {
switch(max) {
case r: h = (g - b) / d + (g < b ? 6 : 0); break;
case g: h = (b - r) / d + 2; break;
case b: h = (r - g) / d + 4; break;
}
h /= 6;
}
return { h: h, s: s, v: v };
}
getFormat () {
return this._format;
}
}
export default SlimColor | 28.191781 | 145 | 0.542166 | 505 | 28 | 0 | 37 | 55 | 10 | 19 | 19 | 8 | 1 | 4 | 10.285714 | 7,356 | 0.008836 | 0.007477 | 0.001359 | 0.000136 | 0.000544 | 0.146154 | 0.061538 | 0.217734 | let trimLeft = /^\s+/;
let trimRight = /\s+$/;
let mathRound = Math.round;
let mathMin = Math.min;
let mathMax = Math.max;
let names = {
aliceblue: 'f0f8ff',
antiquewhite: 'faebd7',
aqua: '0ff',
aquamarine: '7fffd4',
azure: 'f0ffff',
beige: 'f5f5dc',
bisque: 'ffe4c4',
black: '000',
blanchedalmond: 'ffebcd',
blue: '00f',
blueviolet: '8a2be2',
brown: 'a52a2a',
burlywood: 'deb887',
burntsienna: 'ea7e5d',
cadetblue: '5f9ea0',
chartreuse: '7fff00',
chocolate: 'd2691e',
coral: 'ff7f50',
cornflowerblue: '6495ed',
cornsilk: 'fff8dc',
crimson: 'dc143c',
cyan: '0ff',
darkblue: '00008b',
darkcyan: '008b8b',
darkgoldenrod: 'b8860b',
darkgray: 'a9a9a9',
darkgreen: '006400',
darkgrey: 'a9a9a9',
darkkhaki: 'bdb76b',
darkmagenta: '8b008b',
darkolivegreen: '556b2f',
darkorange: 'ff8c00',
darkorchid: '9932cc',
darkred: '8b0000',
darksalmon: 'e9967a',
darkseagreen: '8fbc8f',
darkslateblue: '483d8b',
darkslategray: '2f4f4f',
darkslategrey: '2f4f4f',
darkturquoise: '00ced1',
darkviolet: '9400d3',
deeppink: 'ff1493',
deepskyblue: '00bfff',
dimgray: '696969',
dimgrey: '696969',
dodgerblue: '1e90ff',
firebrick: 'b22222',
floralwhite: 'fffaf0',
forestgreen: '228b22',
fuchsia: 'f0f',
gainsboro: 'dcdcdc',
ghostwhite: 'f8f8ff',
gold: 'ffd700',
goldenrod: 'daa520',
gray: '808080',
green: '008000',
greenyellow: 'adff2f',
grey: '808080',
honeydew: 'f0fff0',
hotpink: 'ff69b4',
indianred: 'cd5c5c',
indigo: '4b0082',
ivory: 'fffff0',
khaki: 'f0e68c',
lavender: 'e6e6fa',
lavenderblush: 'fff0f5',
lawngreen: '7cfc00',
lemonchiffon: 'fffacd',
lightblue: 'add8e6',
lightcoral: 'f08080',
lightcyan: 'e0ffff',
lightgoldenrodyellow: 'fafad2',
lightgray: 'd3d3d3',
lightgreen: '90ee90',
lightgrey: 'd3d3d3',
lightpink: 'ffb6c1',
lightsalmon: 'ffa07a',
lightseagreen: '20b2aa',
lightskyblue: '87cefa',
lightslategray: '789',
lightslategrey: '789',
lightsteelblue: 'b0c4de',
lightyellow: 'ffffe0',
lime: '0f0',
limegreen: '32cd32',
linen: 'faf0e6',
magenta: 'f0f',
maroon: '800000',
mediumaquamarine: '66cdaa',
mediumblue: '0000cd',
mediumorchid: 'ba55d3',
mediumpurple: '9370db',
mediumseagreen: '3cb371',
mediumslateblue: '7b68ee',
mediumspringgreen: '00fa9a',
mediumturquoise: '48d1cc',
mediumvioletred: 'c71585',
midnightblue: '191970',
mintcream: 'f5fffa',
mistyrose: 'ffe4e1',
moccasin: 'ffe4b5',
navajowhite: 'ffdead',
navy: '000080',
oldlace: 'fdf5e6',
olive: '808000',
olivedrab: '6b8e23',
orange: 'ffa500',
orangered: 'ff4500',
orchid: 'da70d6',
palegoldenrod: 'eee8aa',
palegreen: '98fb98',
paleturquoise: 'afeeee',
palevioletred: 'db7093',
papayawhip: 'ffefd5',
peachpuff: 'ffdab9',
peru: 'cd853f',
pink: 'ffc0cb',
plum: 'dda0dd',
powderblue: 'b0e0e6',
purple: '800080',
rebeccapurple: '663399',
red: 'f00',
rosybrown: 'bc8f8f',
royalblue: '4169e1',
saddlebrown: '8b4513',
salmon: 'fa8072',
sandybrown: 'f4a460',
seagreen: '2e8b57',
seashell: 'fff5ee',
sienna: 'a0522d',
silver: 'c0c0c0',
skyblue: '87ceeb',
slateblue: '6a5acd',
slategray: '708090',
slategrey: '708090',
snow: 'fffafa',
springgreen: '00ff7f',
steelblue: '4682b4',
tan: 'd2b48c',
teal: '008080',
thistle: 'd8bfd8',
tomato: 'ff6347',
turquoise: '40e0d0',
violet: 'ee82ee',
wheat: 'f5deb3',
white: 'fff',
whitesmoke: 'f5f5f5',
yellow: 'ff0',
yellowgreen: '9acd32',
};
class SlimColor {
_originalInput;
_r;
_g;
_b;
_a;
_roundA;
_ok = false;
rgb
_format
matchers
init (color = '') {
this.matchers = this.getMathers()
let rgb = this.inputToRGB(color);
this._originalInput = color
this._r = rgb.r
this._g = rgb.g
this._b = rgb.b
this._a = rgb.a
this._roundA = mathRound((100 * this._a) / 100);
this._format = rgb.format;
// Don't let the range of [0,255] come back in [0,1].
// Potentially lose a little bit of precision here, but will fix issues where
// .5 gets interpreted as half of the total, instead of half of 1
// If it was supposed to be 128, this was already taken care of by `inputToRgb`
if (this._r < 1) {
this._r = mathRound(this._r);
}
if (this._g < 1) {
this._g = mathRound(this._g);
}
if (this._b < 1) {
this._b = mathRound(this._b);
}
this._ok = rgb.ok;
}
// Given a string or object, convert that input to RGB
// Possible string inputs:
//
// "red"
// "#f00" or "f00"
// "#ff0000" or "ff0000"
// "#ff000000" or "ff000000"
// "rgb 255 0 0" or "rgb (255, 0, 0)"
// "rgb 1.0 0 0" or "rgb (1, 0, 0)"
// "rgba (255, 0, 0, 1)" or "rgba 255, 0, 0, 1"
// "rgba (1.0, 0, 0, 1)" or "rgba 1.0, 0, 0, 1"
// "hsl(0, 100%, 50%)" or "hsl 0 100% 50%"
// "hsla(0, 100%, 50%, 1)" or "hsla 0 100% 50%, 1"
// "hsv(0, 100%, 100%)" or "hsv 0 100% 100%"
inputToRGB(color) {
let rgb = { r: 0, g: 0, b: 0 };
let a = 1;
let s = null;
let v = null;
let l = null;
let ok = false;
let format = '';
if (typeof color == 'string') {
color = this.stringInputToObject(color);
}
if (typeof color == 'object') {
if (
this.isValidCSSUnit(color.r) &&
this.isValidCSSUnit(color.g) &&
this.isValidCSSUnit(color.b)
) {
rgb = this.rgbToRgb(color.r, color.g, color.b);
ok = true;
format = String(color.r).substring(-1) === '%' ? 'prgb' : 'rgb';
} else if (
this.isValidCSSUnit(color.h) &&
this.isValidCSSUnit(color.s) &&
this.isValidCSSUnit(color.v)
) {
s = this.convertToPercentage(color.s);
v = this.convertToPercentage(color.v);
rgb = this.hsvToRgb(color.h, s, v);
ok = true;
format = 'hsv';
} else if (
this.isValidCSSUnit(color.h) &&
this.isValidCSSUnit(color.s) &&
this.isValidCSSUnit(color.l)
) {
s = this.convertToPercentage(color.s);
l = this.convertToPercentage(color.l);
rgb = this.hslToRgb(color.h, s, l);
ok = true;
format = 'hsl';
}
if (color.hasOwnProperty('a')) {
a = color.a;
}
}
a = this.boundAlpha(a);
return {
ok: ok,
format: color.format || format,
r: mathMin(255, mathMax(rgb.r, 0)),
g: mathMin(255, mathMax(rgb.g, 0)),
b: mathMin(255, mathMax(rgb.b, 0)),
a: a,
};
}
getMathers () {
// <http://www.w3.org/TR/css3-values/#integers>
let CSS_INTEGER = "[-\\+]?\\d+%?";
// <http://www.w3.org/TR/css3-values/#number-value>
let CSS_NUMBER = "[-\\+]?\\d*\\.\\d+%?";
// Allow positive/negative integer/number. Don't capture the either/or, just the entire outcome.
let CSS_UNIT = "(?:" + CSS_NUMBER + ")|(?:" + CSS_INTEGER + ")";
// Actual matching.
// Parentheses and commas are optional, but not required.
// Whitespace can take the place of commas or opening paren
let PERMISSIVE_MATCH3 = "[\\s|\\(]+(" + CSS_UNIT + ")[,|\\s]+(" + CSS_UNIT + ")[,|\\s]+(" + CSS_UNIT + ")\\s*\\)?";
let PERMISSIVE_MATCH4 = "[\\s|\\(]+(" + CSS_UNIT + ")[,|\\s]+(" + CSS_UNIT + ")[,|\\s]+(" + CSS_UNIT + ")[,|\\s]+(" + CSS_UNIT + ")\\s*\\)?";
return {
CSS_UNIT: new RegExp(CSS_UNIT),
rgb: new RegExp("rgb" + PERMISSIVE_MATCH3),
rgba: new RegExp("rgba" + PERMISSIVE_MATCH4),
hsl: new RegExp("hsl" + PERMISSIVE_MATCH3),
hsla: new RegExp("hsla" + PERMISSIVE_MATCH4),
hsv: new RegExp("hsv" + PERMISSIVE_MATCH3),
hsva: new RegExp("hsva" + PERMISSIVE_MATCH4),
hex3: /^#?([0-9a-fA-F]{1})([0-9a-fA-F]{1})([0-9a-fA-F]{1})$/,
hex6: /^#?([0-9a-fA-F]{2})([0-9a-fA-F]{2})([0-9a-fA-F]{2})$/,
hex4: /^#?([0-9a-fA-F]{1})([0-9a-fA-F]{1})([0-9a-fA-F]{1})([0-9a-fA-F]{1})$/,
hex8: /^#?([0-9a-fA-F]{2})([0-9a-fA-F]{2})([0-9a-fA-F]{2})([0-9a-fA-F]{2})$/
}
}
// `stringInputToObject`
// Permissive string parsing. Take in a number of formats, and output an object
// based on detected format. Returns `{ r, g, b }` or `{ h, s, l }` or `{ h, s, v}`
stringInputToObject(color) {
color = color.replace(trimLeft, '').replace(trimRight, '').toLowerCase();
let named = false;
if (names[color]) {
color = names[color];
named = true;
} else if (color == 'transparent') {
return { r: 0, g: 0, b: 0, a: 0, format: 'name' };
}
// Try to match string input using regular expressions.
// Keep most of the number bounding out of this function - don't worry about [0,1] or [0,100] or [0,360]
// Just return an object and let the conversion functions handle that.
// This way the result will be the same whether the tinycolor is initialized with string or object.
let match;
if ((match = this.matchers.rgb.exec(color))) {
return { r: match[1], g: match[2], b: match[3] };
}
if ((match = this.matchers.rgba.exec(color))) {
return { r: match[1], g: match[2], b: match[3], a: match[4] };
}
if ((match = this.matchers.hsl.exec(color))) {
return { h: match[1], s: match[2], l: match[3] };
}
if ((match = this.matchers.hsla.exec(color))) {
return { h: match[1], s: match[2], l: match[3], a: match[4] };
}
if ((match = this.matchers.hsv.exec(color))) {
return { h: match[1], s: match[2], v: match[3] };
}
if ((match = this.matchers.hsva.exec(color))) {
return { h: match[1], s: match[2], v: match[3], a: match[4] };
}
if ((match = this.matchers.hex8.exec(color))) {
return {
r: this.parseIntFromHex(match[1]),
g: this.parseIntFromHex(match[2]),
b: this.parseIntFromHex(match[3]),
a: this.convertHexToDecimal(match[4]),
format: named ? "name" : "hex8"
};
}
if ((match = this.matchers.hex6.exec(color))) {
return {
r: this.parseIntFromHex(match[1]),
g: this.parseIntFromHex(match[2]),
b: this.parseIntFromHex(match[3]),
format: named ? "name" : "hex"
};
}
if ((match = this.matchers.hex4.exec(color))) {
return {
r: this.parseIntFromHex(match[1] + '' + match[1]),
g: this.parseIntFromHex(match[2] + '' + match[2]),
b: this.parseIntFromHex(match[3] + '' + match[3]),
a: this.convertHexToDecimal(match[4] + '' + match[4]),
format: named ? "name" : "hex8"
};
}
if ((match = this.matchers.hex3.exec(color))) {
return {
r: this.parseIntFromHex(match[1] + '' + match[1]),
g: this.parseIntFromHex(match[2] + '' + match[2]),
b: this.parseIntFromHex(match[3] + '' + match[3]),
format: named ? "name" : "hex"
};
}
return false;
}
// `isValidCSSUnit`
// Take in a single string / number and check to see if it looks like a CSS unit
// (see `matchers` above for definition).
isValidCSSUnit(color) {
return !!this.matchers.CSS_UNIT.exec(color);
}
// Conversion Functions
// --------------------
// `rgbToHsl`, `rgbToHsv`, `hslToRgb`, `hsvToRgb` modified from:
// <http://mjijackson.com/2008/02/rgb-to-hsl-and-rgb-to-hsv-color-model-conversion-algorithms-in-javascript>
// `rgbToRgb`
// Handle bounds / percentage checking to conform to CSS color spec
// <http://www.w3.org/TR/css3-color/>
// *Assumes:* r, g, b in [0, 255] or [0, 1]
// *Returns:* { r, g, b } in [0, 255]
rgbToRgb(r, g, b) {
return {
r: this.bound01(r, 255) * 255,
g: this.bound01(g, 255) * 255,
b: this.bound01(b, 255) * 255,
};
}
// Replace a decimal with it's percentage value
convertToPercentage(n) {
if (n <= 1) {
n = n * 100 + '%';
}
return n;
}
// `hsvToRgb`
// Converts an HSV color value to RGB.
// *Assumes:* h is contained in [0, 1] or [0, 360] and s and v are contained in [0, 1] or [0, 100]
// *Returns:* { r, g, b } in the set [0, 255]
hsvToRgb(h, s, v) {
h = this.bound01(h, 360) * 6;
s = this.bound01(s, 100);
v = this.bound01(v, 100);
let i = Math.floor(h),
f = h - i,
p = v * (1 - s),
q = v * (1 - f * s),
t = v * (1 - (1 - f) * s),
mod = i % 6,
r = [v, q, p, p, t, v][mod],
g = [t, v, v, q, p, p][mod],
b = [p, p, t, v, v, q][mod];
return { r: r * 255, g: g * 255, b: b * 255 };
}
// Return a valid alpha value [0,1] with all invalid values being set to 1
boundAlpha(a) {
a = parseFloat(a);
if (isNaN(a) || a < 0 || a > 1) {
a = 1;
}
return a;
}
// `hslToRgb`
// Converts an HSL color value to RGB.
// *Assumes:* h is contained in [0, 1] or [0, 360] and s and l are contained [0, 1] or [0, 100]
// *Returns:* { r, g, b } in the set [0, 255]
hslToRgb(h, s, l) {
let r, g, b;
h = this.bound01(h, 360);
s = this.bound01(s, 100);
l = this.bound01(l, 100);
/* Example usages of 'hue2rgb' are shown below:
r = hue2rgb(p, q, h + 1 / 3);
g = hue2rgb(p, q, h);
b = hue2rgb(p, q, h - 1 / 3);
*/
function hue2rgb(p, q, t) {
if (t < 0) t += 1;
if (t > 1) t -= 1;
if (t < 1 / 6) return p + (q - p) * 6 * t;
if (t < 1 / 2) return q;
if (t < 2 / 3) return p + (q - p) * (2 / 3 - t) * 6;
return p;
}
if (s === 0) {
r = g = b = l; // achromatic
} else {
let q = l < 0.5 ? l * (1 + s) : l + s - l * s;
let p = 2 * l - q;
r = hue2rgb(p, q, h + 1 / 3);
g = hue2rgb(p, q, h);
b = hue2rgb(p, q, h - 1 / 3);
}
return { r: r * 255, g: g * 255, b: b * 255 };
}
// Parse a base-16 hex value into a base-10 integer
parseIntFromHex(val) {
return parseInt(val, 16);
}
// Converts a hex value to a decimal
convertHexToDecimal(h) {
return (this.parseIntFromHex(h) / 255);
}
// Take input from [0, n] and return it as [0, 1]
bound01(n, max) {
if (this.isOnePointZero(n)) { n = "100%"; }
let processPercent = this.isPercentage(n);
n = mathMin(max, mathMax(0, parseFloat(n)));
// Automatically convert percentage into number
if (processPercent) {
n = parseInt((n * max).toString(), 10) / 100;
}
// Handle floating point rounding errors
if ((Math.abs(n - max) < 0.000001)) {
return 1;
}
// Convert into [0, 1] range if it isn't already
return (n % max) / parseFloat(max);
}
// Need to handle 1.0 as 100%, since once it is a number, there is no difference between it and 1
// <http://stackoverflow.com/questions/7422072/javascript-how-to-detect-number-as-a-decimal-including-1-0>
isOnePointZero(n) {
return typeof n == "string" && n.indexOf('.') != -1 && parseFloat(n) === 1;
}
// Check to see if string passed in is a percentage
isPercentage(n) {
return typeof n === "string" && n.indexOf('%') != -1;
}
toHsl () {
let hsl = this.rgbToHsl(this._r, this._g, this._b);
return { h: hsl.h * 360, s: hsl.s, l: hsl.l, a: this._a };
}
// `rgbToHsl`
// Converts an RGB color value to HSL.
// *Assumes:* r, g, and b are contained in [0, 255] or [0, 1]
// *Returns:* { h, s, l } in [0,1]
rgbToHsl(r, g, b) {
r = this.bound01(r, 255);
g = this.bound01(g, 255);
b = this.bound01(b, 255);
let max = mathMax(r, g, b), min = mathMin(r, g, b);
let h, s, l = (max + min) / 2;
if(max == min) {
h = s = 0; // achromatic
}
else {
let d = max - min;
s = l > 0.5 ? d / (2 - max - min) : d / (max + min);
switch(max) {
case r: h = (g - b) / d + (g < b ? 6 : 0); break;
case g: h = (b - r) / d + 2; break;
case b: h = (r - g) / d + 4; break;
}
h /= 6;
}
return { h: h, s: s, l: l };
}
setAlpha (value) {
this._a = this.boundAlpha(value);
this._roundA = mathRound(100*this._a) / 100;
return this;
}
toHex (allow3Char = false) {
return this.rgbToHex(this._r, this._g, this._b, allow3Char);
}
// `rgbToHex`
// Converts an RGB color to hex
// Assumes r, g, and b are contained in the set [0, 255]
// Returns a 3 or 6 character hex
rgbToHex(r, g, b, allow3Char) {
let hex = [
this.pad2(mathRound(r).toString(16)),
this.pad2(mathRound(g).toString(16)),
this.pad2(mathRound(b).toString(16))
];
// Return a 3 character hex if possible
if (allow3Char && hex[0].charAt(0) == hex[0].charAt(1) && hex[1].charAt(0) == hex[1].charAt(1) && hex[2].charAt(0) == hex[2].charAt(1)) {
return hex[0].charAt(0) + hex[1].charAt(0) + hex[2].charAt(0);
}
return hex.join("");
}
// Force a hex value to have 2 characters
pad2(c) {
return c.length == 1 ? '0' + c : '' + c;
}
toRgbString () {
return (this._a == 1) ?
"rgb(" + mathRound(this._r) + ", " + mathRound(this._g) + ", " + mathRound(this._b) + ")" :
"rgba(" + mathRound(this._r) + ", " + mathRound(this._g) + ", " + mathRound(this._b) + ", " + this._roundA + ")";
}
toHslString () {
let hsl = this.rgbToHsl(this._r, this._g, this._b);
let h = mathRound(hsl.h * 360), s = mathRound(hsl.s * 100), l = mathRound(hsl.l * 100);
return (this._a == 1) ?
"hsl(" + h + ", " + s + "%, " + l + "%)" :
"hsla(" + h + ", " + s + "%, " + l + "%, "+ this._roundA + ")";
}
getAlpha () {
return this._a;
}
toHsv () {
let hsv = this.rgbToHsv(this._r, this._g, this._b);
return { h: hsv.h * 360, s: hsv.s, v: hsv.v, a: this._a };
}
// `rgbToHsv`
// Converts an RGB color value to HSV
// *Assumes:* r, g, and b are contained in the set [0, 255] or [0, 1]
// *Returns:* { h, s, v } in [0,1]
rgbToHsv (r, g, b) {
r = this.bound01(r, 255);
g = this.bound01(g, 255);
b = this.bound01(b, 255);
let max = mathMax(r, g, b), min = mathMin(r, g, b);
let h, s, v = max;
let d = max - min;
s = max === 0 ? 0 : d / max;
if(max == min) {
h = 0; // achromatic
}
else {
switch(max) {
case r: h = (g - b) / d + (g < b ? 6 : 0); break;
case g: h = (b - r) / d + 2; break;
case b: h = (r - g) / d + 4; break;
}
h /= 6;
}
return { h: h, s: s, v: v };
}
getFormat () {
return this._format;
}
}
export default SlimColor |
e8140bab25bd03c16b95fc874dad8737bad97046 | 3,655 | ts | TypeScript | src/utils/Color.ts | x6ud/pixel-skeletal-animation-editor | 7e681275347653ec02ccf29b0864e439e3ae6a79 | [
"MIT"
] | 2 | 2022-01-01T01:23:25.000Z | 2022-01-09T06:29:52.000Z | src/utils/Color.ts | x6ud/pixel-skeletal-animation-editor | 7e681275347653ec02ccf29b0864e439e3ae6a79 | [
"MIT"
] | null | null | null | src/utils/Color.ts | x6ud/pixel-skeletal-animation-editor | 7e681275347653ec02ccf29b0864e439e3ae6a79 | [
"MIT"
] | null | null | null | export default class Color {
/** 0 ~ 255 */
readonly r: number;
/** 0 ~ 255 */
readonly g: number;
/** 0 ~ 255 */
readonly b: number;
/** 0 ~ 1 */
readonly h: number;
/** 0 ~ 1 */
readonly s: number;
/** 0 ~ 1 */
readonly v: number;
private constructor(r: number, g: number, b: number, h: number, s: number, v: number) {
this.r = r;
this.g = g;
this.b = b;
this.h = h;
this.s = s;
this.v = v;
}
/**
* @param h 0 ~ 1
* @param s 0 ~ 1
* @param v 0 ~ 1
*/
static hsv(h: number, s: number, v: number) {
let r: number = 0,
g: number = 0,
b: number = 0,
i: number = Math.floor(h * 6),
f: number = h * 6 - i,
p: number = v * (1 - s),
q: number = v * (1 - f * s),
t: number = v * (1 - (1 - f) * s);
switch (i % 6) {
case 0:
r = v;
g = t;
b = p;
break;
case 1:
r = q;
g = v;
b = p;
break;
case 2:
r = p;
g = v;
b = t;
break;
case 3:
r = p;
g = q;
b = v;
break;
case 4:
r = t;
g = p;
b = v;
break;
case 5:
r = v;
g = p;
b = q;
break;
}
return new Color(Math.round(r * 255), Math.round(g * 255), Math.round(b * 255), h, s, v);
}
/**
* @param r 0 ~ 255
* @param g 0 ~ 255
* @param b 0 ~ 255
*/
static rgb(r: number, g: number, b: number) {
let max = Math.max(r, g, b),
min = Math.min(r, g, b),
det = max - min,
h = 0,
s = (max === 0 ? 0 : det / max),
v = max / 255;
switch (max) {
case min:
h = 0;
break;
case r:
h = (g - b) + det * (g < b ? 6 : 0);
h /= 6 * det;
break;
case g:
h = (b - r) + det * 2;
h /= 6 * det;
break;
case b:
h = (r - g) + det * 4;
h /= 6 * det;
break;
}
return new Color(r, g, b, h, s, v);
}
static parse(val: any): Color {
if (!val) {
return Color.rgb(0, 0, 0);
}
if (typeof val === 'string') {
if (val.startsWith('#')) {
const num = Number.parseInt(val.substr(1), 16);
if (isNaN(num)) {
throw new Error('Failed to parse');
}
const r = (num >> 16) & 0xff;
const g = (num >> 8) & 0xff;
const b = num & 0xff;
return Color.rgb(r, b, g);
}
}
if (typeof val === 'number') {
const r = (val >> 16) & 0xff;
const g = (val >> 8) & 0xff;
const b = val & 0xff;
return Color.rgb(r, b, g);
}
throw new Error('Failed to parse');
}
valueOf() {
return (this.r << 16) | (this.g << 8) | (this.b);
}
toString() {
return '#' + this.valueOf().toString(16).padStart(6, '0');
}
static readonly WHITE = Color.rgb(0xff, 0xff, 0xff);
static readonly BLACK = Color.rgb(0, 0, 0);
}
| 24.863946 | 97 | 0.331601 | 117 | 6 | 0 | 13 | 21 | 8 | 3 | 1 | 26 | 1 | 2 | 15.833333 | 1,088 | 0.017463 | 0.019301 | 0.007353 | 0.000919 | 0.001838 | 0.020833 | 0.541667 | 0.274952 | export default class Color {
/** 0 ~ 255 */
readonly r;
/** 0 ~ 255 */
readonly g;
/** 0 ~ 255 */
readonly b;
/** 0 ~ 1 */
readonly h;
/** 0 ~ 1 */
readonly s;
/** 0 ~ 1 */
readonly v;
private constructor(r, g, b, h, s, v) {
this.r = r;
this.g = g;
this.b = b;
this.h = h;
this.s = s;
this.v = v;
}
/**
* @param h 0 ~ 1
* @param s 0 ~ 1
* @param v 0 ~ 1
*/
static hsv(h, s, v) {
let r = 0,
g = 0,
b = 0,
i = Math.floor(h * 6),
f = h * 6 - i,
p = v * (1 - s),
q = v * (1 - f * s),
t = v * (1 - (1 - f) * s);
switch (i % 6) {
case 0:
r = v;
g = t;
b = p;
break;
case 1:
r = q;
g = v;
b = p;
break;
case 2:
r = p;
g = v;
b = t;
break;
case 3:
r = p;
g = q;
b = v;
break;
case 4:
r = t;
g = p;
b = v;
break;
case 5:
r = v;
g = p;
b = q;
break;
}
return new Color(Math.round(r * 255), Math.round(g * 255), Math.round(b * 255), h, s, v);
}
/**
* @param r 0 ~ 255
* @param g 0 ~ 255
* @param b 0 ~ 255
*/
static rgb(r, g, b) {
let max = Math.max(r, g, b),
min = Math.min(r, g, b),
det = max - min,
h = 0,
s = (max === 0 ? 0 : det / max),
v = max / 255;
switch (max) {
case min:
h = 0;
break;
case r:
h = (g - b) + det * (g < b ? 6 : 0);
h /= 6 * det;
break;
case g:
h = (b - r) + det * 2;
h /= 6 * det;
break;
case b:
h = (r - g) + det * 4;
h /= 6 * det;
break;
}
return new Color(r, g, b, h, s, v);
}
static parse(val) {
if (!val) {
return Color.rgb(0, 0, 0);
}
if (typeof val === 'string') {
if (val.startsWith('#')) {
const num = Number.parseInt(val.substr(1), 16);
if (isNaN(num)) {
throw new Error('Failed to parse');
}
const r = (num >> 16) & 0xff;
const g = (num >> 8) & 0xff;
const b = num & 0xff;
return Color.rgb(r, b, g);
}
}
if (typeof val === 'number') {
const r = (val >> 16) & 0xff;
const g = (val >> 8) & 0xff;
const b = val & 0xff;
return Color.rgb(r, b, g);
}
throw new Error('Failed to parse');
}
valueOf() {
return (this.r << 16) | (this.g << 8) | (this.b);
}
toString() {
return '#' + this.valueOf().toString(16).padStart(6, '0');
}
static readonly WHITE = Color.rgb(0xff, 0xff, 0xff);
static readonly BLACK = Color.rgb(0, 0, 0);
}
|
e8163c19af6d0400d21846442a54c5e20ba9eac3 | 4,404 | ts | TypeScript | src/options.ts | AlaaZorkane/ts-proto | 8f3d7dcde4172efd2659bd71ff4e96b412c5373a | [
"Apache-2.0"
] | 1 | 2022-01-12T15:26:53.000Z | 2022-01-12T15:26:53.000Z | src/options.ts | AlaaZorkane/ts-proto | 8f3d7dcde4172efd2659bd71ff4e96b412c5373a | [
"Apache-2.0"
] | null | null | null | src/options.ts | AlaaZorkane/ts-proto | 8f3d7dcde4172efd2659bd71ff4e96b412c5373a | [
"Apache-2.0"
] | null | null | null | export enum LongOption {
NUMBER = 'number',
LONG = 'long',
STRING = 'string',
}
export enum DateOption {
DATE = 'date',
STRING = 'string',
TIMESTAMP = 'timestamp',
}
export enum EnvOption {
NODE = 'node',
BROWSER = 'browser',
BOTH = 'both',
}
export enum OneofOption {
PROPERTIES = 'properties',
UNIONS = 'unions',
}
export enum ServiceOption {
GRPC = 'grpc-js',
GENERIC = 'generic-definitions',
DEFAULT = 'default',
NONE = 'none',
}
export type Options = {
context: boolean;
snakeToCamel: Array<'json' | 'keys'>;
forceLong: LongOption;
useOptionals: boolean | 'none' | 'messages' | 'all'; // boolean is deprecated
useDate: DateOption;
oneof: OneofOption;
esModuleInterop: boolean;
fileSuffix: string;
outputEncodeMethods: boolean;
outputJsonMethods: boolean;
outputPartialMethods: boolean;
outputTypeRegistry: boolean;
stringEnums: boolean;
constEnums: boolean;
enumsAsLiterals: boolean;
outputClientImpl: boolean | 'grpc-web';
outputServices: ServiceOption;
addGrpcMetadata: boolean;
addNestjsRestParameter: boolean;
returnObservable: boolean;
lowerCaseServiceMethods: boolean;
nestJs: boolean;
env: EnvOption;
unrecognizedEnum: boolean;
exportCommonSymbols: boolean;
outputSchema: boolean;
// An alias of !output
onlyTypes: boolean;
emitImportedFiles: boolean;
useExactTypes: boolean;
delimitedMethods: boolean;
};
export function defaultOptions(): Options {
return {
context: false,
snakeToCamel: ['json', 'keys'],
forceLong: LongOption.NUMBER,
useOptionals: 'none',
useDate: DateOption.DATE,
oneof: OneofOption.PROPERTIES,
esModuleInterop: false,
fileSuffix: '',
lowerCaseServiceMethods: false,
outputEncodeMethods: true,
outputJsonMethods: true,
outputPartialMethods: true,
outputTypeRegistry: false,
stringEnums: false,
constEnums: false,
enumsAsLiterals: false,
outputClientImpl: true,
outputServices: ServiceOption.DEFAULT,
returnObservable: false,
addGrpcMetadata: false,
addNestjsRestParameter: false,
nestJs: false,
env: EnvOption.BOTH,
unrecognizedEnum: true,
exportCommonSymbols: true,
outputSchema: false,
onlyTypes: false,
emitImportedFiles: true,
useExactTypes: true,
delimitedMethods: false,
};
}
const nestJsOptions: Partial<Options> = {
lowerCaseServiceMethods: true,
outputEncodeMethods: false,
outputJsonMethods: false,
outputPartialMethods: false,
outputClientImpl: false,
useDate: DateOption.TIMESTAMP,
};
export function optionsFromParameter(parameter: string | undefined): Options {
const options = defaultOptions();
if (parameter) {
const parsed = parseParameter(parameter);
if (parsed.nestJs) {
Object.assign(options, nestJsOptions);
}
Object.assign(options, parsed);
}
// We should promote onlyTypes to its own documented flag, but just an alias for now
if (!options.outputJsonMethods && !options.outputEncodeMethods && !options.outputClientImpl && !options.nestJs) {
options.onlyTypes = true;
}
// Treat forceLong=true as LONG
if ((options.forceLong as any) === true) {
options.forceLong = LongOption.LONG;
}
// Treat outputServices=false as NONE
if ((options.outputServices as any) === false) {
options.outputServices = ServiceOption.NONE;
}
if ((options.useDate as any) === true) {
// Treat useDate=true as DATE
options.useDate = DateOption.DATE;
} else if ((options.useDate as any) === false) {
// Treat useDate=false as TIMESTAMP
options.useDate = DateOption.TIMESTAMP;
}
if ((options.snakeToCamel as any) === false) {
options.snakeToCamel = [];
} else if ((options.snakeToCamel as any) === true) {
options.snakeToCamel = ['keys', 'json'];
}
return options;
}
// A very naive parse function, eventually could/should use iots/runtypes
function parseParameter(parameter: string): Options {
const options = {} as any;
const pairs = parameter.split(',').map((s) => s.split('='));
pairs.forEach(([key, value]) => {
options[key] = value === 'true' ? true : value === 'false' ? false : value;
});
return options;
}
export function getTsPoetOpts(options: Options): { forceDefaultImport?: string[] } {
if (options.esModuleInterop) {
return { forceDefaultImport: ['protobufjs/minimal'] };
} else {
return {};
}
}
| 26.371257 | 115 | 0.691417 | 144 | 6 | 0 | 5 | 5 | 30 | 2 | 7 | 27 | 1 | 7 | 12.166667 | 1,179 | 0.00933 | 0.004241 | 0.025445 | 0.000848 | 0.005937 | 0.152174 | 0.586957 | 0.203541 | export enum LongOption {
NUMBER = 'number',
LONG = 'long',
STRING = 'string',
}
export enum DateOption {
DATE = 'date',
STRING = 'string',
TIMESTAMP = 'timestamp',
}
export enum EnvOption {
NODE = 'node',
BROWSER = 'browser',
BOTH = 'both',
}
export enum OneofOption {
PROPERTIES = 'properties',
UNIONS = 'unions',
}
export enum ServiceOption {
GRPC = 'grpc-js',
GENERIC = 'generic-definitions',
DEFAULT = 'default',
NONE = 'none',
}
export type Options = {
context;
snakeToCamel;
forceLong;
useOptionals; // boolean is deprecated
useDate;
oneof;
esModuleInterop;
fileSuffix;
outputEncodeMethods;
outputJsonMethods;
outputPartialMethods;
outputTypeRegistry;
stringEnums;
constEnums;
enumsAsLiterals;
outputClientImpl;
outputServices;
addGrpcMetadata;
addNestjsRestParameter;
returnObservable;
lowerCaseServiceMethods;
nestJs;
env;
unrecognizedEnum;
exportCommonSymbols;
outputSchema;
// An alias of !output
onlyTypes;
emitImportedFiles;
useExactTypes;
delimitedMethods;
};
export /* Example usages of 'defaultOptions' are shown below:
defaultOptions();
*/
function defaultOptions() {
return {
context: false,
snakeToCamel: ['json', 'keys'],
forceLong: LongOption.NUMBER,
useOptionals: 'none',
useDate: DateOption.DATE,
oneof: OneofOption.PROPERTIES,
esModuleInterop: false,
fileSuffix: '',
lowerCaseServiceMethods: false,
outputEncodeMethods: true,
outputJsonMethods: true,
outputPartialMethods: true,
outputTypeRegistry: false,
stringEnums: false,
constEnums: false,
enumsAsLiterals: false,
outputClientImpl: true,
outputServices: ServiceOption.DEFAULT,
returnObservable: false,
addGrpcMetadata: false,
addNestjsRestParameter: false,
nestJs: false,
env: EnvOption.BOTH,
unrecognizedEnum: true,
exportCommonSymbols: true,
outputSchema: false,
onlyTypes: false,
emitImportedFiles: true,
useExactTypes: true,
delimitedMethods: false,
};
}
const nestJsOptions = {
lowerCaseServiceMethods: true,
outputEncodeMethods: false,
outputJsonMethods: false,
outputPartialMethods: false,
outputClientImpl: false,
useDate: DateOption.TIMESTAMP,
};
export function optionsFromParameter(parameter) {
const options = defaultOptions();
if (parameter) {
const parsed = parseParameter(parameter);
if (parsed.nestJs) {
Object.assign(options, nestJsOptions);
}
Object.assign(options, parsed);
}
// We should promote onlyTypes to its own documented flag, but just an alias for now
if (!options.outputJsonMethods && !options.outputEncodeMethods && !options.outputClientImpl && !options.nestJs) {
options.onlyTypes = true;
}
// Treat forceLong=true as LONG
if ((options.forceLong as any) === true) {
options.forceLong = LongOption.LONG;
}
// Treat outputServices=false as NONE
if ((options.outputServices as any) === false) {
options.outputServices = ServiceOption.NONE;
}
if ((options.useDate as any) === true) {
// Treat useDate=true as DATE
options.useDate = DateOption.DATE;
} else if ((options.useDate as any) === false) {
// Treat useDate=false as TIMESTAMP
options.useDate = DateOption.TIMESTAMP;
}
if ((options.snakeToCamel as any) === false) {
options.snakeToCamel = [];
} else if ((options.snakeToCamel as any) === true) {
options.snakeToCamel = ['keys', 'json'];
}
return options;
}
// A very naive parse function, eventually could/should use iots/runtypes
/* Example usages of 'parseParameter' are shown below:
parseParameter(parameter);
*/
function parseParameter(parameter) {
const options = {} as any;
const pairs = parameter.split(',').map((s) => s.split('='));
pairs.forEach(([key, value]) => {
options[key] = value === 'true' ? true : value === 'false' ? false : value;
});
return options;
}
export function getTsPoetOpts(options) {
if (options.esModuleInterop) {
return { forceDefaultImport: ['protobufjs/minimal'] };
} else {
return {};
}
}
|
e851cc5a5ace3ad76d0ba0afd1852b38b15b9b08 | 1,534 | ts | TypeScript | src/lib/stringmap.ts | Turtlepaw/signal | b23a0e1a5505262aaec628ff65d0f4ebffed5a79 | [
"MIT"
] | 1 | 2022-03-30T02:04:15.000Z | 2022-03-30T02:04:15.000Z | src/lib/stringmap.ts | Turtlepaw/signal | b23a0e1a5505262aaec628ff65d0f4ebffed5a79 | [
"MIT"
] | null | null | null | src/lib/stringmap.ts | Turtlepaw/signal | b23a0e1a5505262aaec628ff65d0f4ebffed5a79 | [
"MIT"
] | null | null | null | export default class StringMap<K, V> {
public _values: object = {};
get(key: K): V {
//@ts-expect-error
let value = this._values[key];
return value != null ? value : null;
}
set(key: K, value: V) {
if (key instanceof Object) {
for (let prop in key) {
//@ts-expect-error
this._values[prop] = key[prop];
}
} else {
//@ts-expect-error
this._values[key] = value;
}
}
exists(key: K) {
//@ts-expect-error
return this._values[key] != null;
}
remove(key: K) {
if (this.exists(key)) {
//@ts-expect-error
return delete this._values[key];
}
return false;
}
keys(): K[] {
let keys = [];
for (let prop in this._values) {
//@ts-expect-error
if (this.exists(prop)) {
keys.push(prop);
}
}
return keys;
}
toString(formatted?: boolean, ident?: string) {
if (formatted) {
return JSON.stringify(this._values, null, ident || '\t');
}
return JSON.stringify(this._values);
}
}
export function parseStringMap(str: string, res: "STRING_MAP" | "MAP") {
if(str.length <= 0) return new Map();
const json = JSON.parse(str);
if(res == "MAP") {
const map = new Map<string, string>();
for (const key of Object.keys(json)) {
map.set(key, json[key]);
}
return map;
} else if(res == "STRING_MAP"){
const map = new StringMap<string, string>();
for (const key of Object.keys(json)) {
map.set(key, json[key]);
}
return map;
}
} | 21.605634 | 72 | 0.551499 | 57 | 7 | 0 | 9 | 5 | 1 | 3 | 0 | 8 | 1 | 1 | 5.714286 | 466 | 0.034335 | 0.01073 | 0.002146 | 0.002146 | 0.002146 | 0 | 0.363636 | 0.28888 | export default class StringMap<K, V> {
public _values = {};
get(key) {
//@ts-expect-error
let value = this._values[key];
return value != null ? value : null;
}
set(key, value) {
if (key instanceof Object) {
for (let prop in key) {
//@ts-expect-error
this._values[prop] = key[prop];
}
} else {
//@ts-expect-error
this._values[key] = value;
}
}
exists(key) {
//@ts-expect-error
return this._values[key] != null;
}
remove(key) {
if (this.exists(key)) {
//@ts-expect-error
return delete this._values[key];
}
return false;
}
keys() {
let keys = [];
for (let prop in this._values) {
//@ts-expect-error
if (this.exists(prop)) {
keys.push(prop);
}
}
return keys;
}
toString(formatted?, ident?) {
if (formatted) {
return JSON.stringify(this._values, null, ident || '\t');
}
return JSON.stringify(this._values);
}
}
export function parseStringMap(str, res) {
if(str.length <= 0) return new Map();
const json = JSON.parse(str);
if(res == "MAP") {
const map = new Map<string, string>();
for (const key of Object.keys(json)) {
map.set(key, json[key]);
}
return map;
} else if(res == "STRING_MAP"){
const map = new StringMap<string, string>();
for (const key of Object.keys(json)) {
map.set(key, json[key]);
}
return map;
}
} |
e88a15592acc457cf8f0abde4fdd10eb497786eb | 3,132 | ts | TypeScript | src/classes/Graph.ts | oadpoaw/disclosure-bot | fb978f9802185e91dcfa1a169e6769f9d00974f0 | [
"MIT"
] | 1 | 2022-03-24T07:14:00.000Z | 2022-03-24T07:14:00.000Z | src/classes/Graph.ts | oadpoaw/disclosure-bot | fb978f9802185e91dcfa1a169e6769f9d00974f0 | [
"MIT"
] | 4 | 2022-03-08T15:46:42.000Z | 2022-03-23T19:13:36.000Z | src/classes/Graph.ts | oadpoaw/disclosure-bot | fb978f9802185e91dcfa1a169e6769f9d00974f0 | [
"MIT"
] | null | null | null | type Node = string;
interface Edge {
source: Node;
target: Node;
}
interface Serialized {
nodes: Node[];
links: Edge[];
}
class GraphCycleError extends Error {
constructor(message: string) {
super(message);
Object.setPrototypeOf(this, GraphCycleError.prototype);
}
}
export class Graph {
private adjacencyList: Record<Node, Node[]>;
public constructor() {
this.adjacencyList = {};
}
private adjacent(node: Node): Node[] {
return this.adjacencyList[node] || [];
}
public addNode(node: Node) {
this.adjacencyList[node] = this.adjacent(node);
return this;
}
public removeNode(node: Node) {
for (const key in this.adjacencyList) {
for (const r of this.adjacencyList[key]) {
if (r === node) {
this.removeEdge(r, key);
}
}
}
for (const u in this.adjacencyList) {
for (const v in this.adjacencyList[u]) {
if (v === node) {
this.removeEdge(u, v);
}
}
}
delete this.adjacencyList[node];
return this;
}
public nodes() {
return Object.keys(this.adjacencyList);
}
public addEdge(source: Node, target: Node) {
this.addNode(source);
this.addNode(target);
this.adjacent(source).push(target);
return this;
}
public removeEdge(u: Node, v: Node) {
if (this.adjacencyList[u])
this.adjacencyList[u] = this.adjacent(u).filter((_v) => _v !== v);
return this;
}
public hasEdge(source: Node, target: Node) {
return this.adjacent(source).includes(target);
}
public depthFirstSearch(
sourceNodes?: Node[],
includeSourceNodes: boolean = true,
errorCycle: string | false = 'Cycle found',
): Node[] {
if (!sourceNodes) sourceNodes = this.nodes();
if (typeof includeSourceNodes !== 'boolean') includeSourceNodes = true;
const visited_nodes: Record<Node, boolean> = {};
const visiting_nodes: Record<Node, boolean> = {};
const node_list: Node[] = [];
const dfs = (node: Node) => {
if (visiting_nodes[node] && errorCycle)
throw new GraphCycleError(errorCycle);
if (!visited_nodes[node]) {
visited_nodes[node] = true;
visiting_nodes[node] = true;
this.adjacent(node).forEach(dfs);
visiting_nodes[node] = false;
node_list.push(node);
}
};
if (includeSourceNodes) {
sourceNodes.forEach(dfs);
} else {
for (const node of sourceNodes) {
visited_nodes[node] = true;
this.adjacent(node).forEach(dfs);
}
}
return node_list;
}
public hasCycle(): boolean {
try {
this.depthFirstSearch(undefined, true);
return false;
} catch (error) {
if (
error instanceof GraphCycleError &&
error.name === 'GraphCycleError'
) {
return true;
} else {
throw error;
}
}
}
public topologicalSort(
sourceNodes?: Node[],
includeSourceNodes: boolean = true,
) {
return this.depthFirstSearch(sourceNodes, includeSourceNodes, false);
}
public toJSON(): Serialized {
const serialized: Serialized = {
nodes: this.nodes(),
links: [],
};
for (const source of serialized.nodes) {
for (const target of this.adjacent(source)) {
serialized.links.push({
source,
target,
});
}
}
return serialized;
}
}
| 19.575 | 73 | 0.647829 | 130 | 15 | 0 | 17 | 5 | 5 | 5 | 0 | 8 | 5 | 2 | 6.2 | 1,025 | 0.03122 | 0.004878 | 0.004878 | 0.004878 | 0.001951 | 0 | 0.190476 | 0.267639 | type Node = string;
interface Edge {
source;
target;
}
interface Serialized {
nodes;
links;
}
class GraphCycleError extends Error {
constructor(message) {
super(message);
Object.setPrototypeOf(this, GraphCycleError.prototype);
}
}
export class Graph {
private adjacencyList;
public constructor() {
this.adjacencyList = {};
}
private adjacent(node) {
return this.adjacencyList[node] || [];
}
public addNode(node) {
this.adjacencyList[node] = this.adjacent(node);
return this;
}
public removeNode(node) {
for (const key in this.adjacencyList) {
for (const r of this.adjacencyList[key]) {
if (r === node) {
this.removeEdge(r, key);
}
}
}
for (const u in this.adjacencyList) {
for (const v in this.adjacencyList[u]) {
if (v === node) {
this.removeEdge(u, v);
}
}
}
delete this.adjacencyList[node];
return this;
}
public nodes() {
return Object.keys(this.adjacencyList);
}
public addEdge(source, target) {
this.addNode(source);
this.addNode(target);
this.adjacent(source).push(target);
return this;
}
public removeEdge(u, v) {
if (this.adjacencyList[u])
this.adjacencyList[u] = this.adjacent(u).filter((_v) => _v !== v);
return this;
}
public hasEdge(source, target) {
return this.adjacent(source).includes(target);
}
public depthFirstSearch(
sourceNodes?,
includeSourceNodes = true,
errorCycle = 'Cycle found',
) {
if (!sourceNodes) sourceNodes = this.nodes();
if (typeof includeSourceNodes !== 'boolean') includeSourceNodes = true;
const visited_nodes = {};
const visiting_nodes = {};
const node_list = [];
/* Example usages of 'dfs' are shown below:
this.adjacent(node).forEach(dfs);
sourceNodes.forEach(dfs);
*/
const dfs = (node) => {
if (visiting_nodes[node] && errorCycle)
throw new GraphCycleError(errorCycle);
if (!visited_nodes[node]) {
visited_nodes[node] = true;
visiting_nodes[node] = true;
this.adjacent(node).forEach(dfs);
visiting_nodes[node] = false;
node_list.push(node);
}
};
if (includeSourceNodes) {
sourceNodes.forEach(dfs);
} else {
for (const node of sourceNodes) {
visited_nodes[node] = true;
this.adjacent(node).forEach(dfs);
}
}
return node_list;
}
public hasCycle() {
try {
this.depthFirstSearch(undefined, true);
return false;
} catch (error) {
if (
error instanceof GraphCycleError &&
error.name === 'GraphCycleError'
) {
return true;
} else {
throw error;
}
}
}
public topologicalSort(
sourceNodes?,
includeSourceNodes = true,
) {
return this.depthFirstSearch(sourceNodes, includeSourceNodes, false);
}
public toJSON() {
const serialized = {
nodes: this.nodes(),
links: [],
};
for (const source of serialized.nodes) {
for (const target of this.adjacent(source)) {
serialized.links.push({
source,
target,
});
}
}
return serialized;
}
}
|
e8af3472f46272efb405c297ed760fe9c7423311 | 1,313 | ts | TypeScript | app/components/views/Home/constants.ts | GreenerDAO/klimadao | fd07f3c5f0a156473f97d56872b9637dc0458b4d | [
"MIT"
] | 5 | 2022-02-27T06:02:10.000Z | 2022-03-01T08:58:32.000Z | app/components/views/Home/constants.ts | GreenerDAO/klimadao | fd07f3c5f0a156473f97d56872b9637dc0458b4d | [
"MIT"
] | null | null | null | app/components/views/Home/constants.ts | GreenerDAO/klimadao | fd07f3c5f0a156473f97d56872b9637dc0458b4d | [
"MIT"
] | 1 | 2022-01-06T02:56:23.000Z | 2022-01-06T02:56:23.000Z | export type LoadWeb3Modal = () => Promise<void>;
interface Link {
to: string;
show: boolean;
text: string;
dataActive: boolean;
}
export interface NavProps {
links: Link[];
chainId: number | undefined;
}
export interface WalletProps {
address?: string;
isMobile?: boolean;
isConnected: boolean;
loadWeb3Modal: LoadWeb3Modal;
disconnect: () => Promise<void>;
}
export interface MobileMenuProps {
links: Link[];
isConnected: boolean;
loadWeb3Modal: LoadWeb3Modal;
disconnect: () => Promise<void>;
}
export const generateLinks = ({
path,
showPklimaButton,
showRedeemButton,
}: {
path: string;
showPklimaButton: boolean;
showRedeemButton: boolean;
}) => [
{
to: "/redeem",
show: showRedeemButton,
text: "REDEEM",
dataActive: path === "/redeem",
},
{
to: "/stake",
show: true,
text: "STAKE",
dataActive: path === "/stake",
},
{
to: "/wrap",
show: true,
text: "WRAP",
dataActive: path === "/wrap",
},
{
to: "/bonds",
show: true,
text: "BOND",
dataActive: path.includes("/bonds"),
},
{
to: "/info",
show: true,
text: "INFO",
dataActive: path === "/info",
},
{
to: "/pklima",
show: showPklimaButton,
text: "pKLIMA",
dataActive: path === "/pklima",
},
];
| 17.276316 | 48 | 0.590251 | 70 | 1 | 0 | 1 | 1 | 15 | 0 | 0 | 15 | 5 | 0 | 38 | 401 | 0.004988 | 0.002494 | 0.037406 | 0.012469 | 0 | 0 | 0.833333 | 0.209032 | export type LoadWeb3Modal = () => Promise<void>;
interface Link {
to;
show;
text;
dataActive;
}
export interface NavProps {
links;
chainId;
}
export interface WalletProps {
address?;
isMobile?;
isConnected;
loadWeb3Modal;
disconnect;
}
export interface MobileMenuProps {
links;
isConnected;
loadWeb3Modal;
disconnect;
}
export const generateLinks = ({
path,
showPklimaButton,
showRedeemButton,
}) => [
{
to: "/redeem",
show: showRedeemButton,
text: "REDEEM",
dataActive: path === "/redeem",
},
{
to: "/stake",
show: true,
text: "STAKE",
dataActive: path === "/stake",
},
{
to: "/wrap",
show: true,
text: "WRAP",
dataActive: path === "/wrap",
},
{
to: "/bonds",
show: true,
text: "BOND",
dataActive: path.includes("/bonds"),
},
{
to: "/info",
show: true,
text: "INFO",
dataActive: path === "/info",
},
{
to: "/pklima",
show: showPklimaButton,
text: "pKLIMA",
dataActive: path === "/pklima",
},
];
|
d6801760582bbe439dc0562cd1686c5fa2391c2f | 3,383 | ts | TypeScript | src/augments/date.ts | electrovir/augment-vir | c6c4f535f23329850d31188a036559edd0f42096 | [
"MIT"
] | null | null | null | src/augments/date.ts | electrovir/augment-vir | c6c4f535f23329850d31188a036559edd0f42096 | [
"MIT"
] | 2 | 2022-03-18T21:45:00.000Z | 2022-03-23T04:13:34.000Z | src/augments/date.ts | electrovir/augment-vir | c6c4f535f23329850d31188a036559edd0f42096 | [
"MIT"
] | null | null | null | export const englishFullMonthNames = [
'january',
'february',
'march',
'april',
'may',
'june',
'july',
'august',
'september',
'october',
'november',
'december',
];
export const englishShortMonthNames = englishFullMonthNames.map((longMonthName) =>
longMonthName.slice(0, 3),
);
export class InvalidDateError extends Error {
public override readonly name = 'InvalidDateError';
}
/**
* @param slashFormatString String that should be of format "MM/DD/YY", "MM/DD/YYYY". When the year
* portion only contains 2 numbers ("MM/DD/YY") the century must be provided in the form of the
* yearPrefix input.
* @param yearPrefix String or number that is used to prefix slash format strings that only contain
* 2 digits ("MM/DD/YY"). If the year is entirely missing form the given slash format string, the
* year will default to year 00 of the given century. See test file for examples.
*/
export function createDateFromSlashFormat(
slashFormatString: string,
yearPrefix: number | string = '',
) {
const [
month,
day,
rawYearEnding = '',
] = slashFormatString.split('/');
if (!month || !day) {
throw new Error(`Unable to extract month or day from "${slashFormatString}"`);
}
const yearEnding =
rawYearEnding.length < 4 ? `${yearPrefix}${rawYearEnding.padStart(2, '0')}` : rawYearEnding;
const returnDate = createDateFromUtcIsoFormat(
`${yearEnding.padStart(4, '0')}-${month.padStart(2, '0')}-${day.padStart(2, '0')}`,
);
return returnDate;
}
/**
* @param commaFormatString Should be at string of the form "monthName dayNumber, fullYear" Example:
* "May 19, 2005"
* @param ignoreInvalidMonth Set to true to ignore invalid months
*/
export function createDateFromNamedCommaFormat(
commaFormatString: string,
ignoreInvalidMonth = false,
) {
const [
monthName,
dayNumber,
fullYear,
] = commaFormatString.replace(',', '').split(' ');
if (!monthName || !dayNumber || !fullYear) {
throw new InvalidDateError(
`Invalid ${createDateFromNamedCommaFormat.name} input: ${commaFormatString}`,
);
}
const longMonthIndex = englishFullMonthNames.indexOf(monthName.toLowerCase());
const shortMonthIndex = englishShortMonthNames.indexOf(monthName.toLowerCase());
let monthIndex = longMonthIndex === -1 ? shortMonthIndex : longMonthIndex;
if (monthIndex === -1) {
if (ignoreInvalidMonth) {
monthIndex = 4;
} else {
throw new InvalidDateError(`Month name ${monthName} was not found.`);
}
}
const returnDate = createDateFromUtcIsoFormat(
`${fullYear.padStart(4, '0')}-${String(monthIndex + 1).padStart(
2,
'0',
)}-${dayNumber.padStart(2, '0')}`,
);
return returnDate;
}
/**
* Converts an iso-formatted string to a UTC date object. The time is nulled out to all zeros.
*
* @param isoFormatString Should be a date in the format YYYY-MM-DD.
*/
export function createDateFromUtcIsoFormat(isoFormatString: string): Date {
const utcDate = new Date(isoFormatString + 'T00:00:00.000Z');
if (isNaN(Number(utcDate))) {
throw new InvalidDateError(`Invalid utc date formed from input "${isoFormatString}"`);
}
return utcDate;
}
| 30.477477 | 100 | 0.648241 | 78 | 4 | 0 | 6 | 11 | 1 | 1 | 0 | 5 | 1 | 0 | 11.75 | 906 | 0.011038 | 0.012141 | 0.001104 | 0.001104 | 0 | 0 | 0.227273 | 0.237289 | export const englishFullMonthNames = [
'january',
'february',
'march',
'april',
'may',
'june',
'july',
'august',
'september',
'october',
'november',
'december',
];
export const englishShortMonthNames = englishFullMonthNames.map((longMonthName) =>
longMonthName.slice(0, 3),
);
export class InvalidDateError extends Error {
public override readonly name = 'InvalidDateError';
}
/**
* @param slashFormatString String that should be of format "MM/DD/YY", "MM/DD/YYYY". When the year
* portion only contains 2 numbers ("MM/DD/YY") the century must be provided in the form of the
* yearPrefix input.
* @param yearPrefix String or number that is used to prefix slash format strings that only contain
* 2 digits ("MM/DD/YY"). If the year is entirely missing form the given slash format string, the
* year will default to year 00 of the given century. See test file for examples.
*/
export function createDateFromSlashFormat(
slashFormatString,
yearPrefix = '',
) {
const [
month,
day,
rawYearEnding = '',
] = slashFormatString.split('/');
if (!month || !day) {
throw new Error(`Unable to extract month or day from "${slashFormatString}"`);
}
const yearEnding =
rawYearEnding.length < 4 ? `${yearPrefix}${rawYearEnding.padStart(2, '0')}` : rawYearEnding;
const returnDate = createDateFromUtcIsoFormat(
`${yearEnding.padStart(4, '0')}-${month.padStart(2, '0')}-${day.padStart(2, '0')}`,
);
return returnDate;
}
/**
* @param commaFormatString Should be at string of the form "monthName dayNumber, fullYear" Example:
* "May 19, 2005"
* @param ignoreInvalidMonth Set to true to ignore invalid months
*/
export /* Example usages of 'createDateFromNamedCommaFormat' are shown below:
createDateFromNamedCommaFormat.name;
*/
function createDateFromNamedCommaFormat(
commaFormatString,
ignoreInvalidMonth = false,
) {
const [
monthName,
dayNumber,
fullYear,
] = commaFormatString.replace(',', '').split(' ');
if (!monthName || !dayNumber || !fullYear) {
throw new InvalidDateError(
`Invalid ${createDateFromNamedCommaFormat.name} input: ${commaFormatString}`,
);
}
const longMonthIndex = englishFullMonthNames.indexOf(monthName.toLowerCase());
const shortMonthIndex = englishShortMonthNames.indexOf(monthName.toLowerCase());
let monthIndex = longMonthIndex === -1 ? shortMonthIndex : longMonthIndex;
if (monthIndex === -1) {
if (ignoreInvalidMonth) {
monthIndex = 4;
} else {
throw new InvalidDateError(`Month name ${monthName} was not found.`);
}
}
const returnDate = createDateFromUtcIsoFormat(
`${fullYear.padStart(4, '0')}-${String(monthIndex + 1).padStart(
2,
'0',
)}-${dayNumber.padStart(2, '0')}`,
);
return returnDate;
}
/**
* Converts an iso-formatted string to a UTC date object. The time is nulled out to all zeros.
*
* @param isoFormatString Should be a date in the format YYYY-MM-DD.
*/
export /* Example usages of 'createDateFromUtcIsoFormat' are shown below:
createDateFromUtcIsoFormat(`${yearEnding.padStart(4, '0')}-${month.padStart(2, '0')}-${day.padStart(2, '0')}`);
createDateFromUtcIsoFormat(`${fullYear.padStart(4, '0')}-${String(monthIndex + 1).padStart(2, '0')}-${dayNumber.padStart(2, '0')}`);
*/
function createDateFromUtcIsoFormat(isoFormatString) {
const utcDate = new Date(isoFormatString + 'T00:00:00.000Z');
if (isNaN(Number(utcDate))) {
throw new InvalidDateError(`Invalid utc date formed from input "${isoFormatString}"`);
}
return utcDate;
}
|
d6886bab5b6a7e6f1b7590f82df23c1c47eb2d00 | 2,487 | ts | TypeScript | package/src/animation/TimelineInfo/functions/normalize.ts | mlynchdev/react-native-skia | 65a3c6676eab6ebe21bdd32d5ced838fc16649f0 | [
"MIT"
] | 2 | 2022-01-06T19:29:21.000Z | 2022-03-12T09:45:13.000Z | package/src/animation/TimelineInfo/functions/normalize.ts | mlynchdev/react-native-skia | 65a3c6676eab6ebe21bdd32d5ced838fc16649f0 | [
"MIT"
] | null | null | null | package/src/animation/TimelineInfo/functions/normalize.ts | mlynchdev/react-native-skia | 65a3c6676eab6ebe21bdd32d5ced838fc16649f0 | [
"MIT"
] | null | null | null | /* eslint-disable no-nested-ternary */
/**
* @description Returns a normalize function that calculates normalized value
* @param total Total duration of parent timeline
* @param offset Offset for timeline (for first repeat)
* @param duration Duration for timeline (for 1 repeat)
* @param repeat Number of repeats for timeline (1 = no repeat, 2 = run once, repeat once)
* @param repeatDelay Repeat delay - used to delay staggered repeats
* @param yoyo True if every second repeat should run in reverse
* @returns Returns a function that can be used to interpolate from time 0..1 and
* the timeline with the offset, duration, repeat, repeatDelay and yoyo parameters.
*/
export const normalizer = (
time: number,
params: {
total: number;
duration: number;
offset?: number;
repeat?: number;
repeatDelay?: number;
yoyo?: boolean;
}
) => {
const {
total,
duration,
offset = 0,
repeat = 1,
repeatDelay = 0,
yoyo = false,
} = params;
// Verify offset
if (offset + duration < 0 || offset + duration > total) {
throw Error(
"Offset + duration should be between zero and parent duration" +
` (${total}) - got offset: ${offset} and duration: ${duration}`
);
}
const calculdatedDuration =
duration * repeat + Math.max(0, repeat - 1) * repeatDelay;
// Verify Duration
if (offset + calculdatedDuration > total) {
throw Error(
`Duration should be between 0 and ${total} - got ${
offset + calculdatedDuration
}`
);
}
// Total
const tltotal = offset + calculdatedDuration;
// calc progress without offset
const p = (-offset + time) * (1 / duration);
// Calc end
if (p < 0) {
// We just return values below zero, knowing that these will
// not be used for animation
return p === Infinity ? 0 : p;
}
// else if (time === tltotal) {
// // last repeat, return 1 (not zero, which is what each repeat would return)
// return 1;
// }
else if (time > tltotal) {
// more than last repeat, we'll just return a number above 1
return p === Infinity ? 1 : p;
} else {
// in repeat or regular - with/without yoyo
const y =
time === 0
? 1
: Math.ceil((-offset + time) * (1 / (duration + repeatDelay))) % 2;
const r =
p === 0
? 0
: p % 1 === 0
? 1
: p % ((duration + repeatDelay) * (1 / duration));
return yoyo && p > 0 && y === 0 ? 1 - r : r;
}
};
| 28.586207 | 90 | 0.605147 | 55 | 1 | 0 | 2 | 7 | 0 | 0 | 0 | 7 | 0 | 0 | 43 | 677 | 0.004431 | 0.01034 | 0 | 0 | 0 | 0 | 0.7 | 0.21344 | /* eslint-disable no-nested-ternary */
/**
* @description Returns a normalize function that calculates normalized value
* @param total Total duration of parent timeline
* @param offset Offset for timeline (for first repeat)
* @param duration Duration for timeline (for 1 repeat)
* @param repeat Number of repeats for timeline (1 = no repeat, 2 = run once, repeat once)
* @param repeatDelay Repeat delay - used to delay staggered repeats
* @param yoyo True if every second repeat should run in reverse
* @returns Returns a function that can be used to interpolate from time 0..1 and
* the timeline with the offset, duration, repeat, repeatDelay and yoyo parameters.
*/
export const normalizer = (
time,
params
) => {
const {
total,
duration,
offset = 0,
repeat = 1,
repeatDelay = 0,
yoyo = false,
} = params;
// Verify offset
if (offset + duration < 0 || offset + duration > total) {
throw Error(
"Offset + duration should be between zero and parent duration" +
` (${total}) - got offset: ${offset} and duration: ${duration}`
);
}
const calculdatedDuration =
duration * repeat + Math.max(0, repeat - 1) * repeatDelay;
// Verify Duration
if (offset + calculdatedDuration > total) {
throw Error(
`Duration should be between 0 and ${total} - got ${
offset + calculdatedDuration
}`
);
}
// Total
const tltotal = offset + calculdatedDuration;
// calc progress without offset
const p = (-offset + time) * (1 / duration);
// Calc end
if (p < 0) {
// We just return values below zero, knowing that these will
// not be used for animation
return p === Infinity ? 0 : p;
}
// else if (time === tltotal) {
// // last repeat, return 1 (not zero, which is what each repeat would return)
// return 1;
// }
else if (time > tltotal) {
// more than last repeat, we'll just return a number above 1
return p === Infinity ? 1 : p;
} else {
// in repeat or regular - with/without yoyo
const y =
time === 0
? 1
: Math.ceil((-offset + time) * (1 / (duration + repeatDelay))) % 2;
const r =
p === 0
? 0
: p % 1 === 0
? 1
: p % ((duration + repeatDelay) * (1 / duration));
return yoyo && p > 0 && y === 0 ? 1 - r : r;
}
};
|
d6cde2bf2631bee80aa9d3e7028775accf4f72df | 4,481 | ts | TypeScript | RecommenederSystem/api/controllers/ArticuloController.ts | JonathanPachacama/AplicacionFer | 3a606e22b7c6a8d777e251f695e8dd6d12a54352 | [
"MIT"
] | null | null | null | RecommenederSystem/api/controllers/ArticuloController.ts | JonathanPachacama/AplicacionFer | 3a606e22b7c6a8d777e251f695e8dd6d12a54352 | [
"MIT"
] | 1 | 2022-02-10T19:23:59.000Z | 2022-02-10T19:23:59.000Z | RecommenederSystem/api/controllers/ArticuloController.ts | JonathanPachacama/AplicacionFer | 3a606e22b7c6a8d777e251f695e8dd6d12a54352 | [
"MIT"
] | null | null | null | /**
* Created by CEDIA on 24/07/2017.
*/
declare var module;
declare var sails;
declare var Articulo;
declare var File;
// localhost:1337/Articulo/metodos
module.exports = {
eliminarArticulo: (req, res) => {
let params = req.allParams();
sails.log.info("Parametros", params);
if (req.method == "POST" && params.id) {
Articulo.destroy({
id: params.id
}).exec((err, articuloBorrado) => {
if (err) return res.serverError(err);
return res.redirect("/bibliotecaUser")
})
} else {
return res.badRequest();
}
},
VerArticulo:(req,res)=>{
let parametros = req.allParams();
if(parametros.id){
Articulo.findOne({
id:parametros.id
})
.exec((err,articuloEditado)=>{
if(err) return res.serverError(err);
if(articuloEditado){
//Si encontro
File.find()
.where({
fkIdArticulo:parametros.id
}).exec(
(error,File)=>{
if(error){
return res.serverError(error);
}
if (!File) {
return res.view('editarArticulo',{
articulos:articuloEditado
})
}
return res.view('editarArticulo',{
articulos:articuloEditado,
File:File
})
}
)
}else{
//No encontro
return res.redirect('/biblioteca')
}
})
}else{
return res.redirect('/biblioteca')
}
},
editanota:(req,res)=>{
let parametros = req.allParams();
if(parametros.title&&
parametros.country&&
parametros.notas&&
parametros.number&&
parametros.volume&&
parametros.year&&
parametros.journal&&
parametros.editorial&&
parametros.abstract&&
parametros.issns&&
parametros.doi&&
parametros.language&&
parametros.category&&
parametros.pages&&
parametros.idArticulo){
Articulo.update({
id:parametros.idArticulo
},{
title:parametros.title,
country:parametros.country,
notas:parametros.notas,
number: parametros.number,
volume: parametros.volume,
year: parametros.year,
journal: parametros. journal,
editorial: parametros. editorial,
abstract: parametros.abstract,
issns:parametros.issns,
doi:parametros.doi,
language:parametros.language,
category:parametros.category,
pages: parametros.pages,
})
.exec((err,Editado)=>{
if(err) return res.serverError(err);
if(Editado){
//Si encontro
return res.redirect('/VerArticulo?id=' + parametros.idArticulo)
}else{
//No encontro
return res.notFound()
}
})
}else{
return res.badRequest()
}
},
editarArticulo:(req,res)=>{
let parametros = req.allParams();
if(parametros.idArticulo&&
parametros.title&&
// parametros.country&&
parametros.number&&
parametros.volume&&
parametros.year&&
parametros.journal&&
// parametros.editorial&&
//parametros.abstract&&
//parametros.issns&&
// parametros.language&&
parametros.keywords&&
//parametros.category&&
parametros.pages
//parametros.notas
){
Articulo.update({
id:parametros.idArticulo
},{
title:parametros.title,
country:parametros.country,
number: parametros.number,
volume: parametros.volume,
year: parametros.year,
journal: parametros. journal,
editorial: parametros. editorial,
abstract: parametros.abstract,
issns:parametros.issns,
doi:parametros.doi,
language:parametros.language,
keywords:parametros.keywords,
category:parametros.category,
pages: parametros.pages,
notas: parametros.notas,
})
.exec((err,Editado)=>{
if(err) return res.serverError(err);
if(Editado){
//Si encontro
return res.redirect('/VerArticulo?id=' + parametros.idArticulo)
}else{
//No encontro
return res.notFound()
}
})
}else{
return res.badRequest()
}
}
}
| 23.460733 | 75 | 0.540281 | 145 | 9 | 0 | 18 | 8 | 0 | 0 | 0 | 0 | 0 | 0 | 20.111111 | 1,069 | 0.025257 | 0.007484 | 0 | 0 | 0 | 0 | 0 | 0.253649 | /**
* Created by CEDIA on 24/07/2017.
*/
declare var module;
declare var sails;
declare var Articulo;
declare var File;
// localhost:1337/Articulo/metodos
module.exports = {
eliminarArticulo: (req, res) => {
let params = req.allParams();
sails.log.info("Parametros", params);
if (req.method == "POST" && params.id) {
Articulo.destroy({
id: params.id
}).exec((err, articuloBorrado) => {
if (err) return res.serverError(err);
return res.redirect("/bibliotecaUser")
})
} else {
return res.badRequest();
}
},
VerArticulo:(req,res)=>{
let parametros = req.allParams();
if(parametros.id){
Articulo.findOne({
id:parametros.id
})
.exec((err,articuloEditado)=>{
if(err) return res.serverError(err);
if(articuloEditado){
//Si encontro
File.find()
.where({
fkIdArticulo:parametros.id
}).exec(
(error,File)=>{
if(error){
return res.serverError(error);
}
if (!File) {
return res.view('editarArticulo',{
articulos:articuloEditado
})
}
return res.view('editarArticulo',{
articulos:articuloEditado,
File:File
})
}
)
}else{
//No encontro
return res.redirect('/biblioteca')
}
})
}else{
return res.redirect('/biblioteca')
}
},
editanota:(req,res)=>{
let parametros = req.allParams();
if(parametros.title&&
parametros.country&&
parametros.notas&&
parametros.number&&
parametros.volume&&
parametros.year&&
parametros.journal&&
parametros.editorial&&
parametros.abstract&&
parametros.issns&&
parametros.doi&&
parametros.language&&
parametros.category&&
parametros.pages&&
parametros.idArticulo){
Articulo.update({
id:parametros.idArticulo
},{
title:parametros.title,
country:parametros.country,
notas:parametros.notas,
number: parametros.number,
volume: parametros.volume,
year: parametros.year,
journal: parametros. journal,
editorial: parametros. editorial,
abstract: parametros.abstract,
issns:parametros.issns,
doi:parametros.doi,
language:parametros.language,
category:parametros.category,
pages: parametros.pages,
})
.exec((err,Editado)=>{
if(err) return res.serverError(err);
if(Editado){
//Si encontro
return res.redirect('/VerArticulo?id=' + parametros.idArticulo)
}else{
//No encontro
return res.notFound()
}
})
}else{
return res.badRequest()
}
},
editarArticulo:(req,res)=>{
let parametros = req.allParams();
if(parametros.idArticulo&&
parametros.title&&
// parametros.country&&
parametros.number&&
parametros.volume&&
parametros.year&&
parametros.journal&&
// parametros.editorial&&
//parametros.abstract&&
//parametros.issns&&
// parametros.language&&
parametros.keywords&&
//parametros.category&&
parametros.pages
//parametros.notas
){
Articulo.update({
id:parametros.idArticulo
},{
title:parametros.title,
country:parametros.country,
number: parametros.number,
volume: parametros.volume,
year: parametros.year,
journal: parametros. journal,
editorial: parametros. editorial,
abstract: parametros.abstract,
issns:parametros.issns,
doi:parametros.doi,
language:parametros.language,
keywords:parametros.keywords,
category:parametros.category,
pages: parametros.pages,
notas: parametros.notas,
})
.exec((err,Editado)=>{
if(err) return res.serverError(err);
if(Editado){
//Si encontro
return res.redirect('/VerArticulo?id=' + parametros.idArticulo)
}else{
//No encontro
return res.notFound()
}
})
}else{
return res.badRequest()
}
}
}
|
f3813017e9bb14bf831177d63f99b8ab50b44ad4 | 2,616 | ts | TypeScript | src/omsorgsdager-kalkulator/types/ResultView.ts | navikt/omsorgsdager-kalkulator | 728188359e19be434465a48a56b221aa71726a80 | [
"MIT"
] | null | null | null | src/omsorgsdager-kalkulator/types/ResultView.ts | navikt/omsorgsdager-kalkulator | 728188359e19be434465a48a56b221aa71726a80 | [
"MIT"
] | 1 | 2022-02-28T14:05:30.000Z | 2022-02-28T14:05:30.000Z | src/omsorgsdager-kalkulator/types/ResultView.ts | navikt/omsorgsdager-kalkulator | 728188359e19be434465a48a56b221aa71726a80 | [
"MIT"
] | null | null | null | export type Empty = {
readonly _tag: 'Empty';
};
export type BeregnButton = {
readonly _tag: 'BeregnButton';
};
export type BeregnButtonAndErrorSummary<E> = {
readonly _tag: 'BeregnButtonAndErrorSummary';
readonly errors: E;
};
export type NoValidChildrenOrange = {
readonly _tag: 'NoValidChildrenOrange';
};
export type ResultBox<A> = {
readonly _tag: 'ResultBox';
readonly result: A;
};
export type ResultView<E, A> =
| Empty
| BeregnButton
| BeregnButtonAndErrorSummary<E>
| NoValidChildrenOrange
| ResultBox<A>;
// constructors
export const empty: ResultView<never, never> = {
_tag: 'Empty',
};
export const beregnButton: ResultView<never, never> = {
_tag: 'BeregnButton',
};
export const beregnButtonAndErrorSummary = <E>(errors: E): ResultView<E, never> => ({
_tag: 'BeregnButtonAndErrorSummary',
errors,
});
export const noValidChildrenOrange: ResultView<never, never> = {
_tag: 'NoValidChildrenOrange',
};
export const resultBox = <A>(result: A): ResultView<never, A> => ({
_tag: 'ResultBox',
result,
});
// filters
export const isEmpty = (data: ResultView<unknown, unknown>): data is Empty => data._tag === 'Empty';
export const isBeregnButton = (data: ResultView<unknown, unknown>): data is BeregnButton =>
data._tag === 'BeregnButton';
export const isBeregnButtonAndErrorSummary = <E>(
data: ResultView<E, unknown>
): data is BeregnButtonAndErrorSummary<E> => data._tag === 'BeregnButtonAndErrorSummary';
export const isNoValidChildrenOrange = (data: ResultView<unknown, unknown>): data is NoValidChildrenOrange =>
data._tag === 'NoValidChildrenOrange';
export const isResultBox = <A>(data: ResultView<unknown, A>): data is ResultBox<A> => data._tag === 'ResultBox';
// fold
export const caseResultViewOf =
<E, A, B>(
empty: () => B,
beregnButton: () => B,
beregnButtonAndErrorSummary: (errors: E) => B,
noValidChildrenOrange: () => B,
resultBox: (result: A) => B
) =>
(resultView: ResultView<E, A>): B => {
switch (resultView._tag) {
case 'Empty': {
return empty();
}
case 'BeregnButton': {
return beregnButton();
}
case 'BeregnButtonAndErrorSummary': {
return beregnButtonAndErrorSummary(resultView.errors);
}
case 'NoValidChildrenOrange': {
return noValidChildrenOrange();
}
case 'ResultBox': {
return resultBox(resultView.result);
}
}
};
| 31.518072 | 112 | 0.626529 | 76 | 9 | 0 | 13 | 11 | 7 | 2 | 0 | 16 | 6 | 0 | 5.333333 | 733 | 0.030014 | 0.015007 | 0.00955 | 0.008186 | 0 | 0 | 0.4 | 0.30251 | export type Empty = {
readonly _tag;
};
export type BeregnButton = {
readonly _tag;
};
export type BeregnButtonAndErrorSummary<E> = {
readonly _tag;
readonly errors;
};
export type NoValidChildrenOrange = {
readonly _tag;
};
export type ResultBox<A> = {
readonly _tag;
readonly result;
};
export type ResultView<E, A> =
| Empty
| BeregnButton
| BeregnButtonAndErrorSummary<E>
| NoValidChildrenOrange
| ResultBox<A>;
// constructors
export const empty = {
_tag: 'Empty',
};
export const beregnButton = {
_tag: 'BeregnButton',
};
export /* Example usages of 'beregnButtonAndErrorSummary' are shown below:
;
beregnButtonAndErrorSummary(resultView.errors);
*/
const beregnButtonAndErrorSummary = <E>(errors) => ({
_tag: 'BeregnButtonAndErrorSummary',
errors,
});
export const noValidChildrenOrange = {
_tag: 'NoValidChildrenOrange',
};
export /* Example usages of 'resultBox' are shown below:
;
resultBox(resultView.result);
*/
const resultBox = <A>(result) => ({
_tag: 'ResultBox',
result,
});
// filters
export const isEmpty = (data): data is Empty => data._tag === 'Empty';
export const isBeregnButton = (data): data is BeregnButton =>
data._tag === 'BeregnButton';
export const isBeregnButtonAndErrorSummary = <E>(
data
): data is BeregnButtonAndErrorSummary<E> => data._tag === 'BeregnButtonAndErrorSummary';
export const isNoValidChildrenOrange = (data): data is NoValidChildrenOrange =>
data._tag === 'NoValidChildrenOrange';
export const isResultBox = <A>(data): data is ResultBox<A> => data._tag === 'ResultBox';
// fold
export const caseResultViewOf =
<E, A, B>(
empty,
beregnButton,
beregnButtonAndErrorSummary,
noValidChildrenOrange,
resultBox
) =>
(resultView) => {
switch (resultView._tag) {
case 'Empty': {
return empty();
}
case 'BeregnButton': {
return beregnButton();
}
case 'BeregnButtonAndErrorSummary': {
return beregnButtonAndErrorSummary(resultView.errors);
}
case 'NoValidChildrenOrange': {
return noValidChildrenOrange();
}
case 'ResultBox': {
return resultBox(resultView.result);
}
}
};
|
f9e8359ed27827947bcf0cb5c43e80042de13cca | 2,455 | ts | TypeScript | 2016/04_2/solution.ts | budavariam/advent_of_code | 0903bcbb0df46371b6a340ca2be007dce6470c66 | [
"MIT"
] | null | null | null | 2016/04_2/solution.ts | budavariam/advent_of_code | 0903bcbb0df46371b6a340ca2be007dce6470c66 | [
"MIT"
] | null | null | null | 2016/04_2/solution.ts | budavariam/advent_of_code | 0903bcbb0df46371b6a340ca2be007dce6470c66 | [
"MIT"
] | 1 | 2022-02-11T13:14:50.000Z | 2022-02-11T13:14:50.000Z | export function solution(input: string[]) {
return "" + input
.map(parseInput)
.filter((room) => room.isNorthPoleObject())
.map((room) => room.sectorID);
}
const REGEXP = /([a-z\-]+)-(\d+)(?:\[(\w+)\])?/;
function parseInput(line: string): Room {
const matches = line.match(REGEXP);
if (matches) {
const name = matches[1];
const sectorID = parseInt(matches[2], 10);
const checksum = matches[3];
return new Room(name, sectorID, checksum);
} else {
return new Room("", 0, "filterthis");
}
}
class Room {
private histogram = {};
private topfiveordered = "";
private decipheredName = "";
constructor(name: string, public readonly sectorID: number, private checksum: string) {
this.histogram = this.calcHistogram(name);
this.topfiveordered = this.calcChecksum(this.histogram);
this.decipheredName = this.decipher(name, sectorID);
}
public toString() {
return this.decipheredName;
}
public isValid() {
return this.topfiveordered === this.checksum;
}
public isNorthPoleObject() {
return this.decipheredName.indexOf("north") > -1;
}
private decipher(text: string, count: number) {
const lowerCaseShift = "a".charCodeAt(0); // 97
return String.fromCharCode(...text.split("").map((char) => {
let shiftedChar = char.charCodeAt(0);
if (shiftedChar === 45) {
shiftedChar = 32; // ' '.charCodeAt(0);
} else {
shiftedChar -= lowerCaseShift;
shiftedChar += count;
shiftedChar %= 26;
shiftedChar += lowerCaseShift;
}
return shiftedChar;
}));
}
private calcHistogram(name: string): any {
const hist: any = {};
name.split("").forEach((character) => {
if (character in hist) {
hist[character] += 1;
} else {
hist[character] = 1;
}
});
return hist;
}
private calcChecksum(histogram: any): string {
return Object.keys(histogram).sort((left, right) => {
if (((histogram[left] === histogram[right]) && (left > right)) || (histogram[left] < histogram[right])) {
return 1;
} else {
return -1;
}
}).join("").slice(0, 5);
}
}
| 29.939024 | 117 | 0.530346 | 72 | 14 | 0 | 15 | 8 | 3 | 4 | 3 | 9 | 1 | 0 | 5 | 609 | 0.047619 | 0.013136 | 0.004926 | 0.001642 | 0 | 0.075 | 0.225 | 0.326591 | export function solution(input) {
return "" + input
.map(parseInput)
.filter((room) => room.isNorthPoleObject())
.map((room) => room.sectorID);
}
const REGEXP = /([a-z\-]+)-(\d+)(?:\[(\w+)\])?/;
/* Example usages of 'parseInput' are shown below:
"" + input
.map(parseInput)
.filter((room) => room.isNorthPoleObject())
.map((room) => room.sectorID);
*/
function parseInput(line) {
const matches = line.match(REGEXP);
if (matches) {
const name = matches[1];
const sectorID = parseInt(matches[2], 10);
const checksum = matches[3];
return new Room(name, sectorID, checksum);
} else {
return new Room("", 0, "filterthis");
}
}
class Room {
private histogram = {};
private topfiveordered = "";
private decipheredName = "";
constructor(name, public readonly sectorID, private checksum) {
this.histogram = this.calcHistogram(name);
this.topfiveordered = this.calcChecksum(this.histogram);
this.decipheredName = this.decipher(name, sectorID);
}
public toString() {
return this.decipheredName;
}
public isValid() {
return this.topfiveordered === this.checksum;
}
public isNorthPoleObject() {
return this.decipheredName.indexOf("north") > -1;
}
private decipher(text, count) {
const lowerCaseShift = "a".charCodeAt(0); // 97
return String.fromCharCode(...text.split("").map((char) => {
let shiftedChar = char.charCodeAt(0);
if (shiftedChar === 45) {
shiftedChar = 32; // ' '.charCodeAt(0);
} else {
shiftedChar -= lowerCaseShift;
shiftedChar += count;
shiftedChar %= 26;
shiftedChar += lowerCaseShift;
}
return shiftedChar;
}));
}
private calcHistogram(name) {
const hist = {};
name.split("").forEach((character) => {
if (character in hist) {
hist[character] += 1;
} else {
hist[character] = 1;
}
});
return hist;
}
private calcChecksum(histogram) {
return Object.keys(histogram).sort((left, right) => {
if (((histogram[left] === histogram[right]) && (left > right)) || (histogram[left] < histogram[right])) {
return 1;
} else {
return -1;
}
}).join("").slice(0, 5);
}
}
|
f9f62e4aba0eb7e1dbd700d9f9b7d3ae6f796b52 | 2,358 | ts | TypeScript | src/models/WebApiIndex.ts | api-client/core | aa157d09b39efa77d49f2d425e7b37828abe0c5b | [
"Apache-2.0"
] | null | null | null | src/models/WebApiIndex.ts | api-client/core | aa157d09b39efa77d49f2d425e7b37828abe0c5b | [
"Apache-2.0"
] | 1 | 2022-02-14T00:01:04.000Z | 2022-02-14T00:04:07.000Z | src/models/WebApiIndex.ts | advanced-rest-client/core | 2efb946f786d8b46e7131c62e0011f6e090ddec3 | [
"Apache-2.0"
] | null | null | null | export const Kind = 'Core#WebApiIndex';
/**
* @deprecated This was used in the old version of ARC.
*/
export interface ILegacyWebApiIndex {
/**
* API title
*/
title: string;
/**
* API media type
* @deprecated This has been renamed to `vendor`.
*/
type: string;
/**
* API order on the list
*/
order: number;
/**
* List of version names stored with this API.
*/
versions: string[];
/**
* The latest added version name.
*/
latest: string;
}
export interface IWebApiIndex {
kind: typeof Kind;
/**
* API title
*/
title: string;
/**
* List of version names stored with this API.
*/
versions: string[];
/**
* The latest added version name.
*/
latest: string;
/**
* The API vendor. E.g. RAML 1.0, OAS 3.0, ASYNC 2.0, ...
*/
vendor: string;
}
export class WebApiIndex {
kind = Kind;
/**
* API title
*/
title = '';
/**
* List of version names stored with this API.
*/
versions: string[] = [];
/**
* The latest added version name.
*/
latest = '';
/**
* The API vendor. E.g. RAML 1.0, OAS 3.0, ASYNC 2.0, ...
*/
vendor = '';
static isLegacy(api: unknown): boolean {
const legacy = api as ILegacyWebApiIndex;
return !!legacy.type;
}
static fromLegacy(api: ILegacyWebApiIndex): WebApiIndex {
const { title, type, versions=[], latest } = api;
const init: IWebApiIndex = {
kind: Kind,
title,
versions,
latest,
vendor: type,
};
return new WebApiIndex(init);
}
constructor(input?: string|IWebApiIndex) {
let init: IWebApiIndex;
if (typeof input === 'string') {
init = JSON.parse(input);
} else if (typeof input === 'object') {
init = input;
} else {
init = {
kind: Kind,
latest: '',
title: '',
vendor: '',
versions: [],
};
}
this.new(init);
}
new(init: IWebApiIndex): void {
const { latest='', title='', vendor='', versions=[] } = init;
this.latest = latest;
this.versions = versions;
this.title = title;
this.vendor = vendor;
}
toJSON(): IWebApiIndex {
const result: IWebApiIndex = {
kind: Kind,
latest: this.latest,
versions: this.versions,
title: this.title,
vendor: this.vendor,
};
return result;
}
}
| 19.170732 | 65 | 0.556404 | 71 | 5 | 0 | 4 | 7 | 15 | 1 | 0 | 14 | 3 | 3 | 7.8 | 671 | 0.013413 | 0.010432 | 0.022355 | 0.004471 | 0.004471 | 0 | 0.451613 | 0.241718 | export const Kind = 'Core#WebApiIndex';
/**
* @deprecated This was used in the old version of ARC.
*/
export interface ILegacyWebApiIndex {
/**
* API title
*/
title;
/**
* API media type
* @deprecated This has been renamed to `vendor`.
*/
type;
/**
* API order on the list
*/
order;
/**
* List of version names stored with this API.
*/
versions;
/**
* The latest added version name.
*/
latest;
}
export interface IWebApiIndex {
kind;
/**
* API title
*/
title;
/**
* List of version names stored with this API.
*/
versions;
/**
* The latest added version name.
*/
latest;
/**
* The API vendor. E.g. RAML 1.0, OAS 3.0, ASYNC 2.0, ...
*/
vendor;
}
export class WebApiIndex {
kind = Kind;
/**
* API title
*/
title = '';
/**
* List of version names stored with this API.
*/
versions = [];
/**
* The latest added version name.
*/
latest = '';
/**
* The API vendor. E.g. RAML 1.0, OAS 3.0, ASYNC 2.0, ...
*/
vendor = '';
static isLegacy(api) {
const legacy = api as ILegacyWebApiIndex;
return !!legacy.type;
}
static fromLegacy(api) {
const { title, type, versions=[], latest } = api;
const init = {
kind: Kind,
title,
versions,
latest,
vendor: type,
};
return new WebApiIndex(init);
}
constructor(input?) {
let init;
if (typeof input === 'string') {
init = JSON.parse(input);
} else if (typeof input === 'object') {
init = input;
} else {
init = {
kind: Kind,
latest: '',
title: '',
vendor: '',
versions: [],
};
}
this.new(init);
}
new(init) {
const { latest='', title='', vendor='', versions=[] } = init;
this.latest = latest;
this.versions = versions;
this.title = title;
this.vendor = vendor;
}
toJSON() {
const result = {
kind: Kind,
latest: this.latest,
versions: this.versions,
title: this.title,
vendor: this.vendor,
};
return result;
}
}
|
0016b0c611866cc5409de79ec34b296f2e344a01 | 2,209 | ts | TypeScript | src/dataViz/Utils.ts | cid-harvard/react-d3-fast-charts | f0dbca7e53d9584c1089b410d5759bdc0c9d16da | [
"MIT"
] | 1 | 2022-03-25T07:02:16.000Z | 2022-03-25T07:02:16.000Z | src/dataViz/Utils.ts | cid-harvard/react-fast-charts | 3bf880782aec6a68b22b38e3c9b43dbd73a211cc | [
"MIT"
] | null | null | null | src/dataViz/Utils.ts | cid-harvard/react-fast-charts | 3bf880782aec6a68b22b38e3c9b43dbd73a211cc | [
"MIT"
] | null | null | null | export const baseColor = '#333333'; // dark gray/black color for text
export const secondaryFont = "'OfficeCodeProWeb', monospace";
export const tertiaryColor = '#f3f3f3'; // really light gray color for use as a hover background color on cards
export const defaultPaletteColors = [
'#003f5c',
'#2f4b7c',
'#665191',
'#a05195',
'#d45087',
'#f95d6a',
'#ff7c43',
'#ffa600',
'#ffa600',
'#c1ab00',
'#86a927',
'#4fa049',
'#019463',
'#008575',
'#00747a',
'#166273',
];
export const defaultDivergentColors = [
'#00876c',
'#8cbcac',
'#f1f1f1',
'#ec9c9d',
'#d43d51',
];
export const defaultCoolChloropleth = [
'#004c6d',
'#326988',
'#5487a5',
'#76a6c2',
'#98c7e0',
'#bbe8ff',
];
export const defaultHotChloropleth = [
'#ff7b00',
'#fd9936',
'#fcb45e',
'#fbcc88',
'#fce2b4',
'#fff6e2',
];
const ranges = [
{ divider: 1e18 , suffix: 'E' },
{ divider: 1e15 , suffix: 'P' },
{ divider: 1e12 , suffix: 'T' },
{ divider: 1e9 , suffix: 'B' },
{ divider: 1e6 , suffix: 'M' },
{ divider: 1e3 , suffix: 'k' },
];
export const formatNumber = (n: number) => {
for (const range of ranges) {
if (n >= range.divider) {
return parseFloat((n / range.divider).toFixed(2)).toString() + range.suffix;
}
}
return n.toString();
};
export function adaptLabelFontSize(d: any) {
// var xPadding, diameter, labelAvailableWidth, labelWidth;
const xPadding = 8;
const diameter = 2 * d.r;
const labelAvailableWidth = diameter - xPadding;
// @ts-ignore
const labelWidth = this.getComputedTextLength();
// There is enough space for the label so leave it as is.
if (labelWidth < labelAvailableWidth) {
return null;
}
/*
* The meaning of the ratio between labelAvailableWidth and labelWidth equaling 1 is that
* the label is taking up exactly its available space.
* With the result as `1em` the font remains the same.
*
* The meaning of the ratio between labelAvailableWidth and labelWidth equaling 0.5 is that
* the label is taking up twice its available space.
* With the result as `0.5em` the font will change to half its original size.
*/
return (labelAvailableWidth / labelWidth) + 'em';
}
| 23.5 | 111 | 0.640561 | 70 | 2 | 0 | 2 | 13 | 0 | 0 | 1 | 1 | 0 | 0 | 7 | 798 | 0.005013 | 0.016291 | 0 | 0 | 0 | 0.058824 | 0.058824 | 0.233966 | export const baseColor = '#333333'; // dark gray/black color for text
export const secondaryFont = "'OfficeCodeProWeb', monospace";
export const tertiaryColor = '#f3f3f3'; // really light gray color for use as a hover background color on cards
export const defaultPaletteColors = [
'#003f5c',
'#2f4b7c',
'#665191',
'#a05195',
'#d45087',
'#f95d6a',
'#ff7c43',
'#ffa600',
'#ffa600',
'#c1ab00',
'#86a927',
'#4fa049',
'#019463',
'#008575',
'#00747a',
'#166273',
];
export const defaultDivergentColors = [
'#00876c',
'#8cbcac',
'#f1f1f1',
'#ec9c9d',
'#d43d51',
];
export const defaultCoolChloropleth = [
'#004c6d',
'#326988',
'#5487a5',
'#76a6c2',
'#98c7e0',
'#bbe8ff',
];
export const defaultHotChloropleth = [
'#ff7b00',
'#fd9936',
'#fcb45e',
'#fbcc88',
'#fce2b4',
'#fff6e2',
];
const ranges = [
{ divider: 1e18 , suffix: 'E' },
{ divider: 1e15 , suffix: 'P' },
{ divider: 1e12 , suffix: 'T' },
{ divider: 1e9 , suffix: 'B' },
{ divider: 1e6 , suffix: 'M' },
{ divider: 1e3 , suffix: 'k' },
];
export const formatNumber = (n) => {
for (const range of ranges) {
if (n >= range.divider) {
return parseFloat((n / range.divider).toFixed(2)).toString() + range.suffix;
}
}
return n.toString();
};
export function adaptLabelFontSize(d) {
// var xPadding, diameter, labelAvailableWidth, labelWidth;
const xPadding = 8;
const diameter = 2 * d.r;
const labelAvailableWidth = diameter - xPadding;
// @ts-ignore
const labelWidth = this.getComputedTextLength();
// There is enough space for the label so leave it as is.
if (labelWidth < labelAvailableWidth) {
return null;
}
/*
* The meaning of the ratio between labelAvailableWidth and labelWidth equaling 1 is that
* the label is taking up exactly its available space.
* With the result as `1em` the font remains the same.
*
* The meaning of the ratio between labelAvailableWidth and labelWidth equaling 0.5 is that
* the label is taking up twice its available space.
* With the result as `0.5em` the font will change to half its original size.
*/
return (labelAvailableWidth / labelWidth) + 'em';
}
|
009999bb6cc1b9b148abc178a6579d671236e29a | 1,383 | ts | TypeScript | packages/api/src/models/Error.ts | secretmissionsoftware/api-nodejs-sdk | 888e5912300ff52d1e59e8ea9d7aac8fe6dea5ce | [
"MIT"
] | null | null | null | packages/api/src/models/Error.ts | secretmissionsoftware/api-nodejs-sdk | 888e5912300ff52d1e59e8ea9d7aac8fe6dea5ce | [
"MIT"
] | 1 | 2022-02-15T19:09:42.000Z | 2022-02-15T19:09:42.000Z | packages/api/src/models/Error.ts | isabella232/api-nodejs-sdk | 608e505f810093c03eefc2ab8b2d100fa91bae66 | [
"MIT"
] | 1 | 2022-02-15T17:54:07.000Z | 2022-02-15T17:54:07.000Z | interface APIError {
number: number
field?: string
message?: string
object?: string
value?: string
}
export type ErrorResponse =
| { errors: APIError[] }
| { code: string; message: string }
export default class APIClientError extends Error {
name: string
message: string
code?: string
errors?: APIError[]
constructor(
name: string,
message: string,
code?: string,
errors?: APIError[]
) {
super()
this.name = name
this.message = message
this.code = code
this.errors = errors
}
}
export const isErrorResponse = ({
error,
error_type: errorType,
response,
}: any): any => error || errorType || response.errors
export const transformErrorResponse = (errorResponse: any): ErrorResponse => {
const {
response,
error,
error_description: errorDescription,
error_type: errorType,
message,
} = errorResponse
// singular error e.g., as returned by APIClient.users.me()
if (error && errorDescription) {
return {
code: error,
message: errorDescription,
}
}
// not_found error
if (errorType && message) {
return {
code: errorType,
message,
}
}
// general error supplied by valid endpoint
return {
errors: response.errors.map(
({
errno: number,
field,
message: msg,
object,
value,
}: any): APIError => ({
number,
field,
message: msg,
object,
value,
})
),
}
}
| 16.081395 | 78 | 0.649313 | 71 | 4 | 0 | 7 | 3 | 9 | 0 | 4 | 13 | 3 | 0 | 12.25 | 438 | 0.025114 | 0.006849 | 0.020548 | 0.006849 | 0 | 0.173913 | 0.565217 | 0.258768 | interface APIError {
number
field?
message?
object?
value?
}
export type ErrorResponse =
| { errors }
| { code; message }
export default class APIClientError extends Error {
name
message
code?
errors?
constructor(
name,
message,
code?,
errors?
) {
super()
this.name = name
this.message = message
this.code = code
this.errors = errors
}
}
export const isErrorResponse = ({
error,
error_type: errorType,
response,
}) => error || errorType || response.errors
export const transformErrorResponse = (errorResponse) => {
const {
response,
error,
error_description: errorDescription,
error_type: errorType,
message,
} = errorResponse
// singular error e.g., as returned by APIClient.users.me()
if (error && errorDescription) {
return {
code: error,
message: errorDescription,
}
}
// not_found error
if (errorType && message) {
return {
code: errorType,
message,
}
}
// general error supplied by valid endpoint
return {
errors: response.errors.map(
({
errno: number,
field,
message: msg,
object,
value,
}) => ({
number,
field,
message: msg,
object,
value,
})
),
}
}
|
00ad041ac3e09396656805ad4573fd28d2f13bc9 | 3,826 | ts | TypeScript | pkgs/ts/@circles-pink/web-client/src/onboarding/utils/paginate.ts | circles-pink/mono | 180f33aeeea516415c84ec9b10e01866afde9eb3 | [
"MIT"
] | 3 | 2022-02-04T14:26:47.000Z | 2022-02-22T12:03:03.000Z | pkgs/ts/@circles-pink/web-client/src/onboarding/utils/paginate.ts | circles-pink/circles-pink | 180f33aeeea516415c84ec9b10e01866afde9eb3 | [
"MIT"
] | null | null | null | pkgs/ts/@circles-pink/web-client/src/onboarding/utils/paginate.ts | circles-pink/circles-pink | 180f33aeeea516415c84ec9b10e01866afde9eb3 | [
"MIT"
] | null | null | null | export type Page = number | '<<' | '>>';
export const paginate = (
totalItems: number,
currentPage = 1,
pageSize = 5,
maxPages = 10000
) => {
// calculate total pages
let totalPages = Math.ceil(totalItems / pageSize);
// ensure current page isn't out of range
if (currentPage < 1) {
currentPage = 1;
} else if (currentPage > totalPages) {
currentPage = totalPages;
}
let startPage: number, endPage: number;
if (totalPages <= maxPages) {
// total pages less than max so show all pages
startPage = 1;
endPage = totalPages;
} else {
// total pages more than max so calculate start and end pages
let maxPagesBeforeCurrentPage = Math.floor(maxPages / 2);
let maxPagesAfterCurrentPage = Math.ceil(maxPages / 2) - 1;
if (currentPage <= maxPagesBeforeCurrentPage) {
// current page near the start
startPage = 1;
endPage = maxPages;
} else if (currentPage + maxPagesAfterCurrentPage >= totalPages) {
// current page near the end
startPage = totalPages - maxPages + 1;
endPage = totalPages;
} else {
// current page somewhere in the middle
startPage = currentPage - maxPagesBeforeCurrentPage;
endPage = currentPage + maxPagesAfterCurrentPage;
}
}
// calculate start and end item indexes
let startIndex = (currentPage - 1) * pageSize;
let endIndex = Math.min(startIndex + pageSize - 1, totalItems - 1);
// create an array of pages to ng-repeat in the pager control
let pages = Array.from(Array(endPage + 1 - startPage).keys()).map(
i => startPage + i
);
// return object with all pager properties required by the view
return {
totalItems: totalItems,
currentPage: currentPage,
pageSize: pageSize,
totalPages: totalPages,
startPage: startPage,
endPage: endPage,
startIndex: startIndex,
endIndex: endIndex,
pages: pages,
};
};
const LEFT_PAGE = '<<';
const RIGHT_PAGE = '>>';
const range = (from: number, to: number | string, step = 1) => {
let i = from;
const range: Page[] = [];
while (i <= to) {
range.push(i);
i += step;
}
return range;
};
export const fetchPageNumbers = ({
currentPage = 1,
totalPages = 0,
pageNeighbours = 0,
}) => {
/**
* totalNumbers: the total page numbers to show on the control
* totalBlocks: totalNumbers + 2 to cover for the left(<) and right(>) controls
*/
const totalNumbers = pageNeighbours * 2 + 3;
const totalBlocks = totalNumbers + 2;
if (totalPages > totalBlocks) {
const startPage = Math.max(2, currentPage - pageNeighbours);
const endPage = Math.min(totalPages - 1, currentPage + pageNeighbours);
let pages = range(startPage, endPage);
/**
* hasLeftSpill: has hidden pages to the left
* hasRightSpill: has hidden pages to the right
* spillOffset: number of hidden pages either to the left or to the right
*/
const hasLeftSpill = startPage > 2;
const hasRightSpill = totalPages - endPage > 1;
const spillOffset = totalNumbers - (pages.length + 1);
switch (true) {
// handle: (1) < {5 6} [7] {8 9} (10)
case hasLeftSpill && !hasRightSpill: {
const extraPages = range(startPage - spillOffset, startPage - 1);
pages = [LEFT_PAGE, ...extraPages, ...pages];
break;
}
// handle: (1) {2 3} [4] {5 6} > (10)
case !hasLeftSpill && hasRightSpill: {
const extraPages = range(endPage + 1, endPage + spillOffset);
pages = [...pages, ...extraPages, RIGHT_PAGE];
break;
}
// handle: (1) < {4 5} [6] {7 8} > (10)
case hasLeftSpill && hasRightSpill:
default: {
pages = [LEFT_PAGE, ...pages, RIGHT_PAGE];
break;
}
}
return [1, ...pages, totalPages];
}
return range(1, totalPages);
};
| 28.340741 | 81 | 0.625719 | 94 | 4 | 0 | 9 | 25 | 0 | 1 | 0 | 7 | 1 | 0 | 19.25 | 1,086 | 0.011971 | 0.02302 | 0 | 0.000921 | 0 | 0 | 0.184211 | 0.274821 | export type Page = number | '<<' | '>>';
export const paginate = (
totalItems,
currentPage = 1,
pageSize = 5,
maxPages = 10000
) => {
// calculate total pages
let totalPages = Math.ceil(totalItems / pageSize);
// ensure current page isn't out of range
if (currentPage < 1) {
currentPage = 1;
} else if (currentPage > totalPages) {
currentPage = totalPages;
}
let startPage, endPage;
if (totalPages <= maxPages) {
// total pages less than max so show all pages
startPage = 1;
endPage = totalPages;
} else {
// total pages more than max so calculate start and end pages
let maxPagesBeforeCurrentPage = Math.floor(maxPages / 2);
let maxPagesAfterCurrentPage = Math.ceil(maxPages / 2) - 1;
if (currentPage <= maxPagesBeforeCurrentPage) {
// current page near the start
startPage = 1;
endPage = maxPages;
} else if (currentPage + maxPagesAfterCurrentPage >= totalPages) {
// current page near the end
startPage = totalPages - maxPages + 1;
endPage = totalPages;
} else {
// current page somewhere in the middle
startPage = currentPage - maxPagesBeforeCurrentPage;
endPage = currentPage + maxPagesAfterCurrentPage;
}
}
// calculate start and end item indexes
let startIndex = (currentPage - 1) * pageSize;
let endIndex = Math.min(startIndex + pageSize - 1, totalItems - 1);
// create an array of pages to ng-repeat in the pager control
let pages = Array.from(Array(endPage + 1 - startPage).keys()).map(
i => startPage + i
);
// return object with all pager properties required by the view
return {
totalItems: totalItems,
currentPage: currentPage,
pageSize: pageSize,
totalPages: totalPages,
startPage: startPage,
endPage: endPage,
startIndex: startIndex,
endIndex: endIndex,
pages: pages,
};
};
const LEFT_PAGE = '<<';
const RIGHT_PAGE = '>>';
/* Example usages of 'range' are shown below:
var range = [];
range.push(i);
return range;
range(startPage, endPage);
range(startPage - spillOffset, startPage - 1);
range(endPage + 1, endPage + spillOffset);
range(1, totalPages);
*/
const range = (from, to, step = 1) => {
let i = from;
const range = [];
while (i <= to) {
range.push(i);
i += step;
}
return range;
};
export const fetchPageNumbers = ({
currentPage = 1,
totalPages = 0,
pageNeighbours = 0,
}) => {
/**
* totalNumbers: the total page numbers to show on the control
* totalBlocks: totalNumbers + 2 to cover for the left(<) and right(>) controls
*/
const totalNumbers = pageNeighbours * 2 + 3;
const totalBlocks = totalNumbers + 2;
if (totalPages > totalBlocks) {
const startPage = Math.max(2, currentPage - pageNeighbours);
const endPage = Math.min(totalPages - 1, currentPage + pageNeighbours);
let pages = range(startPage, endPage);
/**
* hasLeftSpill: has hidden pages to the left
* hasRightSpill: has hidden pages to the right
* spillOffset: number of hidden pages either to the left or to the right
*/
const hasLeftSpill = startPage > 2;
const hasRightSpill = totalPages - endPage > 1;
const spillOffset = totalNumbers - (pages.length + 1);
switch (true) {
// handle: (1) < {5 6} [7] {8 9} (10)
case hasLeftSpill && !hasRightSpill: {
const extraPages = range(startPage - spillOffset, startPage - 1);
pages = [LEFT_PAGE, ...extraPages, ...pages];
break;
}
// handle: (1) {2 3} [4] {5 6} > (10)
case !hasLeftSpill && hasRightSpill: {
const extraPages = range(endPage + 1, endPage + spillOffset);
pages = [...pages, ...extraPages, RIGHT_PAGE];
break;
}
// handle: (1) < {4 5} [6] {7 8} > (10)
case hasLeftSpill && hasRightSpill:
default: {
pages = [LEFT_PAGE, ...pages, RIGHT_PAGE];
break;
}
}
return [1, ...pages, totalPages];
}
return range(1, totalPages);
};
|
ef3a5e7c4eac4889ee330517dced37126465b8b4 | 1,750 | ts | TypeScript | src/helpers/verseSelector.ts | KurchenkoDarij/SevenBible | 2cff33d1665c47e1c90e691951db15f22aa037b7 | [
"MIT"
] | 2 | 2022-01-12T19:08:01.000Z | 2022-03-12T14:12:07.000Z | src/helpers/verseSelector.ts | KurchenkoDarij/SevenBible | 2cff33d1665c47e1c90e691951db15f22aa037b7 | [
"MIT"
] | null | null | null | src/helpers/verseSelector.ts | KurchenkoDarij/SevenBible | 2cff33d1665c47e1c90e691951db15f22aa037b7 | [
"MIT"
] | null | null | null | export const insertVerse = (selectedVerses: number[], verse: number) => {
let index = 0
for (let i = 0, max = 0; i < selectedVerses.length; i++) {
let el = selectedVerses[i]
if (el > max && el < verse) {
max = el
index = i + 1
}
}
selectedVerses.splice(index, 0, verse)
return index
}
const generateArray = (from: number, to: number) => Array.from({length: to - from}, (_, i) => i + from)
export const convertVerses = (verses: number[]) => {
let res = verses[0].toString()
for (let i = 1; i < verses.length; i++) {
const verse = verses[i]
if (verse - 1 !== verses[i - 1])
res += `,${verse}`
else {
let lastIndex: number = 0
for (let j = i; j < verses.length; j++) {
if (j === verses.length - 1) {
lastIndex = j
break
} else if (verses[j + 1] !== verses[j] + 1) {
lastIndex = j
break
}
}
res += `-${verses[lastIndex]}`
i = lastIndex
}
}
return res
}
export const insertVerses = (selectedVerses: number[], verse: number) => {
if (selectedVerses.includes(verse))
selectedVerses.length = 0
else if (selectedVerses.length === 0)
insertVerse(selectedVerses, verse)
else {
const index = insertVerse(selectedVerses, verse)
let neighborVerse = selectedVerses[index - 1] ?? selectedVerses[index + 1]
let neighborVerseIndex = verse > neighborVerse ? index - 1 : index + 1
if (verse > neighborVerse){
const verses = generateArray(neighborVerse + 1, verse)
selectedVerses.splice(neighborVerseIndex + 1, 0, ...verses)
}
else{
const verses = generateArray(verse + 1, neighborVerse)
selectedVerses.splice(index + 1, 0, ...verses)
}
}
}
| 29.166667 | 103 | 0.582286 | 55 | 5 | 0 | 9 | 18 | 0 | 2 | 0 | 8 | 0 | 0 | 10 | 553 | 0.025316 | 0.03255 | 0 | 0 | 0 | 0 | 0.25 | 0.335848 | export /* Example usages of 'insertVerse' are shown below:
insertVerse(selectedVerses, verse);
*/
const insertVerse = (selectedVerses, verse) => {
let index = 0
for (let i = 0, max = 0; i < selectedVerses.length; i++) {
let el = selectedVerses[i]
if (el > max && el < verse) {
max = el
index = i + 1
}
}
selectedVerses.splice(index, 0, verse)
return index
}
/* Example usages of 'generateArray' are shown below:
generateArray(neighborVerse + 1, verse);
generateArray(verse + 1, neighborVerse);
*/
const generateArray = (from, to) => Array.from({length: to - from}, (_, i) => i + from)
export const convertVerses = (verses) => {
let res = verses[0].toString()
for (let i = 1; i < verses.length; i++) {
const verse = verses[i]
if (verse - 1 !== verses[i - 1])
res += `,${verse}`
else {
let lastIndex = 0
for (let j = i; j < verses.length; j++) {
if (j === verses.length - 1) {
lastIndex = j
break
} else if (verses[j + 1] !== verses[j] + 1) {
lastIndex = j
break
}
}
res += `-${verses[lastIndex]}`
i = lastIndex
}
}
return res
}
export const insertVerses = (selectedVerses, verse) => {
if (selectedVerses.includes(verse))
selectedVerses.length = 0
else if (selectedVerses.length === 0)
insertVerse(selectedVerses, verse)
else {
const index = insertVerse(selectedVerses, verse)
let neighborVerse = selectedVerses[index - 1] ?? selectedVerses[index + 1]
let neighborVerseIndex = verse > neighborVerse ? index - 1 : index + 1
if (verse > neighborVerse){
const verses = generateArray(neighborVerse + 1, verse)
selectedVerses.splice(neighborVerseIndex + 1, 0, ...verses)
}
else{
const verses = generateArray(verse + 1, neighborVerse)
selectedVerses.splice(index + 1, 0, ...verses)
}
}
}
|
efbe5dd986b09f67e57a82ec167017d872141060 | 2,246 | tsx | TypeScript | src/features/shared/utils/notif.tsx | DigiChanges/solid-experience | a074020442ed5d0080223667313852e383f78c80 | [
"MIT"
] | 2 | 2022-02-17T10:10:34.000Z | 2022-02-28T00:41:57.000Z | src/features/shared/utils/notif.tsx | DigiChanges/solid-experience | a074020442ed5d0080223667313852e383f78c80 | [
"MIT"
] | null | null | null | src/features/shared/utils/notif.tsx | DigiChanges/solid-experience | a074020442ed5d0080223667313852e383f78c80 | [
"MIT"
] | 1 | 2022-01-13T23:43:11.000Z | 2022-01-13T23:43:11.000Z | /* eslint-disable no-unused-expressions */
// @ts-nocheck
const container = document.createElement( 'div' );
container.id = 'container';
export default function notify ( o = {} )
{
let position = 'bottomright';// but you can choose bottomleft or topright or bottomright
switch ( position )
{
case 'topright':
position = 'top:0;right:0';
break;
case 'bottomleft':
position = 'bottom:0';
break;
case 'bottomright':
position = 'bottom:0;right:0';
break;
default:
position = 'bottomright';
}
// container.style = position;
if ( !container.children[0] )
{
const body = document.getElementsByClassName( 'containerNotification' )[0];
body.append( container );
}
const d = o.duration * 1000 || 0;
const a = ( o.in || '' ).match( /[^ ,]+/g );
const b = ( o.out || '' ).match( /[^ ,]+/g );
const p = ( o.progressbar || '' ).match( /[^ ,]+/g );
const m = ( o.msg || '' );
const r = document.createElement( 'div' );
const close = e =>
{
b && r.classList.add( ...b );
setTimeout( () =>
{
e.remove(); !container.children[0] && container.remove();
}, b ? parseFloat( getComputedStyle( r ).getPropertyValue( 'animation-duration' ) ) * 1000 : 0 );
};
const progressbar = d && p ? `<div class='${p.join( ' ' )}'></div>` : '';
r.innerHTML = o.block || `${m}</br>${progressbar}`;
a && r.classList.add( ...a );
if ( position.match( /top/i ) )
{
container.append( r );
container.scrollTo( 0, container.scrollHeight );
}
else
{
container.prepend( r );
container.scrollTo( container.scrollHeight, 0 );
}
// if (container.children.length == 2 && container.children.length < 3) { container.append(clear) }
// container.scrollHeight > window.,innerHeight;
let s = 0; const t = setInterval( () =>
{
if ( p && d )
{
r.querySelector( `.${p[0]}` ).style.width = `${( d - s ) / d * 100}%`;
}
if ( s >= d )
{
clearInterval( t ); d && close( r );
}
s += 4;
} );
}
| 30.351351 | 105 | 0.504007 | 64 | 4 | 0 | 2 | 13 | 0 | 1 | 0 | 0 | 0 | 0 | 18.5 | 616 | 0.00974 | 0.021104 | 0 | 0 | 0 | 0 | 0 | 0.262084 | /* eslint-disable no-unused-expressions */
// @ts-nocheck
const container = document.createElement( 'div' );
container.id = 'container';
export default function notify ( o = {} )
{
let position = 'bottomright';// but you can choose bottomleft or topright or bottomright
switch ( position )
{
case 'topright':
position = 'top:0;right:0';
break;
case 'bottomleft':
position = 'bottom:0';
break;
case 'bottomright':
position = 'bottom:0;right:0';
break;
default:
position = 'bottomright';
}
// container.style = position;
if ( !container.children[0] )
{
const body = document.getElementsByClassName( 'containerNotification' )[0];
body.append( container );
}
const d = o.duration * 1000 || 0;
const a = ( o.in || '' ).match( /[^ ,]+/g );
const b = ( o.out || '' ).match( /[^ ,]+/g );
const p = ( o.progressbar || '' ).match( /[^ ,]+/g );
const m = ( o.msg || '' );
const r = document.createElement( 'div' );
/* Example usages of 'close' are shown below:
d && close(r);
*/
const close = e =>
{
b && r.classList.add( ...b );
setTimeout( () =>
{
e.remove(); !container.children[0] && container.remove();
}, b ? parseFloat( getComputedStyle( r ).getPropertyValue( 'animation-duration' ) ) * 1000 : 0 );
};
const progressbar = d && p ? `<div class='${p.join( ' ' )}'></div>` : '';
r.innerHTML = o.block || `${m}</br>${progressbar}`;
a && r.classList.add( ...a );
if ( position.match( /top/i ) )
{
container.append( r );
container.scrollTo( 0, container.scrollHeight );
}
else
{
container.prepend( r );
container.scrollTo( container.scrollHeight, 0 );
}
// if (container.children.length == 2 && container.children.length < 3) { container.append(clear) }
// container.scrollHeight > window.,innerHeight;
let s = 0; const t = setInterval( () =>
{
if ( p && d )
{
r.querySelector( `.${p[0]}` ).style.width = `${( d - s ) / d * 100}%`;
}
if ( s >= d )
{
clearInterval( t ); d && close( r );
}
s += 4;
} );
}
|
efd4212b5484e4a5a69aae848bc9a722b0c0e228 | 2,548 | ts | TypeScript | client/src/commons/geometry.ts | microsoft/OneLabeler | 316175e98a1cba72d651567d9fac08fc6c7bdf4f | [
"MIT"
] | 8 | 2022-03-26T17:45:01.000Z | 2022-03-30T14:12:20.000Z | client/src/commons/geometry.ts | microsoft/OneLabeler | 316175e98a1cba72d651567d9fac08fc6c7bdf4f | [
"MIT"
] | null | null | null | client/src/commons/geometry.ts | microsoft/OneLabeler | 316175e98a1cba72d651567d9fac08fc6c7bdf4f | [
"MIT"
] | 1 | 2022-03-27T06:11:24.000Z | 2022-03-27T06:11:24.000Z | // Copyright (c) Microsoft Corporation.
// Licensed under the MIT License.
interface Point {
x: number;
y: number;
}
// eslint-disable-next-line import/prefer-default-export
export const createDensePath = (start: Point, end: Point): Point[] => {
// Given two integer positions,
// interpolate a dense path from the start to the end.
const path: Point[] = [];
const dx = end.x - start.x;
const dy = end.y - start.y;
if (dx === 0 && dy === 0) return [{ ...start }];
if (Math.abs(dx) >= Math.abs(dy)) {
const k = dy / dx;
if (dx >= 0) {
for (let i = 0; i <= dx; i += 1) {
path.push({
x: start.x + i,
y: Math.round(start.y + k * i),
});
}
} else {
for (let i = 0; i >= dx; i -= 1) {
path.push({
x: start.x + i,
y: Math.round(start.y + k * i),
});
}
}
} else {
const k = dx / dy;
if (dy >= 0) {
for (let i = 0; i <= dy; i += 1) {
path.push({
x: Math.round(start.x + k * i),
y: start.y + i,
});
}
} else {
for (let i = 0; i >= dy; i -= 1) {
path.push({
x: Math.round(start.x + k * i),
y: start.y + i,
});
}
}
}
return path;
};
/**
* Compute the linear transformation that transform
* the rectangle [xMin, xMax] x [yMin, yMax]
* to fit the target rectangular area [0, targetWidth] x [0, targetHeight]
* without changing the aspect ratio of the rectangle.
*/
export const calFittingTransform = (
rect: { xMin: number, xMax: number, yMin: number, yMax: number },
targetWidth: number,
targetHeight: number,
): string => {
const {
xMin, xMax, yMin, yMax,
} = rect;
const width = xMax - xMin;
const height = yMax - yMin;
// the scale preserves the aspect ratio
const scale = Math.min(
targetWidth / width,
targetHeight / height,
);
const cx = (xMax + xMin) / 2;
const cy = (yMax + yMin) / 2;
// the transformation for setting the object to the center of the target
const strCenterBackground = `translate(${targetWidth / 2}, ${targetHeight / 2})`;
// the transformation for scaling the concerned area of the object to fit the target size
const strScale = Number.isNaN(scale) ? '' : `scale(${scale})`;
// the transformation for setting the center of the object to the (0, 0) position in the target
const strCenterItem = Number.isNaN(cx) || Number.isNaN(cy) ? '' : `translate(${-cx}, ${-cy})`;
return strCenterBackground + strScale + strCenterItem;
};
| 28 | 97 | 0.563187 | 67 | 2 | 0 | 5 | 20 | 2 | 0 | 0 | 9 | 1 | 0 | 27.5 | 787 | 0.008895 | 0.025413 | 0.002541 | 0.001271 | 0 | 0 | 0.310345 | 0.275626 | // Copyright (c) Microsoft Corporation.
// Licensed under the MIT License.
interface Point {
x;
y;
}
// eslint-disable-next-line import/prefer-default-export
export const createDensePath = (start, end) => {
// Given two integer positions,
// interpolate a dense path from the start to the end.
const path = [];
const dx = end.x - start.x;
const dy = end.y - start.y;
if (dx === 0 && dy === 0) return [{ ...start }];
if (Math.abs(dx) >= Math.abs(dy)) {
const k = dy / dx;
if (dx >= 0) {
for (let i = 0; i <= dx; i += 1) {
path.push({
x: start.x + i,
y: Math.round(start.y + k * i),
});
}
} else {
for (let i = 0; i >= dx; i -= 1) {
path.push({
x: start.x + i,
y: Math.round(start.y + k * i),
});
}
}
} else {
const k = dx / dy;
if (dy >= 0) {
for (let i = 0; i <= dy; i += 1) {
path.push({
x: Math.round(start.x + k * i),
y: start.y + i,
});
}
} else {
for (let i = 0; i >= dy; i -= 1) {
path.push({
x: Math.round(start.x + k * i),
y: start.y + i,
});
}
}
}
return path;
};
/**
* Compute the linear transformation that transform
* the rectangle [xMin, xMax] x [yMin, yMax]
* to fit the target rectangular area [0, targetWidth] x [0, targetHeight]
* without changing the aspect ratio of the rectangle.
*/
export const calFittingTransform = (
rect,
targetWidth,
targetHeight,
) => {
const {
xMin, xMax, yMin, yMax,
} = rect;
const width = xMax - xMin;
const height = yMax - yMin;
// the scale preserves the aspect ratio
const scale = Math.min(
targetWidth / width,
targetHeight / height,
);
const cx = (xMax + xMin) / 2;
const cy = (yMax + yMin) / 2;
// the transformation for setting the object to the center of the target
const strCenterBackground = `translate(${targetWidth / 2}, ${targetHeight / 2})`;
// the transformation for scaling the concerned area of the object to fit the target size
const strScale = Number.isNaN(scale) ? '' : `scale(${scale})`;
// the transformation for setting the center of the object to the (0, 0) position in the target
const strCenterItem = Number.isNaN(cx) || Number.isNaN(cy) ? '' : `translate(${-cx}, ${-cy})`;
return strCenterBackground + strScale + strCenterItem;
};
|
eff8611ff643ea2d40cb21a0e77a780154c7e9dc | 1,881 | ts | TypeScript | problemset/palindrome-partitioning/index.ts | OUDUIDUI/leet-code | 50e61ce16d1c419ccefc075ae9ead721cdd1cdbb | [
"MIT"
] | 6 | 2022-01-17T03:19:56.000Z | 2022-01-17T05:45:39.000Z | problemset/palindrome-partitioning/index.ts | OUDUIDUI/leet-code | 50e61ce16d1c419ccefc075ae9ead721cdd1cdbb | [
"MIT"
] | null | null | null | problemset/palindrome-partitioning/index.ts | OUDUIDUI/leet-code | 50e61ce16d1c419ccefc075ae9ead721cdd1cdbb | [
"MIT"
] | null | null | null | /**
* 回溯 + 记忆化搜索
* @desc 时间复杂度 O(N*2^N) 空间复杂度 O(N^2)
* @param s
*/
export function partition(s: string): string[][] {
const len = s.length
const res: string[][] = []
// 存储已经识别过的子串,用于记忆化搜索
const palindromeMap = new Map<string, boolean>()
backtrack(0, [])
return res
/**
* 回溯
* @param idx
* @param temp
*/
function backtrack(idx: number, temp: string[]) {
// 如果遍历完全部字符串,更新res
if (idx === len) {
res.push(temp)
return
}
// 遍历剩余字符
for (let i = idx; i < len; i++) {
// 截取出对应子串
const str = s.slice(idx, i + 1)
// 判断是否为回文子串
if (isPalindrome(str))
backtrack(i + 1, [...temp, str])
}
}
/**
* 判断是否为回文子串
* @param str
*/
function isPalindrome(str: string): boolean {
// 看看之前是否识别过相同子串,是的话直接返回之前识别的结果
if (palindromeMap.has(str))
return palindromeMap.get(str)!
// 通过双指针方式识别子串
let left = 0
let right = str.length - 1
while (left < right) {
if (str[left] !== str[right]) {
palindromeMap.set(str, false)
return false
}
left++
right--
}
palindromeMap.set(str, true)
return true
}
}
/**
* 回溯 + 动态规划预处理
* @desc 时间复杂度 O(N*2^N) 空间复杂度 O(N^2)
* @param s
*/
export function partition2(s: string): string[][] {
const len = s.length
const dp: boolean[][] = new Array(len)
.fill([])
.map(() => new Array(len).fill(true))
// 使用动态规划初始化子串是否为回文子串
for (let i = len - 1; i >= 0; i--) {
for (let j = i + 1; j < len; j++)
dp[i][j] = s[i] === s[j] && dp[i + 1][j - 1]
}
const res: string[][] = []
backtrack(0, [])
return res
function backtrack(idx: number, temp: string[]) {
if (idx === len) {
res.push(temp)
return
}
for (let i = idx; i < len; i++) {
if (dp[idx][i])
backtrack(i + 1, [...temp, s.slice(idx, i + 1)])
}
}
}
| 19.59375 | 56 | 0.516215 | 57 | 6 | 0 | 7 | 13 | 0 | 2 | 0 | 15 | 0 | 0 | 14.166667 | 714 | 0.018207 | 0.018207 | 0 | 0 | 0 | 0 | 0.576923 | 0.271934 | /**
* 回溯 + 记忆化搜索
* @desc 时间复杂度 O(N*2^N) 空间复杂度 O(N^2)
* @param s
*/
export function partition(s) {
const len = s.length
const res = []
// 存储已经识别过的子串,用于记忆化搜索
const palindromeMap = new Map<string, boolean>()
backtrack(0, [])
return res
/**
* 回溯
* @param idx
* @param temp
*/
/* Example usages of 'backtrack' are shown below:
backtrack(0, []);
backtrack(i + 1, [...temp, str]);
backtrack(i + 1, [...temp, s.slice(idx, i + 1)]);
*/
function backtrack(idx, temp) {
// 如果遍历完全部字符串,更新res
if (idx === len) {
res.push(temp)
return
}
// 遍历剩余字符
for (let i = idx; i < len; i++) {
// 截取出对应子串
const str = s.slice(idx, i + 1)
// 判断是否为回文子串
if (isPalindrome(str))
backtrack(i + 1, [...temp, str])
}
}
/**
* 判断是否为回文子串
* @param str
*/
/* Example usages of 'isPalindrome' are shown below:
isPalindrome(str);
*/
function isPalindrome(str) {
// 看看之前是否识别过相同子串,是的话直接返回之前识别的结果
if (palindromeMap.has(str))
return palindromeMap.get(str)!
// 通过双指针方式识别子串
let left = 0
let right = str.length - 1
while (left < right) {
if (str[left] !== str[right]) {
palindromeMap.set(str, false)
return false
}
left++
right--
}
palindromeMap.set(str, true)
return true
}
}
/**
* 回溯 + 动态规划预处理
* @desc 时间复杂度 O(N*2^N) 空间复杂度 O(N^2)
* @param s
*/
export function partition2(s) {
const len = s.length
const dp = new Array(len)
.fill([])
.map(() => new Array(len).fill(true))
// 使用动态规划初始化子串是否为回文子串
for (let i = len - 1; i >= 0; i--) {
for (let j = i + 1; j < len; j++)
dp[i][j] = s[i] === s[j] && dp[i + 1][j - 1]
}
const res = []
backtrack(0, [])
return res
/* Example usages of 'backtrack' are shown below:
backtrack(0, []);
backtrack(i + 1, [...temp, str]);
backtrack(i + 1, [...temp, s.slice(idx, i + 1)]);
*/
function backtrack(idx, temp) {
if (idx === len) {
res.push(temp)
return
}
for (let i = idx; i < len; i++) {
if (dp[idx][i])
backtrack(i + 1, [...temp, s.slice(idx, i + 1)])
}
}
}
|
66050b37a0775a6164dfd8cc595165bcd9391a46 | 1,135 | ts | TypeScript | src/data/constants.ts | vs1998/math-master | 9ad2d2099478efdf850c86d338f7a3f0dd72c90b | [
"MIT"
] | null | null | null | src/data/constants.ts | vs1998/math-master | 9ad2d2099478efdf850c86d338f7a3f0dd72c90b | [
"MIT"
] | 3 | 2022-02-13T12:24:01.000Z | 2022-02-28T03:49:35.000Z | src/data/constants.ts | veit30/mind-games | 9ad2d2099478efdf850c86d338f7a3f0dd72c90b | [
"MIT"
] | null | null | null | export const DIFFICULTY = {
EASY: 0,
MEDIUM: 1,
HARD: 2,
} as const;
export const OPERATOR = {
SUBTRACT: "-",
ADD: "+",
MULTIPLY: "*",
DEVIDE: "/",
SMALLER: "<",
LARGER: ">",
EQUAL: "=",
} as const;
export const GAME_STATE = {
PENDING: 1,
DONE: 2,
UNDECIDED: 3,
ERROR: 4,
} as const;
export const OPERATOR_COLLECTION = {
ADD: [OPERATOR.ADD],
SUBTRACT: [OPERATOR.SUBTRACT],
MULTIPLY: [OPERATOR.MULTIPLY],
DEVIDE: [OPERATOR.DEVIDE],
BASIC: [OPERATOR.ADD, OPERATOR.SUBTRACT],
AVERAGE: [OPERATOR.ADD, OPERATOR.SUBTRACT, OPERATOR.MULTIPLY],
FULL: [OPERATOR.ADD, OPERATOR.SUBTRACT, OPERATOR.MULTIPLY, OPERATOR.DEVIDE],
};
export const colors = [
"blue",
"red",
"orange",
"yellow",
"green",
"violet",
"white",
];
export const operatorMapper = (s: string | number): string => {
if (s === "*") {
return "×";
} else if (s === "/") {
return "÷";
} else {
return s + "";
}
};
export const ICONS = {
PLAY: "play",
COLOR_SWITCH: "color-switch",
CHEVRON_LEFT: "chevron-left",
HELP: "help",
RESTART: "restart",
CLOSE: "close",
TRASH: "trash",
} as const;
| 18.015873 | 78 | 0.593833 | 56 | 1 | 0 | 1 | 7 | 0 | 0 | 0 | 3 | 0 | 4 | 7 | 404 | 0.00495 | 0.017327 | 0 | 0 | 0.009901 | 0 | 0.333333 | 0.236297 | export const DIFFICULTY = {
EASY: 0,
MEDIUM: 1,
HARD: 2,
} as const;
export const OPERATOR = {
SUBTRACT: "-",
ADD: "+",
MULTIPLY: "*",
DEVIDE: "/",
SMALLER: "<",
LARGER: ">",
EQUAL: "=",
} as const;
export const GAME_STATE = {
PENDING: 1,
DONE: 2,
UNDECIDED: 3,
ERROR: 4,
} as const;
export const OPERATOR_COLLECTION = {
ADD: [OPERATOR.ADD],
SUBTRACT: [OPERATOR.SUBTRACT],
MULTIPLY: [OPERATOR.MULTIPLY],
DEVIDE: [OPERATOR.DEVIDE],
BASIC: [OPERATOR.ADD, OPERATOR.SUBTRACT],
AVERAGE: [OPERATOR.ADD, OPERATOR.SUBTRACT, OPERATOR.MULTIPLY],
FULL: [OPERATOR.ADD, OPERATOR.SUBTRACT, OPERATOR.MULTIPLY, OPERATOR.DEVIDE],
};
export const colors = [
"blue",
"red",
"orange",
"yellow",
"green",
"violet",
"white",
];
export const operatorMapper = (s) => {
if (s === "*") {
return "×";
} else if (s === "/") {
return "÷";
} else {
return s + "";
}
};
export const ICONS = {
PLAY: "play",
COLOR_SWITCH: "color-switch",
CHEVRON_LEFT: "chevron-left",
HELP: "help",
RESTART: "restart",
CLOSE: "close",
TRASH: "trash",
} as const;
|
66101387a59fde3a65bc3034ad86ed33734e3377 | 4,557 | tsx | TypeScript | docs/components/custom/.demos/data/liquidfill_one.tsx | kdcloudone/charts | 9a3b930d171ae89732c3895d03e552d94b3e0fbc | [
"Apache-2.0"
] | 4 | 2022-01-26T07:18:56.000Z | 2022-03-30T01:05:48.000Z | docs/components/custom/.demos/data/liquidfill_one.tsx | kdcloudone/charts | 9a3b930d171ae89732c3895d03e552d94b3e0fbc | [
"Apache-2.0"
] | null | null | null | docs/components/custom/.demos/data/liquidfill_one.tsx | kdcloudone/charts | 9a3b930d171ae89732c3895d03e552d94b3e0fbc | [
"Apache-2.0"
] | null | null | null | let angle = 0; //角度,用来做简单的动画效果的
function getCirlPoint(x0, y0, r, angle) {
let x1 = x0 + r * Math.cos((angle * Math.PI) / 180);
let y1 = y0 + r * Math.sin((angle * Math.PI) / 180);
return {
x: x1,
y: y1,
};
}
export default {
backgroundColor: '#020f18',
series: [
{
name: '内线',
type: 'custom',
coordinateSystem: 'none',
renderItem: function(params, api) {
return {
type: 'arc',
shape: {
cx: api.getWidth() / 2,
cy: api.getHeight() / 2,
r: Math.min(api.getWidth(), api.getHeight()) / 2.3,
startAngle: ((0 + angle) * Math.PI) / 180,
endAngle: ((90 + angle) * Math.PI) / 180,
},
style: {
stroke: '#0ff',
fill: 'transparent',
lineWidth: 3.5,
},
silent: true,
};
},
data: [0],
},
{
name: '内线',
type: 'custom',
coordinateSystem: 'none',
renderItem: function(params, api) {
return {
type: 'arc',
shape: {
cx: api.getWidth() / 2,
cy: api.getHeight() / 2,
r: Math.min(api.getWidth(), api.getHeight()) / 2.3,
startAngle: ((180 + angle) * Math.PI) / 180,
endAngle: ((270 + angle) * Math.PI) / 180,
},
style: {
stroke: '#0ff',
fill: 'transparent',
lineWidth: 3.5,
},
silent: true,
};
},
data: [0],
},
{
name: '外线',
type: 'custom',
coordinateSystem: 'none',
renderItem: function(params, api) {
return {
type: 'arc',
shape: {
cx: api.getWidth() / 2,
cy: api.getHeight() / 2,
r: Math.min(api.getWidth(), api.getHeight()) / 2.1,
startAngle: ((270 + -angle) * Math.PI) / 180,
endAngle: ((40 + -angle) * Math.PI) / 180,
},
style: {
stroke: '#0ff',
fill: 'transparent',
lineWidth: 3.5,
},
silent: true,
};
},
data: [0],
},
{
name: '外线',
type: 'custom',
coordinateSystem: 'none',
renderItem: function(params, api) {
return {
type: 'arc',
shape: {
cx: api.getWidth() / 2,
cy: api.getHeight() / 2,
r: Math.min(api.getWidth(), api.getHeight()) / 2.1,
startAngle: ((90 + -angle) * Math.PI) / 180,
endAngle: ((220 + -angle) * Math.PI) / 180,
},
style: {
stroke: '#0ff',
fill: 'transparent',
lineWidth: 3.5,
},
silent: true,
};
},
data: [0],
},
{
name: '线头点',
type: 'custom',
coordinateSystem: 'none',
renderItem: function(params, api) {
let x0 = api.getWidth() / 2;
let y0 = api.getHeight() / 2;
let r = Math.min(api.getWidth(), api.getHeight()) / 2.1;
let point = getCirlPoint(x0, y0, r, 90 + -angle);
return {
type: 'circle',
shape: {
cx: point.x,
cy: point.y,
r: 5,
},
style: {
stroke: '#0ff', //绿
fill: '#0ff',
},
silent: true,
};
},
data: [0],
},
{
name: '线头点',
type: 'custom',
coordinateSystem: 'none',
renderItem: function(params, api) {
let x0 = api.getWidth() / 2;
let y0 = api.getHeight() / 2;
let r = Math.min(api.getWidth(), api.getHeight()) / 2.1;
let point = getCirlPoint(x0, y0, r, 270 + -angle);
return {
type: 'circle',
shape: {
cx: point.x,
cy: point.y,
r: 5,
},
style: {
stroke: '#0ff', //绿
fill: '#0ff',
},
silent: true,
};
},
data: [0],
},
{
type: 'liquidFill',
radius: '78%',
center: ['50%', '50%'],
color: ['#0ff', '#0ff', '#0ff'], //水波
data: [0.5, 0.5, 0.5], // data个数代表波浪数
label: {
normal: {
show: false,
},
},
backgroundStyle: {
borderWidth: 1,
color: 'transparent',
},
outline: {
show: true,
itemStyle: {
borderColor: '#0ff',
borderWidth: 2,
},
borderDistance: 3,
},
},
],
};
| 24.368984 | 64 | 0.403994 | 184 | 7 | 0 | 16 | 11 | 0 | 1 | 0 | 0 | 0 | 0 | 14.857143 | 1,356 | 0.016962 | 0.008112 | 0 | 0 | 0 | 0 | 0 | 0.236514 | let angle = 0; //角度,用来做简单的动画效果的
/* Example usages of 'getCirlPoint' are shown below:
getCirlPoint(x0, y0, r, 90 + -angle);
getCirlPoint(x0, y0, r, 270 + -angle);
*/
function getCirlPoint(x0, y0, r, angle) {
let x1 = x0 + r * Math.cos((angle * Math.PI) / 180);
let y1 = y0 + r * Math.sin((angle * Math.PI) / 180);
return {
x: x1,
y: y1,
};
}
export default {
backgroundColor: '#020f18',
series: [
{
name: '内线',
type: 'custom',
coordinateSystem: 'none',
renderItem: function(params, api) {
return {
type: 'arc',
shape: {
cx: api.getWidth() / 2,
cy: api.getHeight() / 2,
r: Math.min(api.getWidth(), api.getHeight()) / 2.3,
startAngle: ((0 + angle) * Math.PI) / 180,
endAngle: ((90 + angle) * Math.PI) / 180,
},
style: {
stroke: '#0ff',
fill: 'transparent',
lineWidth: 3.5,
},
silent: true,
};
},
data: [0],
},
{
name: '内线',
type: 'custom',
coordinateSystem: 'none',
renderItem: function(params, api) {
return {
type: 'arc',
shape: {
cx: api.getWidth() / 2,
cy: api.getHeight() / 2,
r: Math.min(api.getWidth(), api.getHeight()) / 2.3,
startAngle: ((180 + angle) * Math.PI) / 180,
endAngle: ((270 + angle) * Math.PI) / 180,
},
style: {
stroke: '#0ff',
fill: 'transparent',
lineWidth: 3.5,
},
silent: true,
};
},
data: [0],
},
{
name: '外线',
type: 'custom',
coordinateSystem: 'none',
renderItem: function(params, api) {
return {
type: 'arc',
shape: {
cx: api.getWidth() / 2,
cy: api.getHeight() / 2,
r: Math.min(api.getWidth(), api.getHeight()) / 2.1,
startAngle: ((270 + -angle) * Math.PI) / 180,
endAngle: ((40 + -angle) * Math.PI) / 180,
},
style: {
stroke: '#0ff',
fill: 'transparent',
lineWidth: 3.5,
},
silent: true,
};
},
data: [0],
},
{
name: '外线',
type: 'custom',
coordinateSystem: 'none',
renderItem: function(params, api) {
return {
type: 'arc',
shape: {
cx: api.getWidth() / 2,
cy: api.getHeight() / 2,
r: Math.min(api.getWidth(), api.getHeight()) / 2.1,
startAngle: ((90 + -angle) * Math.PI) / 180,
endAngle: ((220 + -angle) * Math.PI) / 180,
},
style: {
stroke: '#0ff',
fill: 'transparent',
lineWidth: 3.5,
},
silent: true,
};
},
data: [0],
},
{
name: '线头点',
type: 'custom',
coordinateSystem: 'none',
renderItem: function(params, api) {
let x0 = api.getWidth() / 2;
let y0 = api.getHeight() / 2;
let r = Math.min(api.getWidth(), api.getHeight()) / 2.1;
let point = getCirlPoint(x0, y0, r, 90 + -angle);
return {
type: 'circle',
shape: {
cx: point.x,
cy: point.y,
r: 5,
},
style: {
stroke: '#0ff', //绿
fill: '#0ff',
},
silent: true,
};
},
data: [0],
},
{
name: '线头点',
type: 'custom',
coordinateSystem: 'none',
renderItem: function(params, api) {
let x0 = api.getWidth() / 2;
let y0 = api.getHeight() / 2;
let r = Math.min(api.getWidth(), api.getHeight()) / 2.1;
let point = getCirlPoint(x0, y0, r, 270 + -angle);
return {
type: 'circle',
shape: {
cx: point.x,
cy: point.y,
r: 5,
},
style: {
stroke: '#0ff', //绿
fill: '#0ff',
},
silent: true,
};
},
data: [0],
},
{
type: 'liquidFill',
radius: '78%',
center: ['50%', '50%'],
color: ['#0ff', '#0ff', '#0ff'], //水波
data: [0.5, 0.5, 0.5], // data个数代表波浪数
label: {
normal: {
show: false,
},
},
backgroundStyle: {
borderWidth: 1,
color: 'transparent',
},
outline: {
show: true,
itemStyle: {
borderColor: '#0ff',
borderWidth: 2,
},
borderDistance: 3,
},
},
],
};
|
661cd30123800a03ffd7ce40e31b03341b05433a | 1,828 | ts | TypeScript | internal/codec-commit/index.ts | strager/rome-tools | 3d09ea15e3e0baab005e4774822cdb1330320f4a | [
"MIT"
] | 1 | 2022-03-06T11:00:49.000Z | 2022-03-06T11:00:49.000Z | internal/codec-commit/index.ts | strager/rome-tools | 3d09ea15e3e0baab005e4774822cdb1330320f4a | [
"MIT"
] | null | null | null | internal/codec-commit/index.ts | strager/rome-tools | 3d09ea15e3e0baab005e4774822cdb1330320f4a | [
"MIT"
] | null | null | null | export interface Commit {
readonly type: undefined | string;
readonly description: string;
readonly scope: undefined | string;
readonly breaking: boolean;
readonly pullRequest: undefined | number;
readonly fixesIssues: number[];
}
// TODO: Previously there was usage of ParserCore here, but it ended up having to deserialize the tokens
// and was more complex than this regex approach. If we ever need to perform actual validation, and not
// metadata extraction, we can go back to ParserCore but implement it with token state.
export function parseCommit(input: string): Commit {
let line = input.split("\n")[0];
let type: Commit["type"];
let scope: Commit["scope"];
let breaking: Commit["breaking"] = false;
let pullRequest: Commit["pullRequest"];
let fixesIssues: Commit["fixesIssues"] = [];
let description: Commit["description"] = "";
// Extract the type
const typeMatch = line.match(/^([a-zA-Z]+)(?:[:(!])/);
if (typeMatch != null) {
type = typeMatch[1];
line = line.slice(type.length);
// Extract scope
if (line[0] === "(") {
const scopeMatch = line.match(/^\((.*?)\)/);
if (scopeMatch != null) {
scope = scopeMatch[1];
line = line.slice(scopeMatch[0].length);
}
}
if (line[0] === "!") {
breaking = true;
line = line.slice(1);
}
if (line[0] === ":") {
line = line.slice(1);
}
}
description = line.trim();
// Extract pull request id from description
const pullRequestMatch = description.match(/\(#(\d+)\)$/);
if (pullRequestMatch != null) {
pullRequest = Number(pullRequestMatch[1]);
description = description.slice(0, -pullRequestMatch[0].length).trim();
}
// TODO fixesIssues
if (/BREAKING[\-\s]CHANGE:\s\S+/.test(input)) {
breaking = true;
}
return {
breaking,
type,
description,
scope,
pullRequest,
fixesIssues,
};
}
| 25.041096 | 104 | 0.657549 | 53 | 1 | 0 | 1 | 10 | 6 | 0 | 0 | 7 | 1 | 0 | 43 | 563 | 0.003552 | 0.017762 | 0.010657 | 0.001776 | 0 | 0 | 0.388889 | 0.238905 | export interface Commit {
readonly type;
readonly description;
readonly scope;
readonly breaking;
readonly pullRequest;
readonly fixesIssues;
}
// TODO: Previously there was usage of ParserCore here, but it ended up having to deserialize the tokens
// and was more complex than this regex approach. If we ever need to perform actual validation, and not
// metadata extraction, we can go back to ParserCore but implement it with token state.
export function parseCommit(input) {
let line = input.split("\n")[0];
let type;
let scope;
let breaking = false;
let pullRequest;
let fixesIssues = [];
let description = "";
// Extract the type
const typeMatch = line.match(/^([a-zA-Z]+)(?:[:(!])/);
if (typeMatch != null) {
type = typeMatch[1];
line = line.slice(type.length);
// Extract scope
if (line[0] === "(") {
const scopeMatch = line.match(/^\((.*?)\)/);
if (scopeMatch != null) {
scope = scopeMatch[1];
line = line.slice(scopeMatch[0].length);
}
}
if (line[0] === "!") {
breaking = true;
line = line.slice(1);
}
if (line[0] === ":") {
line = line.slice(1);
}
}
description = line.trim();
// Extract pull request id from description
const pullRequestMatch = description.match(/\(#(\d+)\)$/);
if (pullRequestMatch != null) {
pullRequest = Number(pullRequestMatch[1]);
description = description.slice(0, -pullRequestMatch[0].length).trim();
}
// TODO fixesIssues
if (/BREAKING[\-\s]CHANGE:\s\S+/.test(input)) {
breaking = true;
}
return {
breaking,
type,
description,
scope,
pullRequest,
fixesIssues,
};
}
|
662859e6908455ea573b9f30a290313a0c718d26 | 2,169 | ts | TypeScript | src/libs/diff_lib.ts | hviana/scriptNOP | 3b2d7b189ce7629235706c363700a952d995857b | [
"MIT"
] | 1 | 2022-02-14T14:47:39.000Z | 2022-02-14T14:47:39.000Z | src/libs/diff_lib.ts | hviana/scriptNOP | 3b2d7b189ce7629235706c363700a952d995857b | [
"MIT"
] | null | null | null | src/libs/diff_lib.ts | hviana/scriptNOP | 3b2d7b189ce7629235706c363700a952d995857b | [
"MIT"
] | null | null | null | //adapted from https://github.com/AsyncBanana/microdiff
interface Difference {
type: "CREATE" | "REMOVE" | "CHANGE";
path: (string | number)[];
value?: any;
oldValue?: any;
}
interface Options {
cyclesFix: boolean;
}
const richTypes = { Date: true, RegExp: true, String: true, Number: true };
export default function diff(
obj: Record<string, any> | any[],
newObj: Record<string, any> | any[],
options: Partial<Options> = { cyclesFix: true },
_stack: Record<string, any>[] = [],
): Difference[] {
let diffs: Difference[] = [];
const isObjArray = Array.isArray(obj);
for (const key in obj) {
//@ts-ignore
const objKey = obj[key];
const path = isObjArray ? +key : key;
if (!(key in newObj)) {
diffs.push({
type: "REMOVE",
path: [path],
//@ts-ignore
oldValue: obj[key],
});
continue;
}
//@ts-ignore
const newObjKey = newObj[key];
const areObjects = typeof objKey === "object" &&
typeof newObjKey === "object";
if (
objKey &&
newObjKey &&
areObjects &&
//@ts-ignore
!richTypes[Object.getPrototypeOf(objKey).constructor.name] &&
(!options.cyclesFix || !_stack.includes(objKey))
) {
const nestedDiffs = diff(
objKey,
newObjKey,
options,
options.cyclesFix ? _stack.concat([objKey]) : [],
);
diffs.push.apply(
diffs,
nestedDiffs.map((difference) => {
difference.path.unshift(path);
return difference;
}),
);
} else if (
objKey !== newObjKey &&
!(
areObjects &&
(isNaN(objKey)
? objKey + "" === newObjKey + ""
: +objKey === +newObjKey)
)
) {
diffs.push({
path: [path],
type: "CHANGE",
value: newObjKey,
oldValue: objKey,
});
}
}
const isNewObjArray = Array.isArray(newObj);
for (const key in newObj) {
if (!(key in obj)) {
diffs.push({
type: "CREATE",
path: [isNewObjArray ? +key : key],
//@ts-ignore
value: newObj[key],
});
}
}
return diffs;
}
| 23.322581 | 75 | 0.533426 | 81 | 2 | 0 | 5 | 9 | 5 | 1 | 7 | 6 | 2 | 2 | 33 | 587 | 0.011925 | 0.015332 | 0.008518 | 0.003407 | 0.003407 | 0.333333 | 0.285714 | 0.247723 | //adapted from https://github.com/AsyncBanana/microdiff
interface Difference {
type;
path;
value?;
oldValue?;
}
interface Options {
cyclesFix;
}
const richTypes = { Date: true, RegExp: true, String: true, Number: true };
export default /* Example usages of 'diff' are shown below:
diff(objKey, newObjKey, options, options.cyclesFix ? _stack.concat([objKey]) : []);
*/
function diff(
obj,
newObj,
options = { cyclesFix: true },
_stack = [],
) {
let diffs = [];
const isObjArray = Array.isArray(obj);
for (const key in obj) {
//@ts-ignore
const objKey = obj[key];
const path = isObjArray ? +key : key;
if (!(key in newObj)) {
diffs.push({
type: "REMOVE",
path: [path],
//@ts-ignore
oldValue: obj[key],
});
continue;
}
//@ts-ignore
const newObjKey = newObj[key];
const areObjects = typeof objKey === "object" &&
typeof newObjKey === "object";
if (
objKey &&
newObjKey &&
areObjects &&
//@ts-ignore
!richTypes[Object.getPrototypeOf(objKey).constructor.name] &&
(!options.cyclesFix || !_stack.includes(objKey))
) {
const nestedDiffs = diff(
objKey,
newObjKey,
options,
options.cyclesFix ? _stack.concat([objKey]) : [],
);
diffs.push.apply(
diffs,
nestedDiffs.map((difference) => {
difference.path.unshift(path);
return difference;
}),
);
} else if (
objKey !== newObjKey &&
!(
areObjects &&
(isNaN(objKey)
? objKey + "" === newObjKey + ""
: +objKey === +newObjKey)
)
) {
diffs.push({
path: [path],
type: "CHANGE",
value: newObjKey,
oldValue: objKey,
});
}
}
const isNewObjArray = Array.isArray(newObj);
for (const key in newObj) {
if (!(key in obj)) {
diffs.push({
type: "CREATE",
path: [isNewObjArray ? +key : key],
//@ts-ignore
value: newObj[key],
});
}
}
return diffs;
}
|
6651bfcf0acdccc1d7c1b5f10d820e777f3541ca | 2,995 | ts | TypeScript | src/app/script/bb/math/matrix.ts | satopian/klecks | aa1026c59ab925a275c330b3bbe552063c8c810f | [
"MIT"
] | 11 | 2022-01-29T22:46:39.000Z | 2022-03-28T15:42:22.000Z | src/app/script/bb/math/matrix.ts | satopian/klecks | aa1026c59ab925a275c330b3bbe552063c8c810f | [
"MIT"
] | 14 | 2022-02-13T21:52:23.000Z | 2022-03-31T16:07:47.000Z | src/app/script/bb/math/matrix.ts | satopian/klecks | aa1026c59ab925a275c330b3bbe552063c8c810f | [
"MIT"
] | 7 | 2022-02-04T23:51:42.000Z | 2022-03-21T12:31:44.000Z | export const Matrix = (function () {
// https://developer.mozilla.org/en-US/docs/Web/API/WebGL_API/Matrix_math_for_the_web
// yes not optimized - but it's not used for physics simulations.
// const perfTotal = 0;
// point • matrix
function multiplyMatrixAndPoint(matrix, point) {
const result = [
(point[0] * matrix[0]) + (point[1] * matrix[4]) + (point[2] * matrix[8]) + (point[3] * matrix[12]), // x
(point[0] * matrix[1]) + (point[1] * matrix[5]) + (point[2] * matrix[9]) + (point[3] * matrix[13]), // y
(point[0] * matrix[2]) + (point[1] * matrix[6]) + (point[2] * matrix[10]) + (point[3] * matrix[14]), // z
(point[0] * matrix[3]) + (point[1] * matrix[7]) + (point[2] * matrix[11]) + (point[3] * matrix[15]) // w
];
return result;
}
//matrixB • matrixA
function multiplyMatrices(matrixA, matrixB) {
// Slice the second matrix up into rows
const row0 = [matrixB[0], matrixB[1], matrixB[2], matrixB[3]];
const row1 = [matrixB[4], matrixB[5], matrixB[6], matrixB[7]];
const row2 = [matrixB[8], matrixB[9], matrixB[10], matrixB[11]];
const row3 = [matrixB[12], matrixB[13], matrixB[14], matrixB[15]];
// Multiply each row by matrixA
const result0 = multiplyMatrixAndPoint(matrixA, row0);
const result1 = multiplyMatrixAndPoint(matrixA, row1);
const result2 = multiplyMatrixAndPoint(matrixA, row2);
const result3 = multiplyMatrixAndPoint(matrixA, row3);
// Turn the result rows back into a single matrix
return [
result0[0], result0[1], result0[2], result0[3],
result1[0], result1[1], result1[2], result1[3],
result2[0], result2[1], result2[2], result2[3],
result3[0], result3[1], result3[2], result3[3]
];
}
function createTranslationMatrix(x, y) {
return [
1, 0, 0, 0,
0, 1, 0, 0,
0, 0, 1, 0,
x, y, 0, 1
];
}
function createRotationMatrix(angleRad) {
//let angleRad = angleDeg / 360 * 2 * Math.PI;
return [
Math.cos(-angleRad), -Math.sin(-angleRad), 0, 0,
Math.sin(-angleRad), Math.cos(-angleRad), 0, 0,
0, 0, 1, 0,
0, 0, 0, 1
];
}
function createScaleMatrix(f) {
return [
f, 0, 0, 0,
0, f, 0, 0,
0, 0, 1, 0,
0, 0, 0, 1
];
}
return {
getIdentity: function () {
return [
1, 0, 0, 0,
0, 1, 0, 0,
0, 0, 1, 0,
0, 0, 0, 1
];
},
multiplyMatrixAndPoint: multiplyMatrixAndPoint,
multiplyMatrices: multiplyMatrices,
createTranslationMatrix: createTranslationMatrix,
createRotationMatrix: createRotationMatrix,
createScaleMatrix: createScaleMatrix
};
})(); | 34.825581 | 117 | 0.523873 | 66 | 7 | 0 | 8 | 10 | 0 | 1 | 0 | 0 | 0 | 0 | 15.571429 | 940 | 0.015957 | 0.010638 | 0 | 0 | 0 | 0 | 0 | 0.242422 | export const Matrix = (function () {
// https://developer.mozilla.org/en-US/docs/Web/API/WebGL_API/Matrix_math_for_the_web
// yes not optimized - but it's not used for physics simulations.
// const perfTotal = 0;
// point • matrix
/* Example usages of 'multiplyMatrixAndPoint' are shown below:
multiplyMatrixAndPoint(matrixA, row0);
multiplyMatrixAndPoint(matrixA, row1);
multiplyMatrixAndPoint(matrixA, row2);
multiplyMatrixAndPoint(matrixA, row3);
;
*/
function multiplyMatrixAndPoint(matrix, point) {
const result = [
(point[0] * matrix[0]) + (point[1] * matrix[4]) + (point[2] * matrix[8]) + (point[3] * matrix[12]), // x
(point[0] * matrix[1]) + (point[1] * matrix[5]) + (point[2] * matrix[9]) + (point[3] * matrix[13]), // y
(point[0] * matrix[2]) + (point[1] * matrix[6]) + (point[2] * matrix[10]) + (point[3] * matrix[14]), // z
(point[0] * matrix[3]) + (point[1] * matrix[7]) + (point[2] * matrix[11]) + (point[3] * matrix[15]) // w
];
return result;
}
//matrixB • matrixA
/* Example usages of 'multiplyMatrices' are shown below:
;
*/
function multiplyMatrices(matrixA, matrixB) {
// Slice the second matrix up into rows
const row0 = [matrixB[0], matrixB[1], matrixB[2], matrixB[3]];
const row1 = [matrixB[4], matrixB[5], matrixB[6], matrixB[7]];
const row2 = [matrixB[8], matrixB[9], matrixB[10], matrixB[11]];
const row3 = [matrixB[12], matrixB[13], matrixB[14], matrixB[15]];
// Multiply each row by matrixA
const result0 = multiplyMatrixAndPoint(matrixA, row0);
const result1 = multiplyMatrixAndPoint(matrixA, row1);
const result2 = multiplyMatrixAndPoint(matrixA, row2);
const result3 = multiplyMatrixAndPoint(matrixA, row3);
// Turn the result rows back into a single matrix
return [
result0[0], result0[1], result0[2], result0[3],
result1[0], result1[1], result1[2], result1[3],
result2[0], result2[1], result2[2], result2[3],
result3[0], result3[1], result3[2], result3[3]
];
}
/* Example usages of 'createTranslationMatrix' are shown below:
;
*/
function createTranslationMatrix(x, y) {
return [
1, 0, 0, 0,
0, 1, 0, 0,
0, 0, 1, 0,
x, y, 0, 1
];
}
/* Example usages of 'createRotationMatrix' are shown below:
;
*/
function createRotationMatrix(angleRad) {
//let angleRad = angleDeg / 360 * 2 * Math.PI;
return [
Math.cos(-angleRad), -Math.sin(-angleRad), 0, 0,
Math.sin(-angleRad), Math.cos(-angleRad), 0, 0,
0, 0, 1, 0,
0, 0, 0, 1
];
}
/* Example usages of 'createScaleMatrix' are shown below:
;
*/
function createScaleMatrix(f) {
return [
f, 0, 0, 0,
0, f, 0, 0,
0, 0, 1, 0,
0, 0, 0, 1
];
}
return {
getIdentity: function () {
return [
1, 0, 0, 0,
0, 1, 0, 0,
0, 0, 1, 0,
0, 0, 0, 1
];
},
multiplyMatrixAndPoint: multiplyMatrixAndPoint,
multiplyMatrices: multiplyMatrices,
createTranslationMatrix: createTranslationMatrix,
createRotationMatrix: createRotationMatrix,
createScaleMatrix: createScaleMatrix
};
})(); |
66bd5eba40aca2b596688bef5f65d30ce9284a78 | 3,511 | ts | TypeScript | src/escape.ts | threax/htmlrapier | 03db9f5ea71205527d8a3a8e8c2e10103f698b1c | [
"MIT"
] | 1 | 2022-01-19T18:11:24.000Z | 2022-01-19T18:11:24.000Z | src/escape.ts | threax/htmlrapier | 03db9f5ea71205527d8a3a8e8c2e10103f698b1c | [
"MIT"
] | null | null | null | src/escape.ts | threax/htmlrapier | 03db9f5ea71205527d8a3a8e8c2e10103f698b1c | [
"MIT"
] | null | null | null | "use strict";
/**
* Escape text to prevent html characters from being output. Helps prevent xss, called automatically
* by formatText, if it is configured to escape. If you manually write user data consider using this
* function to escape it, but it is not needed using other HtmlRapier functions like repeat, createComponent
* or formatText. This escape function should be good enough to write html including attributes with ", ', ` or no quotes
* but probably not good enough for css or javascript. Since separating these is the major goal of this library writing
* out javascript or html with this method will not be supported and could be unsafe.
*
* TL, DR: Only for HTML, not javascript or css, escapes &, <, >, ", ', `, , !, @, $, %, (, ), =, +, {, }, [, and ]
* @param {string} text - the text to escape.
* @returns {type} - The escaped version of text.
*/
export function escape(text) {
text = String(text);
var status =
{
textStart: 0,
bracketStart: 0,
output: ""
}
for (var i = 0; i < text.length; ++i) {
switch (text[i]) {
case '&':
outputEncoded(i, text, status, '&');
break;
case '<':
outputEncoded(i, text, status, '<');
break;
case '>':
outputEncoded(i, text, status, '>');
break;
case '"':
outputEncoded(i, text, status, '"');
break;
case '\'':
outputEncoded(i, text, status, ''');
break;
case '`':
outputEncoded(i, text, status, '`');
break;
case ' ':
outputEncoded(i, text, status, ' ');
break;
case '!':
outputEncoded(i, text, status, '!');
break;
case '@':
outputEncoded(i, text, status, '@');
break;
case '$':
outputEncoded(i, text, status, '$');
break;
case '%':
outputEncoded(i, text, status, '%');
break;
case '(':
outputEncoded(i, text, status, '(');
break;
case ')':
outputEncoded(i, text, status, ')');
break;
case '=':
outputEncoded(i, text, status, '=');
break;
case '+':
outputEncoded(i, text, status, '+');
break;
case '{':
outputEncoded(i, text, status, '{');
break;
case '}':
outputEncoded(i, text, status, '}');
break;
case '[':
outputEncoded(i, text, status, '[');
break;
case ']':
outputEncoded(i, text, status, ']');
break;
default:
break;
}
}
if (status.textStart < text.length) {
status.output += text.substring(status.textStart, text.length);
}
return status.output;
}
//Helper function for escaping
function outputEncoded(i, text, status, replacement) {
status.bracketStart = i;
status.output += text.substring(status.textStart, status.bracketStart) + replacement;
status.textStart = i + 1;
} | 35.11 | 121 | 0.477642 | 82 | 2 | 0 | 5 | 2 | 0 | 1 | 0 | 0 | 0 | 0 | 38.5 | 802 | 0.008728 | 0.002494 | 0 | 0 | 0 | 0 | 0 | 0.19899 | "use strict";
/**
* Escape text to prevent html characters from being output. Helps prevent xss, called automatically
* by formatText, if it is configured to escape. If you manually write user data consider using this
* function to escape it, but it is not needed using other HtmlRapier functions like repeat, createComponent
* or formatText. This escape function should be good enough to write html including attributes with ", ', ` or no quotes
* but probably not good enough for css or javascript. Since separating these is the major goal of this library writing
* out javascript or html with this method will not be supported and could be unsafe.
*
* TL, DR: Only for HTML, not javascript or css, escapes &, <, >, ", ', `, , !, @, $, %, (, ), =, +, {, }, [, and ]
* @param {string} text - the text to escape.
* @returns {type} - The escaped version of text.
*/
export function escape(text) {
text = String(text);
var status =
{
textStart: 0,
bracketStart: 0,
output: ""
}
for (var i = 0; i < text.length; ++i) {
switch (text[i]) {
case '&':
outputEncoded(i, text, status, '&');
break;
case '<':
outputEncoded(i, text, status, '<');
break;
case '>':
outputEncoded(i, text, status, '>');
break;
case '"':
outputEncoded(i, text, status, '"');
break;
case '\'':
outputEncoded(i, text, status, ''');
break;
case '`':
outputEncoded(i, text, status, '`');
break;
case ' ':
outputEncoded(i, text, status, ' ');
break;
case '!':
outputEncoded(i, text, status, '!');
break;
case '@':
outputEncoded(i, text, status, '@');
break;
case '$':
outputEncoded(i, text, status, '$');
break;
case '%':
outputEncoded(i, text, status, '%');
break;
case '(':
outputEncoded(i, text, status, '(');
break;
case ')':
outputEncoded(i, text, status, ')');
break;
case '=':
outputEncoded(i, text, status, '=');
break;
case '+':
outputEncoded(i, text, status, '+');
break;
case '{':
outputEncoded(i, text, status, '{');
break;
case '}':
outputEncoded(i, text, status, '}');
break;
case '[':
outputEncoded(i, text, status, '[');
break;
case ']':
outputEncoded(i, text, status, ']');
break;
default:
break;
}
}
if (status.textStart < text.length) {
status.output += text.substring(status.textStart, text.length);
}
return status.output;
}
//Helper function for escaping
/* Example usages of 'outputEncoded' are shown below:
outputEncoded(i, text, status, '&');
outputEncoded(i, text, status, '<');
outputEncoded(i, text, status, '>');
outputEncoded(i, text, status, '"');
outputEncoded(i, text, status, ''');
outputEncoded(i, text, status, '`');
outputEncoded(i, text, status, ' ');
outputEncoded(i, text, status, '!');
outputEncoded(i, text, status, '@');
outputEncoded(i, text, status, '$');
outputEncoded(i, text, status, '%');
outputEncoded(i, text, status, '(');
outputEncoded(i, text, status, ')');
outputEncoded(i, text, status, '=');
outputEncoded(i, text, status, '+');
outputEncoded(i, text, status, '{');
outputEncoded(i, text, status, '}');
outputEncoded(i, text, status, '[');
outputEncoded(i, text, status, ']');
*/
function outputEncoded(i, text, status, replacement) {
status.bracketStart = i;
status.output += text.substring(status.textStart, status.bracketStart) + replacement;
status.textStart = i + 1;
} |
2807516d2c064ba25b7c27dc711ae21133bfb5af | 8,415 | ts | TypeScript | challenges/day17.ts | Ldoppea/advent-of-code-2020-typescript | 608c15619b9cae3bbc65d2d5d42455710d517221 | [
"MIT"
] | null | null | null | challenges/day17.ts | Ldoppea/advent-of-code-2020-typescript | 608c15619b9cae3bbc65d2d5d42455710d517221 | [
"MIT"
] | null | null | null | challenges/day17.ts | Ldoppea/advent-of-code-2020-typescript | 608c15619b9cae3bbc65d2d5d42455710d517221 | [
"MIT"
] | 1 | 2022-01-28T17:21:42.000Z | 2022-01-28T17:21:42.000Z | interface Point {
x: number,
y: number,
z: number,
value: boolean
}
export const ACTIVE = '#';
export const INACTIVE = '.';
export function getHyperForeigners(pocketDimension: string[][][][], w: number, z: number, x: number, y: number) {
const foreigners: string[] = [];
for (let wi = w-1; wi <= w+1; wi++) {
if (wi < 0 || wi >= pocketDimension.length) {
const sizeZ = 3;
const sizeX = 3;
const sizeY = 3;
const insertedInactive = new Array(sizeZ * sizeX * sizeY).fill(INACTIVE)
foreigners.push(...insertedInactive);
continue;
};
const planZ = pocketDimension[wi];
for (let zi = z-1; zi <= z+1; zi++) {
if (zi < 0 || zi >= pocketDimension[0].length) {
const sizeX = 3;
const sizeY = 3;
const insertedInactive = new Array(sizeX * sizeY).fill(INACTIVE)
foreigners.push(...insertedInactive);
continue;
};
const planX = planZ[zi];
for (let xi = x-1; xi <= x+1; xi++) {
if (xi < 0 || xi >= pocketDimension[0][0].length) {
const sizeY = 3;
const insertedInactive = new Array(sizeY).fill(INACTIVE)
foreigners.push(...insertedInactive);
continue;
};
const planY = planX[xi];
for (let yi = y-1; yi <= y+1; yi++) {
if (yi < 0 || yi >= pocketDimension[0][0][0].length) {
foreigners.push(INACTIVE);
continue;
};
if (x === xi && y === yi && z === zi && w === wi) {
continue;
}
const hypercube = planY[yi];
foreigners.push(hypercube)
}
}
}
}
return foreigners;
}
export function getForeigners(pocketDimension: string[][][], z: number, x: number, y: number) {
const foreigners: string[] = [];
for (let zi = z-1; zi <= z+1; zi++) {
if (zi < 0 || zi >= pocketDimension.length) {
const sizeX = 3;
const sizeY = 3;
const insertedInactive = new Array(sizeX * sizeY).fill(INACTIVE)
foreigners.push(...insertedInactive);
continue;
};
const planX = pocketDimension[zi];
for (let xi = x-1; xi <= x+1; xi++) {
if (xi < 0 || xi >= pocketDimension[0].length) {
const sizeY = 3;
const insertedInactive = new Array(sizeY).fill(INACTIVE)
foreigners.push(...insertedInactive);
continue;
};
const planY = planX[xi];
for (let yi = y-1; yi <= y+1; yi++) {
if (yi < 0 || yi >= pocketDimension[0][0].length) {
foreigners.push(INACTIVE);
continue;
};
if (x === xi && y === yi && z === zi) {
continue;
}
const cube = planY[yi];
foreigners.push(cube)
}
}
}
return foreigners;
}
export function getEmptyYGrow(pocketDimension: string[][][]): string {
return INACTIVE;
}
export function getEmptyXGrow(pocketDimension: string[][][]): string[] {
const y = getEmptyYGrow(pocketDimension);
const x = new Array(pocketDimension[0][0].length + 2).fill(y);
return x;
}
export function getEmptyZGrow(pocketDimension: string[][][]): string[][] {
const x = getEmptyXGrow(pocketDimension);
const z = new Array(pocketDimension[0].length + 2).fill(x);
return z;
}
export function getEmptyHyperYGrow(): string {
return INACTIVE;
}
export function getEmptyHyperXGrow(pocketDimension: string[][][][]): string[] {
const y = getEmptyHyperYGrow();
const x = new Array(pocketDimension[0][0][0].length + 2).fill(y);
return x;
}
export function getEmptyHyperZGrow(pocketDimension: string[][][][]): string[][] {
const x = getEmptyHyperXGrow(pocketDimension);
const z = new Array(pocketDimension[0][0].length + 2).fill(x);
return z;
}
export function getEmptyHyperWGrow(pocketDimension: string[][][][]): string[][][] {
const z = getEmptyHyperZGrow(pocketDimension);
const w = new Array(pocketDimension[0].length + 2).fill(z);
return w;
}
const growPocketDimension = (pocketDimension: string[][][]): string[][][] => {
return [
getEmptyZGrow(pocketDimension),
...pocketDimension.map(planZ => {
return [
getEmptyXGrow(pocketDimension),
...planZ.map(planX => {
return [
getEmptyYGrow(pocketDimension),
...planX,
getEmptyYGrow(pocketDimension)
]
}),
getEmptyXGrow(pocketDimension),
]
}),
getEmptyZGrow(pocketDimension),
]
}
const growPocketHyperDimension = (pocketDimension: string[][][][]): string[][][][] => {
return [
getEmptyHyperWGrow(pocketDimension),
...pocketDimension.map(planW => {
return [
getEmptyHyperZGrow(pocketDimension),
...planW.map(planZ => {
return [
getEmptyHyperXGrow(pocketDimension),
...planZ.map(planX => {
return [
getEmptyHyperYGrow(),
...planX,
getEmptyHyperYGrow()
]
}),
getEmptyHyperXGrow(pocketDimension)
]
}),
getEmptyHyperZGrow(pocketDimension),
]
}),
getEmptyHyperWGrow(pocketDimension),
]
}
export function playCycle(pocketDimension: string[][][]): string[][][] {
const grownPocketDimension = growPocketDimension(pocketDimension);
return grownPocketDimension.map((planZ, z) => {
return planZ.map((planX, x) => {
return planX.map((planY, y) => {
const foreigners = getForeigners(grownPocketDimension, z, x, y);
const numberOfActiveForeigners = foreigners.filter(f => f === ACTIVE).length;
if (planY === ACTIVE && (numberOfActiveForeigners === 2 || numberOfActiveForeigners === 3)) {
return ACTIVE;
} else if (planY === INACTIVE && numberOfActiveForeigners === 3) {
return ACTIVE;
} else {
return INACTIVE;
}
});
});
});
}
export function playHyperCycle(pocketDimension: string[][][][]): string[][][][] {
const grownPocketDimension = growPocketHyperDimension(pocketDimension);
return grownPocketDimension.map((planW, w) => {
return planW.map((planZ, z) => {
return planZ.map((planX, x) => {
return planX.map((planY, y) => {
const foreigners = getHyperForeigners(grownPocketDimension, w, z, x, y);
const numberOfActiveForeigners = foreigners.filter(f => f === ACTIVE).length;
if (planY === ACTIVE && (numberOfActiveForeigners === 2 || numberOfActiveForeigners === 3)) {
return ACTIVE;
} else if (planY === INACTIVE && numberOfActiveForeigners === 3) {
return ACTIVE;
} else {
return INACTIVE;
}
});
});
});
});
}
export function getPocketDimension(input: string[]): string[][][] {
return [
input.map(line => line.split(''))
];
}
const countActives = (pocketDimension: string[][][]) => {
return pocketDimension
.flatMap(z => z)
.flatMap(z => z)
.filter(cube => cube === ACTIVE)
.length;
}
const countHyperActives = (pocketDimension: string[][][][]) => {
return pocketDimension
.flatMap(z => z)
.flatMap(z => z)
.flatMap(z => z)
.filter(cube => cube === ACTIVE)
.length;
}
export function countActiveCubes(input: string[]): number {
const pocketDimension = getPocketDimension(input);
const round1 = playCycle(pocketDimension);
const round2 = playCycle(round1);
const round3 = playCycle(round2);
const round4 = playCycle(round3);
const round5 = playCycle(round4);
const round6 = playCycle(round5);
countActives(pocketDimension);
countActives(round1);
countActives(round2);
countActives(round3);
countActives(round4);
countActives(round5);
countActives(round6);
return countActives(round6);;
}
export function countActiveHypercubes(input: string[]): number {
const pocketDimension = [getPocketDimension(input)];
const round1 = playHyperCycle(pocketDimension);
const round2 = playHyperCycle(round1);
const round3 = playHyperCycle(round2);
const round4 = playHyperCycle(round3);
const round5 = playHyperCycle(round4);
const round6 = playHyperCycle(round5);
countHyperActives(pocketDimension);
countHyperActives(round1);
countHyperActives(round2);
countHyperActives(round3);
countHyperActives(round4);
countHyperActives(round5);
countHyperActives(round6);
return countHyperActives(round6);
} | 28.333333 | 113 | 0.598693 | 254 | 40 | 0 | 53 | 66 | 4 | 16 | 0 | 44 | 1 | 0 | 8.75 | 2,363 | 0.039357 | 0.027931 | 0.001693 | 0.000423 | 0 | 0 | 0.269939 | 0.357854 | interface Point {
x,
y,
z,
value
}
export const ACTIVE = '#';
export const INACTIVE = '.';
export /* Example usages of 'getHyperForeigners' are shown below:
getHyperForeigners(grownPocketDimension, w, z, x, y);
*/
function getHyperForeigners(pocketDimension, w, z, x, y) {
const foreigners = [];
for (let wi = w-1; wi <= w+1; wi++) {
if (wi < 0 || wi >= pocketDimension.length) {
const sizeZ = 3;
const sizeX = 3;
const sizeY = 3;
const insertedInactive = new Array(sizeZ * sizeX * sizeY).fill(INACTIVE)
foreigners.push(...insertedInactive);
continue;
};
const planZ = pocketDimension[wi];
for (let zi = z-1; zi <= z+1; zi++) {
if (zi < 0 || zi >= pocketDimension[0].length) {
const sizeX = 3;
const sizeY = 3;
const insertedInactive = new Array(sizeX * sizeY).fill(INACTIVE)
foreigners.push(...insertedInactive);
continue;
};
const planX = planZ[zi];
for (let xi = x-1; xi <= x+1; xi++) {
if (xi < 0 || xi >= pocketDimension[0][0].length) {
const sizeY = 3;
const insertedInactive = new Array(sizeY).fill(INACTIVE)
foreigners.push(...insertedInactive);
continue;
};
const planY = planX[xi];
for (let yi = y-1; yi <= y+1; yi++) {
if (yi < 0 || yi >= pocketDimension[0][0][0].length) {
foreigners.push(INACTIVE);
continue;
};
if (x === xi && y === yi && z === zi && w === wi) {
continue;
}
const hypercube = planY[yi];
foreigners.push(hypercube)
}
}
}
}
return foreigners;
}
export /* Example usages of 'getForeigners' are shown below:
getForeigners(grownPocketDimension, z, x, y);
*/
function getForeigners(pocketDimension, z, x, y) {
const foreigners = [];
for (let zi = z-1; zi <= z+1; zi++) {
if (zi < 0 || zi >= pocketDimension.length) {
const sizeX = 3;
const sizeY = 3;
const insertedInactive = new Array(sizeX * sizeY).fill(INACTIVE)
foreigners.push(...insertedInactive);
continue;
};
const planX = pocketDimension[zi];
for (let xi = x-1; xi <= x+1; xi++) {
if (xi < 0 || xi >= pocketDimension[0].length) {
const sizeY = 3;
const insertedInactive = new Array(sizeY).fill(INACTIVE)
foreigners.push(...insertedInactive);
continue;
};
const planY = planX[xi];
for (let yi = y-1; yi <= y+1; yi++) {
if (yi < 0 || yi >= pocketDimension[0][0].length) {
foreigners.push(INACTIVE);
continue;
};
if (x === xi && y === yi && z === zi) {
continue;
}
const cube = planY[yi];
foreigners.push(cube)
}
}
}
return foreigners;
}
export /* Example usages of 'getEmptyYGrow' are shown below:
getEmptyYGrow(pocketDimension);
*/
function getEmptyYGrow(pocketDimension) {
return INACTIVE;
}
export /* Example usages of 'getEmptyXGrow' are shown below:
getEmptyXGrow(pocketDimension);
*/
function getEmptyXGrow(pocketDimension) {
const y = getEmptyYGrow(pocketDimension);
const x = new Array(pocketDimension[0][0].length + 2).fill(y);
return x;
}
export /* Example usages of 'getEmptyZGrow' are shown below:
getEmptyZGrow(pocketDimension);
*/
function getEmptyZGrow(pocketDimension) {
const x = getEmptyXGrow(pocketDimension);
const z = new Array(pocketDimension[0].length + 2).fill(x);
return z;
}
export /* Example usages of 'getEmptyHyperYGrow' are shown below:
getEmptyHyperYGrow();
*/
function getEmptyHyperYGrow() {
return INACTIVE;
}
export /* Example usages of 'getEmptyHyperXGrow' are shown below:
getEmptyHyperXGrow(pocketDimension);
*/
function getEmptyHyperXGrow(pocketDimension) {
const y = getEmptyHyperYGrow();
const x = new Array(pocketDimension[0][0][0].length + 2).fill(y);
return x;
}
export /* Example usages of 'getEmptyHyperZGrow' are shown below:
getEmptyHyperZGrow(pocketDimension);
*/
function getEmptyHyperZGrow(pocketDimension) {
const x = getEmptyHyperXGrow(pocketDimension);
const z = new Array(pocketDimension[0][0].length + 2).fill(x);
return z;
}
export /* Example usages of 'getEmptyHyperWGrow' are shown below:
getEmptyHyperWGrow(pocketDimension);
*/
function getEmptyHyperWGrow(pocketDimension) {
const z = getEmptyHyperZGrow(pocketDimension);
const w = new Array(pocketDimension[0].length + 2).fill(z);
return w;
}
/* Example usages of 'growPocketDimension' are shown below:
growPocketDimension(pocketDimension);
*/
const growPocketDimension = (pocketDimension) => {
return [
getEmptyZGrow(pocketDimension),
...pocketDimension.map(planZ => {
return [
getEmptyXGrow(pocketDimension),
...planZ.map(planX => {
return [
getEmptyYGrow(pocketDimension),
...planX,
getEmptyYGrow(pocketDimension)
]
}),
getEmptyXGrow(pocketDimension),
]
}),
getEmptyZGrow(pocketDimension),
]
}
/* Example usages of 'growPocketHyperDimension' are shown below:
growPocketHyperDimension(pocketDimension);
*/
const growPocketHyperDimension = (pocketDimension) => {
return [
getEmptyHyperWGrow(pocketDimension),
...pocketDimension.map(planW => {
return [
getEmptyHyperZGrow(pocketDimension),
...planW.map(planZ => {
return [
getEmptyHyperXGrow(pocketDimension),
...planZ.map(planX => {
return [
getEmptyHyperYGrow(),
...planX,
getEmptyHyperYGrow()
]
}),
getEmptyHyperXGrow(pocketDimension)
]
}),
getEmptyHyperZGrow(pocketDimension),
]
}),
getEmptyHyperWGrow(pocketDimension),
]
}
export /* Example usages of 'playCycle' are shown below:
playCycle(pocketDimension);
playCycle(round1);
playCycle(round2);
playCycle(round3);
playCycle(round4);
playCycle(round5);
*/
function playCycle(pocketDimension) {
const grownPocketDimension = growPocketDimension(pocketDimension);
return grownPocketDimension.map((planZ, z) => {
return planZ.map((planX, x) => {
return planX.map((planY, y) => {
const foreigners = getForeigners(grownPocketDimension, z, x, y);
const numberOfActiveForeigners = foreigners.filter(f => f === ACTIVE).length;
if (planY === ACTIVE && (numberOfActiveForeigners === 2 || numberOfActiveForeigners === 3)) {
return ACTIVE;
} else if (planY === INACTIVE && numberOfActiveForeigners === 3) {
return ACTIVE;
} else {
return INACTIVE;
}
});
});
});
}
export /* Example usages of 'playHyperCycle' are shown below:
playHyperCycle(pocketDimension);
playHyperCycle(round1);
playHyperCycle(round2);
playHyperCycle(round3);
playHyperCycle(round4);
playHyperCycle(round5);
*/
function playHyperCycle(pocketDimension) {
const grownPocketDimension = growPocketHyperDimension(pocketDimension);
return grownPocketDimension.map((planW, w) => {
return planW.map((planZ, z) => {
return planZ.map((planX, x) => {
return planX.map((planY, y) => {
const foreigners = getHyperForeigners(grownPocketDimension, w, z, x, y);
const numberOfActiveForeigners = foreigners.filter(f => f === ACTIVE).length;
if (planY === ACTIVE && (numberOfActiveForeigners === 2 || numberOfActiveForeigners === 3)) {
return ACTIVE;
} else if (planY === INACTIVE && numberOfActiveForeigners === 3) {
return ACTIVE;
} else {
return INACTIVE;
}
});
});
});
});
}
export /* Example usages of 'getPocketDimension' are shown below:
getPocketDimension(input);
*/
function getPocketDimension(input) {
return [
input.map(line => line.split(''))
];
}
/* Example usages of 'countActives' are shown below:
countActives(pocketDimension);
countActives(round1);
countActives(round2);
countActives(round3);
countActives(round4);
countActives(round5);
countActives(round6);
*/
const countActives = (pocketDimension) => {
return pocketDimension
.flatMap(z => z)
.flatMap(z => z)
.filter(cube => cube === ACTIVE)
.length;
}
/* Example usages of 'countHyperActives' are shown below:
countHyperActives(pocketDimension);
countHyperActives(round1);
countHyperActives(round2);
countHyperActives(round3);
countHyperActives(round4);
countHyperActives(round5);
countHyperActives(round6);
*/
const countHyperActives = (pocketDimension) => {
return pocketDimension
.flatMap(z => z)
.flatMap(z => z)
.flatMap(z => z)
.filter(cube => cube === ACTIVE)
.length;
}
export function countActiveCubes(input) {
const pocketDimension = getPocketDimension(input);
const round1 = playCycle(pocketDimension);
const round2 = playCycle(round1);
const round3 = playCycle(round2);
const round4 = playCycle(round3);
const round5 = playCycle(round4);
const round6 = playCycle(round5);
countActives(pocketDimension);
countActives(round1);
countActives(round2);
countActives(round3);
countActives(round4);
countActives(round5);
countActives(round6);
return countActives(round6);;
}
export function countActiveHypercubes(input) {
const pocketDimension = [getPocketDimension(input)];
const round1 = playHyperCycle(pocketDimension);
const round2 = playHyperCycle(round1);
const round3 = playHyperCycle(round2);
const round4 = playHyperCycle(round3);
const round5 = playHyperCycle(round4);
const round6 = playHyperCycle(round5);
countHyperActives(pocketDimension);
countHyperActives(round1);
countHyperActives(round2);
countHyperActives(round3);
countHyperActives(round4);
countHyperActives(round5);
countHyperActives(round6);
return countHyperActives(round6);
} |
2884640349f6f95f654d9799686a927d887d5d9e | 2,918 | ts | TypeScript | problemset/maximal-rectangle/index.ts | OUDUIDUI/leet-code | 50e61ce16d1c419ccefc075ae9ead721cdd1cdbb | [
"MIT"
] | 6 | 2022-01-17T03:19:56.000Z | 2022-01-17T05:45:39.000Z | problemset/maximal-rectangle/index.ts | OUDUIDUI/leet-code | 50e61ce16d1c419ccefc075ae9ead721cdd1cdbb | [
"MIT"
] | null | null | null | problemset/maximal-rectangle/index.ts | OUDUIDUI/leet-code | 50e61ce16d1c419ccefc075ae9ead721cdd1cdbb | [
"MIT"
] | null | null | null | /**
* 暴力解法
* @desc 时间复杂度 O(M^2 * N) 空间复杂度 O(MN)
* @param matrix
*/
export function maximalRectangle(matrix: string[][]): number {
if (matrix.length === 0) return 0
const m = matrix.length
const n = matrix[0].length
/**
* 记录左边连续 "1" 的数量
*
* ['1', '0', '1', '0', '0'], [1, 0, 1, 0, 0],
* ['1', '0', '1', '1', '1'], => [1, 0, 1, 2, 3],
* ['1', '1', '1', '1', '1'], => [1, 2, 3, 4, 5],
* ['1', '0', '0', '1', '0'] [1, 0, 0, 1, 0]
*/
const left: number[][] = new Array(m).fill(0).map(() => new Array(n).fill(0))
for (let i = 0; i < m; i++) {
for (let j = 0; j < n; j++) {
if (matrix[i][j] === '1')
left[i][j] = (j === 0 ? 0 : left[i][j - 1]) + 1
}
}
let ret = 0
for (let i = 0; i < m; i++) {
for (let j = 0; j < n; j++) {
if (matrix[i][j] === '0')
continue
// 初始化宽度和面积
let width = left[i][j]
let area = width
// 从下向上遍历 left 数组,获取最大面积
for (let k = i - 1; k >= 0; k--) {
width = Math.min(width, left[k][j])
area = Math.max(area, (i - k + 1) /* height */ * width)
}
ret = Math.max(ret, area)
}
}
return ret
}
/**
* 单调栈
* @desc 时间复杂度 O(MN) 空间复杂度 O(MN)
* @param matrix
*/
export function maximalRectangle2(matrix: string[][]): number {
if (matrix.length === 0) return 0
const m = matrix.length
const n = matrix[0].length
const left: number[][] = new Array(m).fill(0).map(() => new Array(n).fill(0))
for (let i = 0; i < m; i++) {
for (let j = 0; j < n; j++) {
if (matrix[i][j] === '1')
left[i][j] = (j === 0 ? 0 : left[i][j - 1]) + 1
}
}
let ret = 0
// 横向扫描
for (let j = 0; j < n; j++) {
/**
*
* ['1', '0', '1', '0', '0'],
* ['1', '0', '1', '1', '1'],
* ['1', '1', '1', '1', '1'],
* ['1', '0', '0', '1', '0']
*
* 『 '-'代表对应item为0,高度不重要 』
* 『 对应数值代表对应item向左扩展的最大宽度情况下的最大高度 』
* j = 0 => heights = [4, 4, 4, 4]
* j = 1 => heights = [-, -, 1, -]
* j = 2 => heights = [3, 3, 1, -]
* j = 3 => heights = [-, 3, 1, 3]
* j = 4 => heights = [-, 2, 1, -]
*/
const heights = new Array(m).fill(0)
const stack = []
// 从上到下扫描
for (let i = 0; i < m; i++) {
while (stack.length && left[stack[stack.length - 1]][j] >= left[i][j])
stack.pop()
heights[i] = stack.length === 0 ? -1 : stack[stack.length - 1]
stack.push(i)
}
stack.length = 0
// 从下到上扫描
for (let i = m - 1; i >= 0; i--) {
while (stack.length && left[stack[stack.length - 1]][j] >= left[i][j])
stack.pop()
const down = stack.length === 0 ? m : stack[stack.length - 1]
heights[i] = down - heights[i] - 1
stack.push(i)
}
for (let i = 0; i < m; i++) {
const height = heights[i]
const area = height * left[i][j]
ret = Math.max(ret, area)
}
}
return ret
}
| 25.155172 | 79 | 0.425977 | 64 | 4 | 0 | 2 | 26 | 0 | 0 | 0 | 6 | 0 | 0 | 15.5 | 1,232 | 0.00487 | 0.021104 | 0 | 0 | 0 | 0 | 0.1875 | 0.250173 | /**
* 暴力解法
* @desc 时间复杂度 O(M^2 * N) 空间复杂度 O(MN)
* @param matrix
*/
export function maximalRectangle(matrix) {
if (matrix.length === 0) return 0
const m = matrix.length
const n = matrix[0].length
/**
* 记录左边连续 "1" 的数量
*
* ['1', '0', '1', '0', '0'], [1, 0, 1, 0, 0],
* ['1', '0', '1', '1', '1'], => [1, 0, 1, 2, 3],
* ['1', '1', '1', '1', '1'], => [1, 2, 3, 4, 5],
* ['1', '0', '0', '1', '0'] [1, 0, 0, 1, 0]
*/
const left = new Array(m).fill(0).map(() => new Array(n).fill(0))
for (let i = 0; i < m; i++) {
for (let j = 0; j < n; j++) {
if (matrix[i][j] === '1')
left[i][j] = (j === 0 ? 0 : left[i][j - 1]) + 1
}
}
let ret = 0
for (let i = 0; i < m; i++) {
for (let j = 0; j < n; j++) {
if (matrix[i][j] === '0')
continue
// 初始化宽度和面积
let width = left[i][j]
let area = width
// 从下向上遍历 left 数组,获取最大面积
for (let k = i - 1; k >= 0; k--) {
width = Math.min(width, left[k][j])
area = Math.max(area, (i - k + 1) /* height */ * width)
}
ret = Math.max(ret, area)
}
}
return ret
}
/**
* 单调栈
* @desc 时间复杂度 O(MN) 空间复杂度 O(MN)
* @param matrix
*/
export function maximalRectangle2(matrix) {
if (matrix.length === 0) return 0
const m = matrix.length
const n = matrix[0].length
const left = new Array(m).fill(0).map(() => new Array(n).fill(0))
for (let i = 0; i < m; i++) {
for (let j = 0; j < n; j++) {
if (matrix[i][j] === '1')
left[i][j] = (j === 0 ? 0 : left[i][j - 1]) + 1
}
}
let ret = 0
// 横向扫描
for (let j = 0; j < n; j++) {
/**
*
* ['1', '0', '1', '0', '0'],
* ['1', '0', '1', '1', '1'],
* ['1', '1', '1', '1', '1'],
* ['1', '0', '0', '1', '0']
*
* 『 '-'代表对应item为0,高度不重要 』
* 『 对应数值代表对应item向左扩展的最大宽度情况下的最大高度 』
* j = 0 => heights = [4, 4, 4, 4]
* j = 1 => heights = [-, -, 1, -]
* j = 2 => heights = [3, 3, 1, -]
* j = 3 => heights = [-, 3, 1, 3]
* j = 4 => heights = [-, 2, 1, -]
*/
const heights = new Array(m).fill(0)
const stack = []
// 从上到下扫描
for (let i = 0; i < m; i++) {
while (stack.length && left[stack[stack.length - 1]][j] >= left[i][j])
stack.pop()
heights[i] = stack.length === 0 ? -1 : stack[stack.length - 1]
stack.push(i)
}
stack.length = 0
// 从下到上扫描
for (let i = m - 1; i >= 0; i--) {
while (stack.length && left[stack[stack.length - 1]][j] >= left[i][j])
stack.pop()
const down = stack.length === 0 ? m : stack[stack.length - 1]
heights[i] = down - heights[i] - 1
stack.push(i)
}
for (let i = 0; i < m; i++) {
const height = heights[i]
const area = height * left[i][j]
ret = Math.max(ret, area)
}
}
return ret
}
|
28f3b7ec91c1e4439fb361bb1fdbabf395020e5c | 3,798 | ts | TypeScript | src/common/cache/mongoose-store.ts | Atyantik/nestjs-barebone | ba40bbd15389ba4432eea88b29111180e64ce3b3 | [
"MIT"
] | 1 | 2022-01-24T16:36:34.000Z | 2022-01-24T16:36:34.000Z | src/common/cache/mongoose-store.ts | Atyantik/nestjs-barebone | ba40bbd15389ba4432eea88b29111180e64ce3b3 | [
"MIT"
] | null | null | null | src/common/cache/mongoose-store.ts | Atyantik/nestjs-barebone | ba40bbd15389ba4432eea88b29111180e64ce3b3 | [
"MIT"
] | null | null | null | class MongooseStoreError extends Error {}
class MongooseStore {
mongoose: any;
modelProvider: any;
model: any;
ttl = 0;
constructor(args: any) {
if (!args || !(args.mongoose || args.model)) {
throw new MongooseStoreError(
'you MUST provide either mongoose or model instance in store args',
);
}
this.mongoose = args.mongoose;
this.modelProvider = args.connection || args.mongoose;
if (args.model) {
switch (typeof args.model) {
case 'object':
this.model = args.model;
break;
case 'string':
this.model = this.modelProvider.model(args.model);
break;
default:
throw new MongooseStoreError(
'unexpected type of args.model in constructor',
);
}
} else {
this.model = this.makeModel(args);
}
this.ttl = args.ttl === undefined ? 60 : args.ttl;
}
makeModel(args) {
const schemaTemplate = {
obj: {
_id: String,
val: this.mongoose.Schema.Types.Mixed,
exp: Date,
},
options: {
collection: 'MongooseCache',
versionKey: false,
read: 'secondaryPreferred',
},
};
const options = Object.assign(
{},
schemaTemplate.options,
args.modelOptions,
);
const schema = new this.mongoose.Schema(schemaTemplate.obj, options);
schema.index({ exp: 1 }, { expireAfterSeconds: 0 });
return this.modelProvider.model(args.modelName || 'MongooseCache', schema);
}
result(fn, error = null, result = null) {
if (fn) {
return fn(error, result);
}
if (error) {
return Promise.reject(error);
}
if (result) {
return Promise.resolve(result);
}
}
get(key, options, fn) {
try {
return this.model
.findOne({ _id: key })
.then((record) => {
if (!record) {
return this.result(fn);
}
// this is necessary, since mongoose autoclean is not accurate
if (record.exp && record.exp < new Date()) {
return this.del(key, null, fn);
} else {
return this.result(fn, null, record.val);
}
})
.catch((e) => this.result(fn, e));
} catch (e) {
this.result(fn, e);
}
}
set(key, val, options, fn) {
try {
options = options || {};
const ttl = options.ttl || this.ttl;
const doc: {
val: any;
exp?: Date;
} = { val: val };
if (this.ttl > 0) {
doc.exp = new Date(Date.now() + ttl * 1000);
}
return this.model
.updateOne({ _id: key }, doc, { upsert: true })
.then(() => this.result(fn))
.catch((e) => this.result(fn, e));
} catch (e) {
this.result(fn, e);
}
}
del(key, options, fn) {
try {
return this.model.deleteOne({ _id: key }).then(() => this.result(fn));
} catch (e) {
this.result(fn, e);
}
}
reset(key, fn) {
try {
if ('function' === typeof key) {
fn = key;
key = null;
}
return this.model.deleteMany({}).then(() => {
if (fn) {
fn();
}
});
} catch (e) {
this.result(fn, e);
}
}
keys(fn) {
try {
const now = new Date();
return this.model
.find({})
.then((records) => {
records = records
.filter(function (record) {
return !record.exp || record.exp > now;
})
.map((record) => record._id);
this.result(fn, null, records);
})
.catch((e) => this.result(fn, e));
} catch (e) {
this.result(fn, e);
}
}
}
export const create = function (args) {
return new MongooseStore(args);
};
| 22.473373 | 79 | 0.504739 | 147 | 19 | 0 | 26 | 7 | 4 | 3 | 5 | 0 | 2 | 2 | 7.684211 | 1,035 | 0.043478 | 0.006763 | 0.003865 | 0.001932 | 0.001932 | 0.089286 | 0 | 0.296066 | class MongooseStoreError extends Error {}
class MongooseStore {
mongoose;
modelProvider;
model;
ttl = 0;
constructor(args) {
if (!args || !(args.mongoose || args.model)) {
throw new MongooseStoreError(
'you MUST provide either mongoose or model instance in store args',
);
}
this.mongoose = args.mongoose;
this.modelProvider = args.connection || args.mongoose;
if (args.model) {
switch (typeof args.model) {
case 'object':
this.model = args.model;
break;
case 'string':
this.model = this.modelProvider.model(args.model);
break;
default:
throw new MongooseStoreError(
'unexpected type of args.model in constructor',
);
}
} else {
this.model = this.makeModel(args);
}
this.ttl = args.ttl === undefined ? 60 : args.ttl;
}
makeModel(args) {
const schemaTemplate = {
obj: {
_id: String,
val: this.mongoose.Schema.Types.Mixed,
exp: Date,
},
options: {
collection: 'MongooseCache',
versionKey: false,
read: 'secondaryPreferred',
},
};
const options = Object.assign(
{},
schemaTemplate.options,
args.modelOptions,
);
const schema = new this.mongoose.Schema(schemaTemplate.obj, options);
schema.index({ exp: 1 }, { expireAfterSeconds: 0 });
return this.modelProvider.model(args.modelName || 'MongooseCache', schema);
}
result(fn, error = null, result = null) {
if (fn) {
return fn(error, result);
}
if (error) {
return Promise.reject(error);
}
if (result) {
return Promise.resolve(result);
}
}
get(key, options, fn) {
try {
return this.model
.findOne({ _id: key })
.then((record) => {
if (!record) {
return this.result(fn);
}
// this is necessary, since mongoose autoclean is not accurate
if (record.exp && record.exp < new Date()) {
return this.del(key, null, fn);
} else {
return this.result(fn, null, record.val);
}
})
.catch((e) => this.result(fn, e));
} catch (e) {
this.result(fn, e);
}
}
set(key, val, options, fn) {
try {
options = options || {};
const ttl = options.ttl || this.ttl;
const doc = { val: val };
if (this.ttl > 0) {
doc.exp = new Date(Date.now() + ttl * 1000);
}
return this.model
.updateOne({ _id: key }, doc, { upsert: true })
.then(() => this.result(fn))
.catch((e) => this.result(fn, e));
} catch (e) {
this.result(fn, e);
}
}
del(key, options, fn) {
try {
return this.model.deleteOne({ _id: key }).then(() => this.result(fn));
} catch (e) {
this.result(fn, e);
}
}
reset(key, fn) {
try {
if ('function' === typeof key) {
fn = key;
key = null;
}
return this.model.deleteMany({}).then(() => {
if (fn) {
fn();
}
});
} catch (e) {
this.result(fn, e);
}
}
keys(fn) {
try {
const now = new Date();
return this.model
.find({})
.then((records) => {
records = records
.filter(function (record) {
return !record.exp || record.exp > now;
})
.map((record) => record._id);
this.result(fn, null, records);
})
.catch((e) => this.result(fn, e));
} catch (e) {
this.result(fn, e);
}
}
}
export const create = function (args) {
return new MongooseStore(args);
};
|
8f371ad2f00decfaf97eb1934d1476768a97de33 | 7,119 | ts | TypeScript | challenges/day10.ts | Ldoppea/advent-of-code-2020-typescript | 608c15619b9cae3bbc65d2d5d42455710d517221 | [
"MIT"
] | null | null | null | challenges/day10.ts | Ldoppea/advent-of-code-2020-typescript | 608c15619b9cae3bbc65d2d5d42455710d517221 | [
"MIT"
] | null | null | null | challenges/day10.ts | Ldoppea/advent-of-code-2020-typescript | 608c15619b9cae3bbc65d2d5d42455710d517221 | [
"MIT"
] | 1 | 2022-01-28T17:21:42.000Z | 2022-01-28T17:21:42.000Z | export function getJoltageProduct(input: string[]): number {
const joltages = input.map(line => parseInt(line)).sort((a, b) => a - b);
let numOf1Jolt = 0;
let numOf3Jolt = 1;
joltages.reduce((previous, current) => {
if (current - previous == 1) {
numOf1Jolt++;
}
if (current - previous == 3) {
numOf3Jolt++;
}
return current;
}, 0);
return numOf1Jolt * numOf3Jolt;
}
// Fibonacci de taille 3
const computeSuiteCombinations = (suiteLength: number): number => {
let previous3 = 0;
let previous2 = 0;
let previous1 = 1;
let current = 0;
for (let i = 0; i < suiteLength; i++) {
current = previous3 + previous2 + previous1;
previous3 = previous2;
previous2 = previous1;
previous1 = current;
}
return current;
}
export function getNumberOfDistrinctArrangements(input: string[]): number {
const joltages = input.map(line => parseInt(line)).sort((a, b) => a - b);
let adapters = joltages.map((joltage, index) => {
return index == 0
? joltage
: joltage - joltages[index - 1];
});
// add final adapter
adapters.push(3);
// compute series
let series: number[] = [];
let currentSerie: number = 0;
adapters.forEach(adapter => {
if (adapter === 1) {
currentSerie++;
} else {
series.push(currentSerie);
currentSerie = 0;
}
});
// compute combinations
let numberOfCombinations = series
.filter(serie => serie !== 0)
.reduce((accumulator, currentSerieLength) => {
return accumulator * computeSuiteCombinations(currentSerieLength);
}, 1);
return numberOfCombinations;
}
/*
serie of 1 '1 adapter', cannot remove last -> 0 removable
result = 0
serie of 2 '1 adapter', cannot remove last -> 1 removable
>2<
0
1
result = 2
serie of 3 '1 adapter', cannot remove last -> 2 removables
-->3<--
>2<
00 10
01 11
result = 4
serie of 4 '1 adapter', cannot remove last -> 3 removables
----->4<-----
>3<
000 -> x 100
001 101
010 110
011 111
result = 7
serie of 5 '1 adapter', cannot remove last -> 4 removables
----------------->5<--------------------
->3<- ------>4<------
0000 -> x 0100 1000 -> x 1100
0001 -> x 0101 1001 1101
0010 0110 1010 1110
0011 0111 1011 1111
>2<
result = 13
serie of 6 '1 adapter', cannot remove last -> 5 removables
-------------------------------------------------->6<----------------------------------------------------
->3<- ------>4<------- --------------------->5<---------------------
00000 -> x 00100 01000 -> x 01100 10000 -> x 10100 11000 -> x 11100
00001 -> x 00101 01001 01101 10001 -> x 10101 11001 11101
00010 -> x 00110 01010 01110 10010 10110 11010 11110
00011 -> x 00111 01011 01111 10011 10111 11011 11111
result = 24
serie of 7 '1 adapter', cannot remove last -> 6 removables
-------------------------------------------------------------------------------------------------------->7<-----------------------------------------------------------------------------------------------------------
------->4<------- --------------------->5<--------------------- ------------------------------------------------>6<------------------------------------------------
000000 -> x 000100 -> x 001000 -> x 001100 010000 -> x 010100 011000 -> x 011100 100000 -> x 100100 101000 -> x 101100 110000 -> x 110100 111000 -> x 111100
000001 -> x 000101 -> x 001001 001101 010001 -> x 010101 011001 011101 100001 -> x 100101 101001 101101 110001 -> x 110101 111001 111101
000010 -> x 000110 -> x 001010 001110 010010 010110 011010 011110 100010 -> x 100110 101010 101110 110010 110110 111010 111110
000011 -> x 000111 -> x 001011 001111 010011 010111 011011 011111 100011 -> x 100111 101011 101111 110011 110111 111011 111111
result = 44
serie of 8 '1 adapter', cannot remove last -> 7 removables
----------------------->5<---------------------- ------------------------------------------------>6<------------------------------------------------
0000000 -> x 0000100 -> x 0001000 -> x 0001100 -> x 0010000 -> x 0010100 0011000 -> x 0011100 0100000 -> x 0100100 0101000 -> x 0101100 0110000 -> x 0110100 0111000 -> x 0111100
0000001 -> x 0000101 -> x 0001001 -> x 0001101 -> x 0010001 -> x 0010101 0011001 0011101 0100001 -> x 0100101 0101001 0101101 0110001 -> x 0110101 0111001 0111101
0000010 -> x 0000110 -> x 0001010 -> x 0001110 -> x 0010010 0010110 0011010 0011110 0100010 -> x 0100110 0101010 0101110 0110010 0110110 0111010 0111110
0000011 -> x 0000111 -> x 0001011 -> x 0001111 -> x 0010011 0010111 0011011 0011111 0100011 -> x 0100111 0101011 0101111 0110011 0110111 0111011 0111111
----------------------------------------------------------------------------------------------------------->7<-----------------------------------------------------------------------------------------------------------
1000000 -> x 1000100 -> x 1001000 -> x 1001100 1010000 -> x 1010100 1011000 -> x 1011100 1100000 -> x 1100100 1101000 -> x 1101100 1110000 -> x 1110100 1111000 -> x 1111100
1000001 -> x 1000101 -> x 1001001 1001101 1010001 -> x 1010101 1011001 1011101 1100001 -> x 1100101 1101001 1101101 1110001 -> x 1110101 1111001 1111101
1000010 -> x 1000110 -> x 1001010 1001110 1010010 1010110 1011010 1011110 1100010 -> x 1100110 1101010 1101110 1110010 1110110 1111010 1111110
1000011 -> x 1000111 -> x 1001011 1001111 1010011 1010111 1011011 1011111 1100011 -> x 1100111 1101011 1101111 1110011 1110111 1111011 1111111
result = 81
Suite fibonacci à 3 niveaux:
0 <--- initialisateur - 3
0 <--- initialisateur - 2
1 <--- initialisateur - 1
--- début suite fibonaci
1 <--- 1 + 0 + 0
2 <--- 1 + 1 + 0
4 <--- 2 + 1 + 1
7 <--- 4 + 2 + 1
13 <--- 7 + 4 + 2
24 <--- 13 + 7 + 4
44 <--- 24 + 13 + 7
81 <--- 44 + 24 + 13
*/ | 39.994382 | 217 | 0.447394 | 53 | 12 | 0 | 17 | 14 | 0 | 1 | 0 | 8 | 0 | 0 | 5.75 | 2,928 | 0.009904 | 0.004781 | 0 | 0 | 0 | 0 | 0.186047 | 0.208826 | export function getJoltageProduct(input) {
const joltages = input.map(line => parseInt(line)).sort((a, b) => a - b);
let numOf1Jolt = 0;
let numOf3Jolt = 1;
joltages.reduce((previous, current) => {
if (current - previous == 1) {
numOf1Jolt++;
}
if (current - previous == 3) {
numOf3Jolt++;
}
return current;
}, 0);
return numOf1Jolt * numOf3Jolt;
}
// Fibonacci de taille 3
/* Example usages of 'computeSuiteCombinations' are shown below:
accumulator * computeSuiteCombinations(currentSerieLength);
*/
const computeSuiteCombinations = (suiteLength) => {
let previous3 = 0;
let previous2 = 0;
let previous1 = 1;
let current = 0;
for (let i = 0; i < suiteLength; i++) {
current = previous3 + previous2 + previous1;
previous3 = previous2;
previous2 = previous1;
previous1 = current;
}
return current;
}
export function getNumberOfDistrinctArrangements(input) {
const joltages = input.map(line => parseInt(line)).sort((a, b) => a - b);
let adapters = joltages.map((joltage, index) => {
return index == 0
? joltage
: joltage - joltages[index - 1];
});
// add final adapter
adapters.push(3);
// compute series
let series = [];
let currentSerie = 0;
adapters.forEach(adapter => {
if (adapter === 1) {
currentSerie++;
} else {
series.push(currentSerie);
currentSerie = 0;
}
});
// compute combinations
let numberOfCombinations = series
.filter(serie => serie !== 0)
.reduce((accumulator, currentSerieLength) => {
return accumulator * computeSuiteCombinations(currentSerieLength);
}, 1);
return numberOfCombinations;
}
/*
serie of 1 '1 adapter', cannot remove last -> 0 removable
result = 0
serie of 2 '1 adapter', cannot remove last -> 1 removable
>2<
0
1
result = 2
serie of 3 '1 adapter', cannot remove last -> 2 removables
-->3<--
>2<
00 10
01 11
result = 4
serie of 4 '1 adapter', cannot remove last -> 3 removables
----->4<-----
>3<
000 -> x 100
001 101
010 110
011 111
result = 7
serie of 5 '1 adapter', cannot remove last -> 4 removables
----------------->5<--------------------
->3<- ------>4<------
0000 -> x 0100 1000 -> x 1100
0001 -> x 0101 1001 1101
0010 0110 1010 1110
0011 0111 1011 1111
>2<
result = 13
serie of 6 '1 adapter', cannot remove last -> 5 removables
-------------------------------------------------->6<----------------------------------------------------
->3<- ------>4<------- --------------------->5<---------------------
00000 -> x 00100 01000 -> x 01100 10000 -> x 10100 11000 -> x 11100
00001 -> x 00101 01001 01101 10001 -> x 10101 11001 11101
00010 -> x 00110 01010 01110 10010 10110 11010 11110
00011 -> x 00111 01011 01111 10011 10111 11011 11111
result = 24
serie of 7 '1 adapter', cannot remove last -> 6 removables
-------------------------------------------------------------------------------------------------------->7<-----------------------------------------------------------------------------------------------------------
------->4<------- --------------------->5<--------------------- ------------------------------------------------>6<------------------------------------------------
000000 -> x 000100 -> x 001000 -> x 001100 010000 -> x 010100 011000 -> x 011100 100000 -> x 100100 101000 -> x 101100 110000 -> x 110100 111000 -> x 111100
000001 -> x 000101 -> x 001001 001101 010001 -> x 010101 011001 011101 100001 -> x 100101 101001 101101 110001 -> x 110101 111001 111101
000010 -> x 000110 -> x 001010 001110 010010 010110 011010 011110 100010 -> x 100110 101010 101110 110010 110110 111010 111110
000011 -> x 000111 -> x 001011 001111 010011 010111 011011 011111 100011 -> x 100111 101011 101111 110011 110111 111011 111111
result = 44
serie of 8 '1 adapter', cannot remove last -> 7 removables
----------------------->5<---------------------- ------------------------------------------------>6<------------------------------------------------
0000000 -> x 0000100 -> x 0001000 -> x 0001100 -> x 0010000 -> x 0010100 0011000 -> x 0011100 0100000 -> x 0100100 0101000 -> x 0101100 0110000 -> x 0110100 0111000 -> x 0111100
0000001 -> x 0000101 -> x 0001001 -> x 0001101 -> x 0010001 -> x 0010101 0011001 0011101 0100001 -> x 0100101 0101001 0101101 0110001 -> x 0110101 0111001 0111101
0000010 -> x 0000110 -> x 0001010 -> x 0001110 -> x 0010010 0010110 0011010 0011110 0100010 -> x 0100110 0101010 0101110 0110010 0110110 0111010 0111110
0000011 -> x 0000111 -> x 0001011 -> x 0001111 -> x 0010011 0010111 0011011 0011111 0100011 -> x 0100111 0101011 0101111 0110011 0110111 0111011 0111111
----------------------------------------------------------------------------------------------------------->7<-----------------------------------------------------------------------------------------------------------
1000000 -> x 1000100 -> x 1001000 -> x 1001100 1010000 -> x 1010100 1011000 -> x 1011100 1100000 -> x 1100100 1101000 -> x 1101100 1110000 -> x 1110100 1111000 -> x 1111100
1000001 -> x 1000101 -> x 1001001 1001101 1010001 -> x 1010101 1011001 1011101 1100001 -> x 1100101 1101001 1101101 1110001 -> x 1110101 1111001 1111101
1000010 -> x 1000110 -> x 1001010 1001110 1010010 1010110 1011010 1011110 1100010 -> x 1100110 1101010 1101110 1110010 1110110 1111010 1111110
1000011 -> x 1000111 -> x 1001011 1001111 1010011 1010111 1011011 1011111 1100011 -> x 1100111 1101011 1101111 1110011 1110111 1111011 1111111
result = 81
Suite fibonacci à 3 niveaux:
0 <--- initialisateur - 3
0 <--- initialisateur - 2
1 <--- initialisateur - 1
--- début suite fibonaci
1 <--- 1 + 0 + 0
2 <--- 1 + 1 + 0
4 <--- 2 + 1 + 1
7 <--- 4 + 2 + 1
13 <--- 7 + 4 + 2
24 <--- 13 + 7 + 4
44 <--- 24 + 13 + 7
81 <--- 44 + 24 + 13
*/ |
8fa1ca7bae5daad4472b123a0b76d5f63d63cf52 | 2,301 | ts | TypeScript | src/app/models/ontology-parameter.model.ts | os-climate/sostrades-webgui | 029dc7f13850997fb756991e98c2b6d4d837de51 | [
"MIT",
"Apache-2.0",
"BSD-3-Clause"
] | 1 | 2022-03-16T08:25:41.000Z | 2022-03-16T08:25:41.000Z | src/app/models/ontology-parameter.model.ts | os-climate/sostrades-webgui | 029dc7f13850997fb756991e98c2b6d4d837de51 | [
"MIT",
"Apache-2.0",
"BSD-3-Clause"
] | null | null | null | src/app/models/ontology-parameter.model.ts | os-climate/sostrades-webgui | 029dc7f13850997fb756991e98c2b6d4d837de51 | [
"MIT",
"Apache-2.0",
"BSD-3-Clause"
] | null | null | null | export class OntologyParameter {
constructor(
public id: string,
public datatype: string,
public definition: string,
public label: string,
public quantityKind: string,
public unit: string,
public uri: string,
public definitionSource: string,
public ACLtag: string,
) { }
public static Create(jsonData: any): OntologyParameter {
const result: OntologyParameter = new OntologyParameter(
jsonData[OntologyParameterAttributes.ID],
jsonData[OntologyParameterAttributes.DATATYPE],
jsonData[OntologyParameterAttributes.DEFINITION],
jsonData[OntologyParameterAttributes.LABEL],
jsonData[OntologyParameterAttributes.QUANTITYKIND],
jsonData[OntologyParameterAttributes.UNIT],
jsonData[OntologyParameterAttributes.URI],
jsonData[OntologyParameterAttributes.DEFINITIONSOURCE],
jsonData[OntologyParameterAttributes.ACLTAG]);
return result;
}
public static getKeyLabel(key: string): string {
const keyLabelDict = {
id: 'ID',
datatype: 'Datatype',
definition: 'Definition',
label: 'Label',
quantityKind: 'Quantity Kind',
unit: 'Unit',
uri: 'URI',
definitionSource: 'Definition Source',
ACLtag: 'Airbus Common Language Tag'
};
if (key in keyLabelDict) {
return keyLabelDict[key];
} else {
return key;
}
}
public toString = (): string => {
const strings: string[] = [];
if (this.id !== null && this.id !== undefined) {
strings.push(`${this.id}`);
}
if (this.definition !== null && this.definition !== undefined) {
strings.push(`${this.definition}`);
}
if (this.uri !== null && this.uri !== undefined) {
strings.push(`${this.uri}`);
}
if (this.definitionSource !== null && this.definitionSource !== undefined) {
strings.push(`${this.definitionSource}`);
}
if (this.ACLtag !== null && this.ACLtag !== undefined) {
strings.push(`${this.ACLtag}`);
}
return strings.join('\n');
}
}
export enum OntologyParameterAttributes {
ID = 'id',
DATATYPE = 'datatype',
DEFINITION = 'definition',
LABEL = 'label',
QUANTITYKIND = 'quantityKind',
UNIT = 'unit',
URI = 'uri',
DEFINITIONSOURCE = 'definitionSource',
ACLTAG = 'ACLTag'
}
| 28.060976 | 80 | 0.644502 | 74 | 4 | 0 | 11 | 3 | 1 | 0 | 1 | 13 | 1 | 0 | 11 | 552 | 0.027174 | 0.005435 | 0.001812 | 0.001812 | 0 | 0.052632 | 0.684211 | 0.252606 | export class OntologyParameter {
constructor(
public id,
public datatype,
public definition,
public label,
public quantityKind,
public unit,
public uri,
public definitionSource,
public ACLtag,
) { }
public static Create(jsonData) {
const result = new OntologyParameter(
jsonData[OntologyParameterAttributes.ID],
jsonData[OntologyParameterAttributes.DATATYPE],
jsonData[OntologyParameterAttributes.DEFINITION],
jsonData[OntologyParameterAttributes.LABEL],
jsonData[OntologyParameterAttributes.QUANTITYKIND],
jsonData[OntologyParameterAttributes.UNIT],
jsonData[OntologyParameterAttributes.URI],
jsonData[OntologyParameterAttributes.DEFINITIONSOURCE],
jsonData[OntologyParameterAttributes.ACLTAG]);
return result;
}
public static getKeyLabel(key) {
const keyLabelDict = {
id: 'ID',
datatype: 'Datatype',
definition: 'Definition',
label: 'Label',
quantityKind: 'Quantity Kind',
unit: 'Unit',
uri: 'URI',
definitionSource: 'Definition Source',
ACLtag: 'Airbus Common Language Tag'
};
if (key in keyLabelDict) {
return keyLabelDict[key];
} else {
return key;
}
}
public toString = () => {
const strings = [];
if (this.id !== null && this.id !== undefined) {
strings.push(`${this.id}`);
}
if (this.definition !== null && this.definition !== undefined) {
strings.push(`${this.definition}`);
}
if (this.uri !== null && this.uri !== undefined) {
strings.push(`${this.uri}`);
}
if (this.definitionSource !== null && this.definitionSource !== undefined) {
strings.push(`${this.definitionSource}`);
}
if (this.ACLtag !== null && this.ACLtag !== undefined) {
strings.push(`${this.ACLtag}`);
}
return strings.join('\n');
}
}
export enum OntologyParameterAttributes {
ID = 'id',
DATATYPE = 'datatype',
DEFINITION = 'definition',
LABEL = 'label',
QUANTITYKIND = 'quantityKind',
UNIT = 'unit',
URI = 'uri',
DEFINITIONSOURCE = 'definitionSource',
ACLTAG = 'ACLTag'
}
|
ba2f66ff06864a4b9fdbbaa066f7700640b957b6 | 1,798 | ts | TypeScript | problemset/find-right-interval/index.ts | OUDUIDUI/leet-code | 50e61ce16d1c419ccefc075ae9ead721cdd1cdbb | [
"MIT"
] | 6 | 2022-01-17T03:19:56.000Z | 2022-01-17T05:45:39.000Z | problemset/find-right-interval/index.ts | OUDUIDUI/leet-code | 50e61ce16d1c419ccefc075ae9ead721cdd1cdbb | [
"MIT"
] | null | null | null | problemset/find-right-interval/index.ts | OUDUIDUI/leet-code | 50e61ce16d1c419ccefc075ae9ead721cdd1cdbb | [
"MIT"
] | null | null | null | /**
* 二分法
* @desc 时间复杂度 O(NlogN) 空间复杂度 O(N)
* @param intervals
* @returns
*/
export function findRightInterval(intervals: number[][]): number[] {
const len = intervals.length
if (len <= 1) return [-1]
const startIntervals: [startNum: number, index: number][]
= new Array(len).fill([]).map(() => [0, 0])
for (let i = 0; i < len; i++) {
startIntervals[i][0] = intervals[i][0]
startIntervals[i][1] = i
}
startIntervals.sort((a, b) => a[0] - b[0])
const ans: number[] = []
for (let i = 0; i < len; i++) {
let left = 0
let right = len - 1
let target = -1
while (left <= right) {
const mid = (left + right) >> 1
if (startIntervals[mid][0] >= intervals[i][1]) {
target = startIntervals[mid][1]
right = mid - 1
}
else {
left = mid + 1
}
}
ans[i] = target
}
return ans
}
/**
* 双指针
* @desc 时间复杂度 O(NlogN) 空间复杂度 O(N)
* @param intervals
* @returns
*/
export function findRightInterval2(intervals: number[][]): number[] {
const len = intervals.length
if (len <= 1) return [-1]
const startIntervals: [startNum: number, index: number][]
= new Array(len).fill([]).map(() => [0, 0])
const endIntervals: [endNum: number, index: number][]
= new Array(len).fill([]).map(() => [0, 0])
for (let i = 0; i < len; i++) {
startIntervals[i][0] = intervals[i][0]
startIntervals[i][1] = i
endIntervals[i][0] = intervals[i][1]
endIntervals[i][1] = i
}
startIntervals.sort((a, b) => a[0] - b[0])
endIntervals.sort((a, b) => a[0] - b[0])
const ans: number[] = []
for (let i = 0, j = 0; i < len; i++) {
while (j < len && endIntervals[i][0] > startIntervals[j][0]) j++
ans[endIntervals[i][1]] = j < len ? startIntervals[j][1] : -1
}
return ans
}
| 23.051282 | 69 | 0.545606 | 51 | 8 | 0 | 8 | 16 | 0 | 0 | 0 | 12 | 0 | 0 | 6.625 | 650 | 0.024615 | 0.024615 | 0 | 0 | 0 | 0 | 0.375 | 0.307589 | /**
* 二分法
* @desc 时间复杂度 O(NlogN) 空间复杂度 O(N)
* @param intervals
* @returns
*/
export function findRightInterval(intervals) {
const len = intervals.length
if (len <= 1) return [-1]
const startIntervals
= new Array(len).fill([]).map(() => [0, 0])
for (let i = 0; i < len; i++) {
startIntervals[i][0] = intervals[i][0]
startIntervals[i][1] = i
}
startIntervals.sort((a, b) => a[0] - b[0])
const ans = []
for (let i = 0; i < len; i++) {
let left = 0
let right = len - 1
let target = -1
while (left <= right) {
const mid = (left + right) >> 1
if (startIntervals[mid][0] >= intervals[i][1]) {
target = startIntervals[mid][1]
right = mid - 1
}
else {
left = mid + 1
}
}
ans[i] = target
}
return ans
}
/**
* 双指针
* @desc 时间复杂度 O(NlogN) 空间复杂度 O(N)
* @param intervals
* @returns
*/
export function findRightInterval2(intervals) {
const len = intervals.length
if (len <= 1) return [-1]
const startIntervals
= new Array(len).fill([]).map(() => [0, 0])
const endIntervals
= new Array(len).fill([]).map(() => [0, 0])
for (let i = 0; i < len; i++) {
startIntervals[i][0] = intervals[i][0]
startIntervals[i][1] = i
endIntervals[i][0] = intervals[i][1]
endIntervals[i][1] = i
}
startIntervals.sort((a, b) => a[0] - b[0])
endIntervals.sort((a, b) => a[0] - b[0])
const ans = []
for (let i = 0, j = 0; i < len; i++) {
while (j < len && endIntervals[i][0] > startIntervals[j][0]) j++
ans[endIntervals[i][1]] = j < len ? startIntervals[j][1] : -1
}
return ans
}
|
baccc8dbf76971289cc447efa5374259c88f18f3 | 2,172 | ts | TypeScript | problemset/surrounded-regions/index.ts | OUDUIDUI/leet-code | 50e61ce16d1c419ccefc075ae9ead721cdd1cdbb | [
"MIT"
] | 6 | 2022-01-17T03:19:56.000Z | 2022-01-17T05:45:39.000Z | problemset/surrounded-regions/index.ts | OUDUIDUI/leet-code | 50e61ce16d1c419ccefc075ae9ead721cdd1cdbb | [
"MIT"
] | null | null | null | problemset/surrounded-regions/index.ts | OUDUIDUI/leet-code | 50e61ce16d1c419ccefc075ae9ead721cdd1cdbb | [
"MIT"
] | null | null | null | /**
* 深度优先搜索
* @desc 时间复杂度 O(MN) 空间复杂度 O(MN)
* @param board
*/
export function solve(board: string[][]): void {
const m = board.length
if (m === 0) return
const n = board[0].length
if (n === 0) return
// 从最外圈向内寻找
let i
for (i = 0; i < m; i++) {
dfs(board, i, 0)
dfs(board, i, n - 1)
}
for (i = 1; i < n - 1; i++) {
dfs(board, 0, i)
dfs(board, m - 1, i)
}
// 将O换成X,将A换成O
for (i = 0; i < m; i++) {
for (let j = 0; j < n; j++) {
if (board[i][j] === 'A')
board[i][j] = 'O'
else if (board[i][j] === 'O')
board[i][j] = 'X'
}
}
function dfs(board: string[][], x: number, y: number) {
if (x < 0 || x >= m || y < 0 || y >= n || board[x][y] !== 'O') return
board[x][y] = 'A'
dfs(board, x + 1, y)
dfs(board, x - 1, y)
dfs(board, x, y + 1)
dfs(board, x, y - 1)
}
}
/**
* 广度优先搜索
* @desc 时间复杂度 O(MN) 空间复杂度 O(MN)
* @param board
*/
export function solve2(board: string[][]): void {
const m = board.length
if (m === 0) return
const n = board[0].length
if (n === 0) return
const queue: [number, number][] = []
for (let i = 0; i < m; i++) {
if (board[i][0] === 'O') {
queue.unshift([i, 0])
board[i][0] = 'A'
}
if (board[i][n - 1] === 'O') {
queue.unshift([i, n - 1])
board[i][n - 1] = 'A'
}
}
for (let i = 1; i < n - 1; i++) {
if (board[0][i] === 'O') {
queue.unshift([0, i])
board[0][i] = 'A'
}
if (board[m - 1][i] === 'O') {
queue.unshift([m - 1, i])
board[m - 1][i] = 'A'
}
}
const dirs = [
[0, 1],
[1, 0],
[0, -1],
[-1, 0],
]
while (queue.length) {
const [x, y] = queue.pop()!
for (const dir of dirs) {
const mx = x + dir[0]
const my = y + dir[1]
if (mx < 0 || mx >= m || my < 0 || my >= n || board[mx][my] !== 'O')
continue
queue.unshift([mx, my])
board[mx][my] = 'A'
}
}
// 将O换成X,将A换成O
for (let i = 0; i < m; i++) {
for (let j = 0; j < n; j++) {
if (board[i][j] === 'A')
board[i][j] = 'O'
else if (board[i][j] === 'O')
board[i][j] = 'X'
}
}
}
| 19.926606 | 74 | 0.414825 | 83 | 3 | 0 | 5 | 15 | 0 | 1 | 0 | 9 | 0 | 0 | 28.333333 | 937 | 0.008538 | 0.016009 | 0 | 0 | 0 | 0 | 0.391304 | 0.242162 | /**
* 深度优先搜索
* @desc 时间复杂度 O(MN) 空间复杂度 O(MN)
* @param board
*/
export function solve(board) {
const m = board.length
if (m === 0) return
const n = board[0].length
if (n === 0) return
// 从最外圈向内寻找
let i
for (i = 0; i < m; i++) {
dfs(board, i, 0)
dfs(board, i, n - 1)
}
for (i = 1; i < n - 1; i++) {
dfs(board, 0, i)
dfs(board, m - 1, i)
}
// 将O换成X,将A换成O
for (i = 0; i < m; i++) {
for (let j = 0; j < n; j++) {
if (board[i][j] === 'A')
board[i][j] = 'O'
else if (board[i][j] === 'O')
board[i][j] = 'X'
}
}
/* Example usages of 'dfs' are shown below:
dfs(board, i, 0);
dfs(board, i, n - 1);
dfs(board, 0, i);
dfs(board, m - 1, i);
dfs(board, x + 1, y);
dfs(board, x - 1, y);
dfs(board, x, y + 1);
dfs(board, x, y - 1);
*/
function dfs(board, x, y) {
if (x < 0 || x >= m || y < 0 || y >= n || board[x][y] !== 'O') return
board[x][y] = 'A'
dfs(board, x + 1, y)
dfs(board, x - 1, y)
dfs(board, x, y + 1)
dfs(board, x, y - 1)
}
}
/**
* 广度优先搜索
* @desc 时间复杂度 O(MN) 空间复杂度 O(MN)
* @param board
*/
export function solve2(board) {
const m = board.length
if (m === 0) return
const n = board[0].length
if (n === 0) return
const queue = []
for (let i = 0; i < m; i++) {
if (board[i][0] === 'O') {
queue.unshift([i, 0])
board[i][0] = 'A'
}
if (board[i][n - 1] === 'O') {
queue.unshift([i, n - 1])
board[i][n - 1] = 'A'
}
}
for (let i = 1; i < n - 1; i++) {
if (board[0][i] === 'O') {
queue.unshift([0, i])
board[0][i] = 'A'
}
if (board[m - 1][i] === 'O') {
queue.unshift([m - 1, i])
board[m - 1][i] = 'A'
}
}
const dirs = [
[0, 1],
[1, 0],
[0, -1],
[-1, 0],
]
while (queue.length) {
const [x, y] = queue.pop()!
for (const dir of dirs) {
const mx = x + dir[0]
const my = y + dir[1]
if (mx < 0 || mx >= m || my < 0 || my >= n || board[mx][my] !== 'O')
continue
queue.unshift([mx, my])
board[mx][my] = 'A'
}
}
// 将O换成X,将A换成O
for (let i = 0; i < m; i++) {
for (let j = 0; j < n; j++) {
if (board[i][j] === 'A')
board[i][j] = 'O'
else if (board[i][j] === 'O')
board[i][j] = 'X'
}
}
}
|
bafcc75ee18216e097532600ba0afdf1af8532af | 9,312 | ts | TypeScript | nutuml-core/src/sequence/SeqLexical.ts | nutuml/nutuml | 92b216baf1861c78f46ad623548228ac9e2cb2d6 | [
"MIT"
] | 3 | 2022-02-09T09:22:52.000Z | 2022-02-10T07:58:36.000Z | nutuml-core/src/sequence/SeqLexical.ts | nutuml/nutuml | 92b216baf1861c78f46ad623548228ac9e2cb2d6 | [
"MIT"
] | null | null | null | nutuml-core/src/sequence/SeqLexical.ts | nutuml/nutuml | 92b216baf1861c78f46ad623548228ac9e2cb2d6 | [
"MIT"
] | null | null | null |
const separators = [':'];
const newLines = ['\r','\n'];
const reservedWords = ['hide','autonumber','as', 'participant', 'actor', 'boundary',
'control', 'entity', 'database', 'collections','title','header','footer',
'alt','else','opt','loop','par','break','critical','group','end','note',
'left','right','of','over','ref','activate','deactivate','destroy','box','skinparam'];
const oneLineWords = ['title','header','footer','alt','else','opt','loop','par','break','critical','group'];
const multiLineWords = ['title','note','ref'];
const operators = ['-','>','<','->', '-->','<-','<--'];
const TYPE_RESERVED = 1;
const TYPE_WORD = 2;
const TYPE_MESSAGE = 3;
const TYPE_OPERATOR = 4;
const TYPE_SEPARATORS = 5;
const TYPE_STRING = 6;
const TYPE_SEPARATE_LINE = 7;
const TYPE_COMMA = 8;
const TYPE_DELAY = 9;
const TYPE_SPACE =10;
function isWordChar(c:string){
var result = /[a-z0-9]/i.test(c);
if(result){
return result;
}
if(c=='#' || c=='[' || c==']'){
return true;
}
return c.charCodeAt(0)>255;
}
export function analysis(str: string) {
/**
* current用于标识当前字符位置,
* str[cur]即为当前字符
*/
let cur = 0;
/**
* tokens存储词法分析的最终结果
*/
let tokens = [];
var multiLineFlag = false;
var multiLine = false;
var curLine =1;
while(cur < str.length) {
if(newLines.indexOf(str[cur])!==-1 && multiLineFlag ==true){
multiLine = true
curLine++
multiLineFlag = false
cur++
}
if(multiLine){
// handle multiline message until of 'end' at begin of line
var message = "";
var lineStart = true;
var multiStart = curLine;
while(cur < str.length){
if(lineStart){
if(isWordChar(str[cur])) { // 读单词
let word = "" + str[cur++];
// 测试下一位字符,如果不是字母直接进入下一次循环(此时cur已经右移)
// 如果是则继续读字母,并将cur向右移动
while(cur < str.length && isWordChar(str[cur])) {
// cur < str.length防止越界
word += str[cur++];
}
if("end"==word){
multiLine = false;
tokens.push({
type: TYPE_MESSAGE,
value: message.trim(),
line: multiStart
});
tokens.push({
type: TYPE_RESERVED,
value: word,
line: curLine
});
break;
}else{
message += word
lineStart = false;
}
}else{
message += str[cur++]
}
}else{
if(newLines.indexOf(str[cur])!==-1){
lineStart = true;
curLine++
}
message += str[cur++]
}
}
multiLine = false
}
if(/\s/.test(str[cur])) { // 跳过空格
if(str[cur]=='\n'){
curLine++;
}
cur++;
} else if(isWordChar(str[cur])) { // 读单词
let word = "" + str[cur++];
// 测试下一位字符,如果不是字母直接进入下一次循环(此时cur已经右移)
// 如果是则继续读字母,并将cur向右移动
while(cur < str.length && isWordChar(str[cur])) {
// cur < str.length防止越界
word += str[cur++];
}
if(reservedWords.indexOf(word)!==-1) {
tokens.push({
type: TYPE_RESERVED,
value: word,
line: curLine
}); // 存储保留字(关键字)
if(multiLineWords.indexOf(word)!==-1){
if(tokens.length<2 || tokens[tokens.length-2].value!="end"){
multiLineFlag = true;
}
}
if(oneLineWords.indexOf(word)!==-1){
while(cur<str.length && /\s/.test(str[cur]) && newLines.indexOf(str[cur])==-1){
cur++;
}
var tempWord = "";
while(cur < str.length && newLines.indexOf(str[cur])==-1) {
tempWord += str[cur++];
multiLineFlag = false;
}
tokens.push({
type: TYPE_MESSAGE,
value: tempWord,
line: curLine
})
}
} else {
tokens.push({
type: TYPE_WORD,
value: word,
line: curLine
}); // 存储普通单词
}
} else if(separators.indexOf(str[cur])!==-1) {
multiLineFlag = false
tokens.push({
type: TYPE_SEPARATORS,
value: str[cur++],
line: curLine
}); // 存储分隔符并将cur向右移动
let word = "";
while(cur < str.length && " " == str[cur]){
cur++;
}
// 测试下一位字符,如果是换行进入下一次循环
// 如果不是则继续读字符,并将cur向右移动
while(cur < str.length && newLines.indexOf(str[cur])==-1) {
word += str[cur++];
}
word = word.replace(/\\n/g,"\n")
tokens.push({
type: TYPE_MESSAGE,
value: word,
line: curLine
});
} else if(','==str[cur]) {
tokens.push({
type: TYPE_COMMA,
value: str[cur++],
line: curLine
}); // 存储分隔符并将cur向右移动
} else if('.'==str[cur]) {
var message = "";
if(cur+2 < str.length && '.'==str[cur+1] && '.'==str[cur+2]) {
cur=cur+3;
while(cur<str.length){
if('.'==str[cur] && cur+2 < str.length && '.'==str[cur+1] && '.'==str[cur+2]){
cur=cur+3
break;
}
if('\n'==str[cur]){
break;
}
message += str[cur++]
}
}else{
return "syntax error"
}
tokens.push({
type: TYPE_DELAY,
value: message,
line: curLine
}); // 存储分隔符并将cur向右移动
}else if('|'==str[cur]) {
var message = "";
if(cur+2 < str.length && '|'==str[cur+1] && '|'==str[cur+2]) {
// match |||
cur=cur+3;
}else if(cur +1<str.length && '|'==str[cur+1]){
cur+=2;
while(cur<str.length){
if('|'==str[cur] && cur+1 < str.length && '|'==str[cur+1]){
cur=cur+2
break;
}
if('\n'==str[cur]){
break;
}
message += str[cur++]
}
}else{
return "syntax error"
}
tokens.push({
type: TYPE_SPACE,
value: message,
line: curLine
}); // 存储分隔符并将cur向右移动
} else if(operators.indexOf(str[cur])!==-1) {
let operator = "" + str[cur++];
while(cur < str.length && operators.indexOf(str[cur])!==-1) {
operator += str[cur++];
}
tokens.push({
type: TYPE_OPERATOR,
value: operator,
line: curLine
}); // 存储运算符
} else if('"'==str[cur]){
let operator = "";
cur++;
while(cur < str.length) {
var c = str[cur++];
if('"'==c)break;
operator += c;
}
operator = operator.replace("\\n","\n")
tokens.push({
type: TYPE_STRING,
value: operator,
line: curLine
});
} else if('='==str[cur]){
cur++;
if('='==str[cur]){
var message = "";
cur++
while(cur < str.length) {
var c = str[cur++];
if('='==c && cur<str.length && str[cur]=='='){
cur++;
break;
}
message += c;
}
tokens.push({
type: TYPE_SEPARATE_LINE,
value: message,
line: curLine
});
}else{
return "syntax error"
}
}else {
return "syntax error:" + str[cur];
}
}
return tokens;
} | 34.10989 | 108 | 0.363402 | 249 | 2 | 0 | 2 | 36 | 0 | 1 | 0 | 2 | 0 | 0 | 113 | 2,131 | 0.001877 | 0.016893 | 0 | 0 | 0 | 0 | 0.05 | 0.230298 |
const separators = [':'];
const newLines = ['\r','\n'];
const reservedWords = ['hide','autonumber','as', 'participant', 'actor', 'boundary',
'control', 'entity', 'database', 'collections','title','header','footer',
'alt','else','opt','loop','par','break','critical','group','end','note',
'left','right','of','over','ref','activate','deactivate','destroy','box','skinparam'];
const oneLineWords = ['title','header','footer','alt','else','opt','loop','par','break','critical','group'];
const multiLineWords = ['title','note','ref'];
const operators = ['-','>','<','->', '-->','<-','<--'];
const TYPE_RESERVED = 1;
const TYPE_WORD = 2;
const TYPE_MESSAGE = 3;
const TYPE_OPERATOR = 4;
const TYPE_SEPARATORS = 5;
const TYPE_STRING = 6;
const TYPE_SEPARATE_LINE = 7;
const TYPE_COMMA = 8;
const TYPE_DELAY = 9;
const TYPE_SPACE =10;
/* Example usages of 'isWordChar' are shown below:
isWordChar(str[cur]);
cur < str.length && isWordChar(str[cur]);
*/
function isWordChar(c){
var result = /[a-z0-9]/i.test(c);
if(result){
return result;
}
if(c=='#' || c=='[' || c==']'){
return true;
}
return c.charCodeAt(0)>255;
}
export function analysis(str) {
/**
* current用于标识当前字符位置,
* str[cur]即为当前字符
*/
let cur = 0;
/**
* tokens存储词法分析的最终结果
*/
let tokens = [];
var multiLineFlag = false;
var multiLine = false;
var curLine =1;
while(cur < str.length) {
if(newLines.indexOf(str[cur])!==-1 && multiLineFlag ==true){
multiLine = true
curLine++
multiLineFlag = false
cur++
}
if(multiLine){
// handle multiline message until of 'end' at begin of line
var message = "";
var lineStart = true;
var multiStart = curLine;
while(cur < str.length){
if(lineStart){
if(isWordChar(str[cur])) { // 读单词
let word = "" + str[cur++];
// 测试下一位字符,如果不是字母直接进入下一次循环(此时cur已经右移)
// 如果是则继续读字母,并将cur向右移动
while(cur < str.length && isWordChar(str[cur])) {
// cur < str.length防止越界
word += str[cur++];
}
if("end"==word){
multiLine = false;
tokens.push({
type: TYPE_MESSAGE,
value: message.trim(),
line: multiStart
});
tokens.push({
type: TYPE_RESERVED,
value: word,
line: curLine
});
break;
}else{
message += word
lineStart = false;
}
}else{
message += str[cur++]
}
}else{
if(newLines.indexOf(str[cur])!==-1){
lineStart = true;
curLine++
}
message += str[cur++]
}
}
multiLine = false
}
if(/\s/.test(str[cur])) { // 跳过空格
if(str[cur]=='\n'){
curLine++;
}
cur++;
} else if(isWordChar(str[cur])) { // 读单词
let word = "" + str[cur++];
// 测试下一位字符,如果不是字母直接进入下一次循环(此时cur已经右移)
// 如果是则继续读字母,并将cur向右移动
while(cur < str.length && isWordChar(str[cur])) {
// cur < str.length防止越界
word += str[cur++];
}
if(reservedWords.indexOf(word)!==-1) {
tokens.push({
type: TYPE_RESERVED,
value: word,
line: curLine
}); // 存储保留字(关键字)
if(multiLineWords.indexOf(word)!==-1){
if(tokens.length<2 || tokens[tokens.length-2].value!="end"){
multiLineFlag = true;
}
}
if(oneLineWords.indexOf(word)!==-1){
while(cur<str.length && /\s/.test(str[cur]) && newLines.indexOf(str[cur])==-1){
cur++;
}
var tempWord = "";
while(cur < str.length && newLines.indexOf(str[cur])==-1) {
tempWord += str[cur++];
multiLineFlag = false;
}
tokens.push({
type: TYPE_MESSAGE,
value: tempWord,
line: curLine
})
}
} else {
tokens.push({
type: TYPE_WORD,
value: word,
line: curLine
}); // 存储普通单词
}
} else if(separators.indexOf(str[cur])!==-1) {
multiLineFlag = false
tokens.push({
type: TYPE_SEPARATORS,
value: str[cur++],
line: curLine
}); // 存储分隔符并将cur向右移动
let word = "";
while(cur < str.length && " " == str[cur]){
cur++;
}
// 测试下一位字符,如果是换行进入下一次循环
// 如果不是则继续读字符,并将cur向右移动
while(cur < str.length && newLines.indexOf(str[cur])==-1) {
word += str[cur++];
}
word = word.replace(/\\n/g,"\n")
tokens.push({
type: TYPE_MESSAGE,
value: word,
line: curLine
});
} else if(','==str[cur]) {
tokens.push({
type: TYPE_COMMA,
value: str[cur++],
line: curLine
}); // 存储分隔符并将cur向右移动
} else if('.'==str[cur]) {
var message = "";
if(cur+2 < str.length && '.'==str[cur+1] && '.'==str[cur+2]) {
cur=cur+3;
while(cur<str.length){
if('.'==str[cur] && cur+2 < str.length && '.'==str[cur+1] && '.'==str[cur+2]){
cur=cur+3
break;
}
if('\n'==str[cur]){
break;
}
message += str[cur++]
}
}else{
return "syntax error"
}
tokens.push({
type: TYPE_DELAY,
value: message,
line: curLine
}); // 存储分隔符并将cur向右移动
}else if('|'==str[cur]) {
var message = "";
if(cur+2 < str.length && '|'==str[cur+1] && '|'==str[cur+2]) {
// match |||
cur=cur+3;
}else if(cur +1<str.length && '|'==str[cur+1]){
cur+=2;
while(cur<str.length){
if('|'==str[cur] && cur+1 < str.length && '|'==str[cur+1]){
cur=cur+2
break;
}
if('\n'==str[cur]){
break;
}
message += str[cur++]
}
}else{
return "syntax error"
}
tokens.push({
type: TYPE_SPACE,
value: message,
line: curLine
}); // 存储分隔符并将cur向右移动
} else if(operators.indexOf(str[cur])!==-1) {
let operator = "" + str[cur++];
while(cur < str.length && operators.indexOf(str[cur])!==-1) {
operator += str[cur++];
}
tokens.push({
type: TYPE_OPERATOR,
value: operator,
line: curLine
}); // 存储运算符
} else if('"'==str[cur]){
let operator = "";
cur++;
while(cur < str.length) {
var c = str[cur++];
if('"'==c)break;
operator += c;
}
operator = operator.replace("\\n","\n")
tokens.push({
type: TYPE_STRING,
value: operator,
line: curLine
});
} else if('='==str[cur]){
cur++;
if('='==str[cur]){
var message = "";
cur++
while(cur < str.length) {
var c = str[cur++];
if('='==c && cur<str.length && str[cur]=='='){
cur++;
break;
}
message += c;
}
tokens.push({
type: TYPE_SEPARATE_LINE,
value: message,
line: curLine
});
}else{
return "syntax error"
}
}else {
return "syntax error:" + str[cur];
}
}
return tokens;
} |
b74b137fa72db2988455ca15ece46e084f4ad5d2 | 1,818 | ts | TypeScript | packages/snap-url-manager/src/UrlManager/typecheck.ts | searchspring/snap | 050a3e8e94678c61db77c597e20bab6e9492bc4f | [
"MIT"
] | 4 | 2022-02-10T20:10:47.000Z | 2022-03-16T15:12:33.000Z | packages/snap-url-manager/src/UrlManager/typecheck.ts | searchspring/snap | 050a3e8e94678c61db77c597e20bab6e9492bc4f | [
"MIT"
] | 86 | 2022-02-01T20:51:18.000Z | 2022-03-31T21:20:13.000Z | packages/snap-url-manager/src/UrlManager/typecheck.ts | searchspring/snap | 050a3e8e94678c61db77c597e20bab6e9492bc4f | [
"MIT"
] | null | null | null | export function checkStateRangeValue(value: Record<string, unknown>): boolean {
if (typeof value != 'object') {
return false;
}
if (typeof value.low != 'number' && value.low !== undefined) {
return false;
}
if (typeof value.high != 'number' && value.high !== undefined) {
return false;
}
if (typeof value.low != 'number' && typeof value.high != 'number') {
// at least one must be defined
return true;
}
return true;
}
export function checkStateFilter(filters: Record<string, Array<unknown>>): boolean {
for (const key of Object.keys(filters)) {
if (typeof key !== 'string') {
return false;
}
const fieldFilter = filters[key];
const invalidFilter = fieldFilter.find((filter) => {
if (typeof filter == 'string') {
return false;
}
if (typeof filter == 'number') {
return false;
}
if (typeof filter == 'object' && filter !== null) {
return !checkStateRangeValue(filter as Record<string, unknown>);
}
});
if (invalidFilter) {
return false;
}
}
return true;
}
export function checkStateSort(sort: unknown): boolean {
const sortsAsArray = sort instanceof Array ? sort : [sort];
for (const sort of sortsAsArray) {
if (typeof sort.field != 'string') {
return false;
}
if (typeof sort.direction != 'string') {
return false;
}
}
return true;
}
export function checkState(state: Record<string, unknown>): boolean {
if (typeof state.filter == 'object' && !checkStateFilter(state.filter as Record<string, Array<unknown>>)) {
return false;
}
if (typeof state.sort == 'object' && !checkStateSort(state.sort)) {
return false;
}
if (state.page !== undefined && typeof state.page != 'number') {
return false;
}
if (state.query !== undefined && typeof state.query != 'string') {
return false;
}
return true;
}
| 20.896552 | 108 | 0.643564 | 65 | 5 | 0 | 5 | 3 | 0 | 3 | 0 | 15 | 0 | 18 | 13.2 | 557 | 0.017953 | 0.005386 | 0 | 0 | 0.032316 | 0 | 1.153846 | 0.224078 | export /* Example usages of 'checkStateRangeValue' are shown below:
!checkStateRangeValue(filter as Record<string, unknown>);
*/
function checkStateRangeValue(value) {
if (typeof value != 'object') {
return false;
}
if (typeof value.low != 'number' && value.low !== undefined) {
return false;
}
if (typeof value.high != 'number' && value.high !== undefined) {
return false;
}
if (typeof value.low != 'number' && typeof value.high != 'number') {
// at least one must be defined
return true;
}
return true;
}
export /* Example usages of 'checkStateFilter' are shown below:
typeof state.filter == 'object' && !checkStateFilter(state.filter as Record<string, Array<unknown>>);
*/
function checkStateFilter(filters) {
for (const key of Object.keys(filters)) {
if (typeof key !== 'string') {
return false;
}
const fieldFilter = filters[key];
const invalidFilter = fieldFilter.find((filter) => {
if (typeof filter == 'string') {
return false;
}
if (typeof filter == 'number') {
return false;
}
if (typeof filter == 'object' && filter !== null) {
return !checkStateRangeValue(filter as Record<string, unknown>);
}
});
if (invalidFilter) {
return false;
}
}
return true;
}
export /* Example usages of 'checkStateSort' are shown below:
typeof state.sort == 'object' && !checkStateSort(state.sort);
*/
function checkStateSort(sort) {
const sortsAsArray = sort instanceof Array ? sort : [sort];
for (const sort of sortsAsArray) {
if (typeof sort.field != 'string') {
return false;
}
if (typeof sort.direction != 'string') {
return false;
}
}
return true;
}
export function checkState(state) {
if (typeof state.filter == 'object' && !checkStateFilter(state.filter as Record<string, Array<unknown>>)) {
return false;
}
if (typeof state.sort == 'object' && !checkStateSort(state.sort)) {
return false;
}
if (state.page !== undefined && typeof state.page != 'number') {
return false;
}
if (state.query !== undefined && typeof state.query != 'string') {
return false;
}
return true;
}
|
b7b202e7b28242eca2cfc8f35a2dcfcc2d347d4f | 2,670 | ts | TypeScript | src/index.ts | imranbarbhuiya/ascii-pretty-table | d153c306fee80e21a58ab6edd296502ee923f805 | [
"MIT"
] | null | null | null | src/index.ts | imranbarbhuiya/ascii-pretty-table | d153c306fee80e21a58ab6edd296502ee923f805 | [
"MIT"
] | 1 | 2022-03-20T05:43:20.000Z | 2022-03-20T05:43:20.000Z | src/index.ts | imranbarbhuiya/ascii-pretty-table | d153c306fee80e21a58ab6edd296502ee923f805 | [
"MIT"
] | null | null | null | export interface JsonData {
name: string;
chars: Chars;
rows: string[][];
}
export interface Chars {
edge: string;
top: string;
bottom: string;
corner: string;
}
class Table {
public name: string;
public rows: string[][];
public chars: Chars;
constructor(name: string) {
this.name = name;
this.rows = [];
/**
* @type {{edge:String, fill:String, top:String, bottom: String, corner:String}}
* @default
* edge: "|",
* fill: "─",
* top: ".",
* bottom: "'",
* corner: "+"
*
*/
this.chars = {
edge: "|",
top: ".",
bottom: "'",
corner: "+",
};
}
setSeparator({ edge, top, bottom, corner }: Partial<Chars>): this {
this.chars.edge = edge || this.chars.edge;
this.chars.top = top || this.chars.top;
this.chars.bottom = bottom || this.chars.bottom;
this.chars.corner = corner || this.chars.corner;
return this;
}
setHeading(...headings: string[]): this {
this.rows.unshift(headings);
return this;
}
addRow(...row: string[]): this {
this.rows.push(row);
return this;
}
fromJSON(json: JsonData): this {
this.name = json.name;
this.chars = json.chars;
this.rows = json.rows;
return this;
}
/**
*
* @returns {JSON}
*/
toJSON(): JsonData {
return {
name: this.name,
chars: this.chars,
rows: this.rows,
};
}
toString(): string {
let table = "\n";
const repeat = Math.max(
...this.rows.map((row) => {
let longest = 0;
row.forEach((element) => {
longest += element.length;
});
return longest + 6;
}),
this.name.length + 6
);
table += this.chars.corner;
table += this.chars.top.repeat(repeat);
table += this.chars.corner;
table += "\n";
table += `${this.chars.edge} ${" ".repeat(this.name.length / 4)} ${
this.name
} ${" ".repeat(this.name.length / 4)} ${this.chars.edge}\n`;
table += this.chars.corner;
table += this.chars.bottom.repeat(repeat);
table += this.chars.corner;
table += "\n";
this.rows.forEach((row) => {
table += `${this.chars.edge}`;
row.forEach((column) => {
const spaceRepeat = Math.max(0, (this.name.length - column.length) / 4);
table += " ".repeat(spaceRepeat);
table += `${column}`;
table += " ".repeat(spaceRepeat);
table += this.chars.edge;
});
table += "\n";
table += this.chars.corner;
table += this.chars.bottom.repeat(repeat);
table += this.chars.corner;
table += "\n";
});
return table;
}
}
export default Table;
| 23.628319 | 84 | 0.535581 | 95 | 11 | 0 | 9 | 4 | 10 | 0 | 0 | 12 | 3 | 0 | 8 | 777 | 0.02574 | 0.005148 | 0.01287 | 0.003861 | 0 | 0 | 0.352941 | 0.252868 | export interface JsonData {
name;
chars;
rows;
}
export interface Chars {
edge;
top;
bottom;
corner;
}
class Table {
public name;
public rows;
public chars;
constructor(name) {
this.name = name;
this.rows = [];
/**
* @type {{edge:String, fill:String, top:String, bottom: String, corner:String}}
* @default
* edge: "|",
* fill: "─",
* top: ".",
* bottom: "'",
* corner: "+"
*
*/
this.chars = {
edge: "|",
top: ".",
bottom: "'",
corner: "+",
};
}
setSeparator({ edge, top, bottom, corner }) {
this.chars.edge = edge || this.chars.edge;
this.chars.top = top || this.chars.top;
this.chars.bottom = bottom || this.chars.bottom;
this.chars.corner = corner || this.chars.corner;
return this;
}
setHeading(...headings) {
this.rows.unshift(headings);
return this;
}
addRow(...row) {
this.rows.push(row);
return this;
}
fromJSON(json) {
this.name = json.name;
this.chars = json.chars;
this.rows = json.rows;
return this;
}
/**
*
* @returns {JSON}
*/
toJSON() {
return {
name: this.name,
chars: this.chars,
rows: this.rows,
};
}
toString() {
let table = "\n";
const repeat = Math.max(
...this.rows.map((row) => {
let longest = 0;
row.forEach((element) => {
longest += element.length;
});
return longest + 6;
}),
this.name.length + 6
);
table += this.chars.corner;
table += this.chars.top.repeat(repeat);
table += this.chars.corner;
table += "\n";
table += `${this.chars.edge} ${" ".repeat(this.name.length / 4)} ${
this.name
} ${" ".repeat(this.name.length / 4)} ${this.chars.edge}\n`;
table += this.chars.corner;
table += this.chars.bottom.repeat(repeat);
table += this.chars.corner;
table += "\n";
this.rows.forEach((row) => {
table += `${this.chars.edge}`;
row.forEach((column) => {
const spaceRepeat = Math.max(0, (this.name.length - column.length) / 4);
table += " ".repeat(spaceRepeat);
table += `${column}`;
table += " ".repeat(spaceRepeat);
table += this.chars.edge;
});
table += "\n";
table += this.chars.corner;
table += this.chars.bottom.repeat(repeat);
table += this.chars.corner;
table += "\n";
});
return table;
}
}
export default Table;
|
ea9254c152b06549f2aa0e3b2d8c239decb69e82 | 1,321 | ts | TypeScript | src/screens/BarChartComponent/barChartFunctions.ts | TheWidlarzGroup/charts-library | 333d8ddc67f87f83fa9c73b585a931c660c4dc0c | [
"MIT"
] | 1 | 2022-03-30T17:40:54.000Z | 2022-03-30T17:40:54.000Z | src/screens/BarChartComponent/barChartFunctions.ts | TheWidlarzGroup/charts-library | 333d8ddc67f87f83fa9c73b585a931c660c4dc0c | [
"MIT"
] | null | null | null | src/screens/BarChartComponent/barChartFunctions.ts | TheWidlarzGroup/charts-library | 333d8ddc67f87f83fa9c73b585a931c660c4dc0c | [
"MIT"
] | null | null | null | export const transformDataForBarChart = (
number: number
): { value: number; svg: { fill: string; stroke?: string; strokeWidth?: number } } => {
// random ranges > number < inscribed to distinguish colors
if (number <= 30) {
return {
value: number,
svg: {
fill: 'red',
},
}
} else if (number > 30 && number < 70) {
return {
value: number,
svg: {
stroke: 'orange',
strokeWidth: 2,
fill: '#FFD580',
},
}
} else {
return {
value: number,
svg: {
fill: 'green',
},
}
}
}
export const transformDataForBarChart2 = (
number: number,
index: number
): { value: number; svg: { fill: string; stroke?: string; strokeWidth?: number } } => {
// random ranges > number < inscribed to distinguish colors
if (index % 2 === 0) {
return {
value: number,
svg: {
fill: 'red',
},
}
} else if (index % 3 === 0) {
return {
value: number,
svg: {
stroke: 'orange',
strokeWidth: 2,
fill: '#FFD580',
},
}
} else if (index % 5 === 0) {
return {
value: number,
svg: {
fill: 'green',
},
}
} else {
return {
value: number,
svg: {
fill: 'purple',
},
}
}
}
| 19.426471 | 87 | 0.476154 | 64 | 2 | 0 | 3 | 2 | 0 | 0 | 0 | 11 | 0 | 0 | 27.5 | 375 | 0.013333 | 0.005333 | 0 | 0 | 0 | 0 | 1.571429 | 0.216728 | export const transformDataForBarChart = (
number
) => {
// random ranges > number < inscribed to distinguish colors
if (number <= 30) {
return {
value: number,
svg: {
fill: 'red',
},
}
} else if (number > 30 && number < 70) {
return {
value: number,
svg: {
stroke: 'orange',
strokeWidth: 2,
fill: '#FFD580',
},
}
} else {
return {
value: number,
svg: {
fill: 'green',
},
}
}
}
export const transformDataForBarChart2 = (
number,
index
) => {
// random ranges > number < inscribed to distinguish colors
if (index % 2 === 0) {
return {
value: number,
svg: {
fill: 'red',
},
}
} else if (index % 3 === 0) {
return {
value: number,
svg: {
stroke: 'orange',
strokeWidth: 2,
fill: '#FFD580',
},
}
} else if (index % 5 === 0) {
return {
value: number,
svg: {
fill: 'green',
},
}
} else {
return {
value: number,
svg: {
fill: 'purple',
},
}
}
}
|
eaa92966cbe116f28e1b5c9c0f4b724a32bab041 | 5,154 | ts | TypeScript | src/algorithms/bellmanFord.ts | maissenayed/lago | 53c8403739f891cb4fb565dabafdfdb1a982840c | [
"MIT"
] | 1 | 2022-02-22T07:47:43.000Z | 2022-02-22T07:47:43.000Z | src/algorithms/bellmanFord.ts | nizam754/lago | 53c8403739f891cb4fb565dabafdfdb1a982840c | [
"MIT"
] | null | null | null | src/algorithms/bellmanFord.ts | nizam754/lago | 53c8403739f891cb4fb565dabafdfdb1a982840c | [
"MIT"
] | 1 | 2022-03-10T19:43:10.000Z | 2022-03-10T19:43:10.000Z | type Vertex = string;
type Weight = number;
type Graph = Record<string, Record<string, Weight>>;
/**
* If a target is not provided, finds the single-source shortest path distance from the source vertex with positive or negative edge weights
* (but with no negative weight cycles).
* Else, it returns the shortest path as well as its distance from source vertex to target vertex.
* In the case of negative weight cycles, if target is defined, then negative infinity and empty array path will be returned,
* else, all distances from A will be returned with negative infinity.
*
* @param {Graph} graph Vertex with its fields being the neighboring vertices and value being the weight from vertex to neighboring vertices
* @param {Vertex} source Starting vertex in graph
* @param {Vertex} target Ending vertex in graph
* @return {Record<string, number> | [number, Array<Vertex>]} An object mapping of the distance from the source vertex or an array containing the distance
* and an array containing the path from source to target vertex
*/
function bellmanFord(
graph: Graph,
source: Vertex,
target?: Vertex,
): Record<string, number> | [number, Array<Vertex>] {
const vertices = Object.keys(graph);
// if graph is empty, immediately return
if (vertices.length === 0) {
return target ? [0, []] : {};
}
if (!vertices.includes(source) || (target && !vertices.includes(target))) {
return target ? [-Infinity, []] : {};
}
const distances = getDistances(vertices, source);
const predecessor = getPredecessor(vertices);
// requires only n - 1 iteration
for (let i = 0; i < vertices.length - 1; i++) {
for (let startVertex of vertices) {
const neighbors = graph[startVertex];
for (let endVertex in neighbors) {
const weight = graph[startVertex][endVertex];
// relaxation
if (distances[startVertex] + weight < distances[endVertex]) {
distances[endVertex] = distances[startVertex] + weight;
predecessor[endVertex] = startVertex;
}
}
}
}
// checks for any negative weight cycles. If true returns all distances as -Infinity as a sign negative weight cycles
for (let startVertex of vertices) {
const neighbors = graph[startVertex];
for (let endVertex in neighbors) {
const weight = graph[startVertex][endVertex];
// if relaxation occurs here, negative weight cycles detected
if (distances[startVertex] + weight < distances[endVertex]) {
return target ? [-Infinity, []] : negativeWeightCycles(vertices);
}
}
}
if (!target) {
return distances;
}
const shortestDistance = distances[target];
const path = getPath(predecessor, source, target);
return [shortestDistance, path];
}
/**
* Returns an Object mapping of nodes to distance with values all being negative infinity to represent a negative weight cycle being present.
*
* @param {Array<Vertex>} vertices An array of all vertices in the graph
* @return {Record<string, number>} An object mapping of nodes with values being negative infinity
*/
function negativeWeightCycles(vertices: Array<Vertex>): Record<string, number> {
return vertices.reduce((acc, curr) => {
acc[curr] = -Infinity;
return acc;
}, {} as Record<string, number>);
}
/**
* Initializes the distance mapping from source to rest of the vertices.
*
* @param {Array<Vertex>} vertices An array of all vertices in the graph
* @param {Vertex} source Starting vertex in graph
* @return {Record<string, number>} An object mapping of source to rest of vertices
*/
function getDistances(
vertices: Array<Vertex>,
source: Vertex,
): Record<string, number> {
const distances = vertices.reduce((acc, curr) => {
acc[curr] = Infinity;
return acc;
}, {} as Record<string, number>);
distances[source] = 0;
return distances;
}
/**
* Returns an array denoting the path from start vertex to end vertex.
*
* @param {Object} predecessor Mapping of child vertex pointing to parent vertex
* @param {Vertex} source Starting vertex in graph
* @param {Vertex} target End vertex in graph
* @return {Array<String>} An array containing the path from source to target vertex
*/
function getPath(
predecessor: Record<string, string | undefined>,
source: Vertex,
target: Vertex,
): Array<string> {
const path = [target];
while (target && target !== source) {
const next = predecessor[target];
target = next ?? source; // if next is undefined, it reaches source
path.push(target);
}
return path.reverse();
}
/**
* Generates a default object mapping of child vertex pointing to parent vertex which will be defaulted to undefined initially.
*
* @param {Array<Vertex>} vertices An array of all vertices in the graph
* @return {Record<string, Vertex | undefined>} An object mapping of child vertex pointing to parent vertex
*/
function getPredecessor(
vertices: Array<Vertex>,
): Record<string, Vertex | undefined> {
const predecessor = {} as Record<string, Vertex | undefined>;
for (let vertex of vertices) {
predecessor[vertex] = undefined;
}
return predecessor;
}
export default bellmanFord;
| 36.041958 | 154 | 0.701009 | 85 | 7 | 0 | 14 | 14 | 0 | 4 | 0 | 20 | 3 | 3 | 8.857143 | 1,254 | 0.016746 | 0.011164 | 0 | 0.002392 | 0.002392 | 0 | 0.571429 | 0.249492 | type Vertex = string;
type Weight = number;
type Graph = Record<string, Record<string, Weight>>;
/**
* If a target is not provided, finds the single-source shortest path distance from the source vertex with positive or negative edge weights
* (but with no negative weight cycles).
* Else, it returns the shortest path as well as its distance from source vertex to target vertex.
* In the case of negative weight cycles, if target is defined, then negative infinity and empty array path will be returned,
* else, all distances from A will be returned with negative infinity.
*
* @param {Graph} graph Vertex with its fields being the neighboring vertices and value being the weight from vertex to neighboring vertices
* @param {Vertex} source Starting vertex in graph
* @param {Vertex} target Ending vertex in graph
* @return {Record<string, number> | [number, Array<Vertex>]} An object mapping of the distance from the source vertex or an array containing the distance
* and an array containing the path from source to target vertex
*/
/* Example usages of 'bellmanFord' are shown below:
;
*/
function bellmanFord(
graph,
source,
target?,
) {
const vertices = Object.keys(graph);
// if graph is empty, immediately return
if (vertices.length === 0) {
return target ? [0, []] : {};
}
if (!vertices.includes(source) || (target && !vertices.includes(target))) {
return target ? [-Infinity, []] : {};
}
const distances = getDistances(vertices, source);
const predecessor = getPredecessor(vertices);
// requires only n - 1 iteration
for (let i = 0; i < vertices.length - 1; i++) {
for (let startVertex of vertices) {
const neighbors = graph[startVertex];
for (let endVertex in neighbors) {
const weight = graph[startVertex][endVertex];
// relaxation
if (distances[startVertex] + weight < distances[endVertex]) {
distances[endVertex] = distances[startVertex] + weight;
predecessor[endVertex] = startVertex;
}
}
}
}
// checks for any negative weight cycles. If true returns all distances as -Infinity as a sign negative weight cycles
for (let startVertex of vertices) {
const neighbors = graph[startVertex];
for (let endVertex in neighbors) {
const weight = graph[startVertex][endVertex];
// if relaxation occurs here, negative weight cycles detected
if (distances[startVertex] + weight < distances[endVertex]) {
return target ? [-Infinity, []] : negativeWeightCycles(vertices);
}
}
}
if (!target) {
return distances;
}
const shortestDistance = distances[target];
const path = getPath(predecessor, source, target);
return [shortestDistance, path];
}
/**
* Returns an Object mapping of nodes to distance with values all being negative infinity to represent a negative weight cycle being present.
*
* @param {Array<Vertex>} vertices An array of all vertices in the graph
* @return {Record<string, number>} An object mapping of nodes with values being negative infinity
*/
/* Example usages of 'negativeWeightCycles' are shown below:
target ? [-Infinity, []] : negativeWeightCycles(vertices);
*/
function negativeWeightCycles(vertices) {
return vertices.reduce((acc, curr) => {
acc[curr] = -Infinity;
return acc;
}, {} as Record<string, number>);
}
/**
* Initializes the distance mapping from source to rest of the vertices.
*
* @param {Array<Vertex>} vertices An array of all vertices in the graph
* @param {Vertex} source Starting vertex in graph
* @return {Record<string, number>} An object mapping of source to rest of vertices
*/
/* Example usages of 'getDistances' are shown below:
getDistances(vertices, source);
*/
function getDistances(
vertices,
source,
) {
const distances = vertices.reduce((acc, curr) => {
acc[curr] = Infinity;
return acc;
}, {} as Record<string, number>);
distances[source] = 0;
return distances;
}
/**
* Returns an array denoting the path from start vertex to end vertex.
*
* @param {Object} predecessor Mapping of child vertex pointing to parent vertex
* @param {Vertex} source Starting vertex in graph
* @param {Vertex} target End vertex in graph
* @return {Array<String>} An array containing the path from source to target vertex
*/
/* Example usages of 'getPath' are shown below:
getPath(predecessor, source, target);
*/
function getPath(
predecessor,
source,
target,
) {
const path = [target];
while (target && target !== source) {
const next = predecessor[target];
target = next ?? source; // if next is undefined, it reaches source
path.push(target);
}
return path.reverse();
}
/**
* Generates a default object mapping of child vertex pointing to parent vertex which will be defaulted to undefined initially.
*
* @param {Array<Vertex>} vertices An array of all vertices in the graph
* @return {Record<string, Vertex | undefined>} An object mapping of child vertex pointing to parent vertex
*/
/* Example usages of 'getPredecessor' are shown below:
getPredecessor(vertices);
*/
function getPredecessor(
vertices,
) {
const predecessor = {} as Record<string, Vertex | undefined>;
for (let vertex of vertices) {
predecessor[vertex] = undefined;
}
return predecessor;
}
export default bellmanFord;
|
9d18cd905ea50a724ab484c9b238116e051b07cd | 2,222 | ts | TypeScript | lib/regex.ts | eenagy/siwe | ae7212421faac6034b6d63ae200be067909a3699 | [
"Apache-2.0",
"MIT"
] | 1 | 2022-01-06T20:05:39.000Z | 2022-01-06T20:05:39.000Z | lib/regex.ts | eenagy/siwe | ae7212421faac6034b6d63ae200be067909a3699 | [
"Apache-2.0",
"MIT"
] | null | null | null | lib/regex.ts | eenagy/siwe | ae7212421faac6034b6d63ae200be067909a3699 | [
"Apache-2.0",
"MIT"
] | null | null | null | const DOMAIN =
'(?<domain>([^?#]*)) wants you to sign in with your Ethereum account:';
const ADDRESS = '\\n(?<address>0x[a-zA-Z0-9]{40})\\n\\n';
const STATEMENT = '((?<statement>[^\\n]+)\\n)?';
const URI = '(([^:?#]+):)?(([^?#]*))?([^?#]*)(\\?([^#]*))?(#(.*))';
const URI_LINE = `\\nURI: (?<uri>${URI}?)`;
const VERSION = '\\nVersion: (?<version>1)';
const CHAIN_ID = '\\nChain ID: (?<chainId>[0-9]+)';
const NONCE = '\\nNonce: (?<nonce>[a-zA-Z0-9]{8,})';
const DATETIME = `([0-9]+)-(0[1-9]|1[012])-(0[1-9]|[12][0-9]|3[01])[Tt]([01][0-9]|2[0-3]):([0-5][0-9]):([0-5][0-9]|60)(\.[0-9]+)?(([Zz])|([\+|\-]([01][0-9]|2[0-3]):[0-5][0-9]))`;
const ISSUED_AT = `\\nIssued At: (?<issuedAt>${DATETIME})`;
const EXPIRATION_TIME = `(\\nExpiration Time: (?<expirationTime>${DATETIME}))?`;
const NOT_BEFORE = `(\\nNot Before: (?<notBefore>${DATETIME}))?`;
const REQUEST_ID =
"(\\nRequest ID: (?<requestId>[-._~!$&'()*+,;=:@%a-zA-Z0-9]*))?";
const RESOURCES = `(\\nResources:(?<resources>(\\n- ${URI}?)+))?`;
const MESSAGE = `^${DOMAIN}${ADDRESS}${STATEMENT}${URI_LINE}${VERSION}${CHAIN_ID}${NONCE}${ISSUED_AT}${EXPIRATION_TIME}${NOT_BEFORE}${REQUEST_ID}${RESOURCES}$`;
export class ParsedMessage {
domain: string;
address: string;
statement: string;
uri: string;
version: string;
chainId: string;
nonce: string;
issuedAt: string;
expirationTime: string | null;
notBefore: string | null;
requestId: string | null;
resources: string[] | null;
match?: RegExpExecArray;
constructor(msg: string) {
const REGEX = new RegExp(MESSAGE, 'g');
let match = REGEX.exec(msg);
if (!match) {
throw new Error('Message did not match the regular expression.');
}
this.match = match;
this.domain = match?.groups?.domain;
this.address = match?.groups?.address;
this.statement = match?.groups?.statement;
this.uri = match?.groups?.uri;
this.version = match?.groups?.version;
this.nonce = match?.groups?.nonce;
this.chainId = match?.groups?.chainId;
this.issuedAt = match?.groups?.issuedAt;
this.expirationTime = match?.groups?.expirationTime;
this.notBefore = match?.groups?.notBefore;
this.requestId = match?.groups?.requestId;
this.resources = match?.groups?.resources?.split('\n- ').slice(1);
}
}
| 38.982456 | 178 | 0.616112 | 52 | 1 | 0 | 1 | 17 | 13 | 0 | 0 | 13 | 1 | 0 | 18 | 828 | 0.002415 | 0.020531 | 0.0157 | 0.001208 | 0 | 0 | 0.40625 | 0.244236 | const DOMAIN =
'(?<domain>([^?#]*)) wants you to sign in with your Ethereum account:';
const ADDRESS = '\\n(?<address>0x[a-zA-Z0-9]{40})\\n\\n';
const STATEMENT = '((?<statement>[^\\n]+)\\n)?';
const URI = '(([^:?#]+):)?(([^?#]*))?([^?#]*)(\\?([^#]*))?(#(.*))';
const URI_LINE = `\\nURI: (?<uri>${URI}?)`;
const VERSION = '\\nVersion: (?<version>1)';
const CHAIN_ID = '\\nChain ID: (?<chainId>[0-9]+)';
const NONCE = '\\nNonce: (?<nonce>[a-zA-Z0-9]{8,})';
const DATETIME = `([0-9]+)-(0[1-9]|1[012])-(0[1-9]|[12][0-9]|3[01])[Tt]([01][0-9]|2[0-3]):([0-5][0-9]):([0-5][0-9]|60)(\.[0-9]+)?(([Zz])|([\+|\-]([01][0-9]|2[0-3]):[0-5][0-9]))`;
const ISSUED_AT = `\\nIssued At: (?<issuedAt>${DATETIME})`;
const EXPIRATION_TIME = `(\\nExpiration Time: (?<expirationTime>${DATETIME}))?`;
const NOT_BEFORE = `(\\nNot Before: (?<notBefore>${DATETIME}))?`;
const REQUEST_ID =
"(\\nRequest ID: (?<requestId>[-._~!$&'()*+,;=:@%a-zA-Z0-9]*))?";
const RESOURCES = `(\\nResources:(?<resources>(\\n- ${URI}?)+))?`;
const MESSAGE = `^${DOMAIN}${ADDRESS}${STATEMENT}${URI_LINE}${VERSION}${CHAIN_ID}${NONCE}${ISSUED_AT}${EXPIRATION_TIME}${NOT_BEFORE}${REQUEST_ID}${RESOURCES}$`;
export class ParsedMessage {
domain;
address;
statement;
uri;
version;
chainId;
nonce;
issuedAt;
expirationTime;
notBefore;
requestId;
resources;
match?;
constructor(msg) {
const REGEX = new RegExp(MESSAGE, 'g');
let match = REGEX.exec(msg);
if (!match) {
throw new Error('Message did not match the regular expression.');
}
this.match = match;
this.domain = match?.groups?.domain;
this.address = match?.groups?.address;
this.statement = match?.groups?.statement;
this.uri = match?.groups?.uri;
this.version = match?.groups?.version;
this.nonce = match?.groups?.nonce;
this.chainId = match?.groups?.chainId;
this.issuedAt = match?.groups?.issuedAt;
this.expirationTime = match?.groups?.expirationTime;
this.notBefore = match?.groups?.notBefore;
this.requestId = match?.groups?.requestId;
this.resources = match?.groups?.resources?.split('\n- ').slice(1);
}
}
|
9d2bbc064e3cebd074b1fa1b09959385300d23fc | 3,285 | ts | TypeScript | util/prism_utils.ts | kitsonk/dotland | be946ca34b887d97f37260ed7f4b0a0feaa58fea | [
"MIT"
] | null | null | null | util/prism_utils.ts | kitsonk/dotland | be946ca34b887d97f37260ed7f4b0a0feaa58fea | [
"MIT"
] | 3 | 2022-02-17T19:37:29.000Z | 2022-02-24T10:46:41.000Z | util/prism_utils.ts | kitsonk/dotland | be946ca34b887d97f37260ed7f4b0a0feaa58fea | [
"MIT"
] | null | null | null | // Copyright 2022 the Deno authors. All rights reserved. MIT license.
// Taken from https://github.com/FormidableLabs/prism-react-renderer/blob/master/src/utils/normalizeTokens.js
/** Empty lines need to contain a single empty token, denoted with { empty: true } */
// deno-lint-ignore no-explicit-any
function normalizeEmptyLines(line: any[]) {
if (line.length === 0) {
line.push({
types: ["plain"],
content: "\n",
empty: true,
});
} else if (line.length === 1 && line[0].content === "") {
line[0].content = "\n";
line[0].empty = true;
}
}
function appendTypes(types: string[], add: string[] | string): string[] {
const typesSize = types.length;
if (typesSize > 0 && types[typesSize - 1] === add) {
return types;
}
return types.concat(add);
}
const newlineRe = /\r\n|\r|\n/;
/**
* Takes an array of Prism's tokens and groups them by line, turning plain
* strings into tokens as well. Tokens can become recursive in some cases,
* which means that their types are concatenated. Plain-string tokens however
* are always of type "plain".
* This is not recursive to avoid exceeding the call-stack limit, since it's unclear
* how nested Prism's tokens can become
*/
// deno-lint-ignore no-explicit-any
export function normalizeTokens(tokens: Array<any | string>): any[][] {
const typeArrStack: string[][] = [[]];
const tokenArrStack = [tokens];
const tokenArrIndexStack = [0];
const tokenArrSizeStack = [tokens.length];
let i = 0;
let stackIndex = 0;
// deno-lint-ignore no-explicit-any
let currentLine: any[] = [];
const acc = [currentLine];
while (stackIndex > -1) {
while (
(i = tokenArrIndexStack[stackIndex]++) < tokenArrSizeStack[stackIndex]
) {
let content;
let types = typeArrStack[stackIndex];
const tokenArr = tokenArrStack[stackIndex];
const token = tokenArr[i];
// Determine content and append type to types if necessary
if (typeof token === "string") {
types = stackIndex > 0 ? types : ["plain"];
content = token;
} else {
types = appendTypes(types, token.type);
if (token.alias) {
types = appendTypes(types, token.alias);
}
content = token.content;
}
// If token.content is an array, increase the stack depth and repeat this while-loop
if (typeof content !== "string") {
stackIndex++;
typeArrStack.push(types);
tokenArrStack.push(content);
tokenArrIndexStack.push(0);
tokenArrSizeStack.push(content.length);
continue;
}
// Split by newlines
const splitByNewlines = content.split(newlineRe);
const newlineCount = splitByNewlines.length;
currentLine.push({ types, content: splitByNewlines[0] });
// Create a new line for each string on a new line
for (let i = 1; i < newlineCount; i++) {
normalizeEmptyLines(currentLine);
acc.push(currentLine = []);
currentLine.push({ types, content: splitByNewlines[i] });
}
}
// Decrease the stack depth
stackIndex--;
typeArrStack.pop();
tokenArrStack.pop();
tokenArrIndexStack.pop();
tokenArrSizeStack.pop();
}
normalizeEmptyLines(currentLine);
return acc;
}
| 29.863636 | 109 | 0.636834 | 73 | 3 | 0 | 4 | 17 | 0 | 2 | 4 | 6 | 0 | 2 | 22 | 888 | 0.007883 | 0.019144 | 0 | 0 | 0.002252 | 0.166667 | 0.25 | 0.248293 | // Copyright 2022 the Deno authors. All rights reserved. MIT license.
// Taken from https://github.com/FormidableLabs/prism-react-renderer/blob/master/src/utils/normalizeTokens.js
/** Empty lines need to contain a single empty token, denoted with { empty: true } */
// deno-lint-ignore no-explicit-any
/* Example usages of 'normalizeEmptyLines' are shown below:
normalizeEmptyLines(currentLine);
*/
function normalizeEmptyLines(line) {
if (line.length === 0) {
line.push({
types: ["plain"],
content: "\n",
empty: true,
});
} else if (line.length === 1 && line[0].content === "") {
line[0].content = "\n";
line[0].empty = true;
}
}
/* Example usages of 'appendTypes' are shown below:
types = appendTypes(types, token.type);
types = appendTypes(types, token.alias);
*/
function appendTypes(types, add) {
const typesSize = types.length;
if (typesSize > 0 && types[typesSize - 1] === add) {
return types;
}
return types.concat(add);
}
const newlineRe = /\r\n|\r|\n/;
/**
* Takes an array of Prism's tokens and groups them by line, turning plain
* strings into tokens as well. Tokens can become recursive in some cases,
* which means that their types are concatenated. Plain-string tokens however
* are always of type "plain".
* This is not recursive to avoid exceeding the call-stack limit, since it's unclear
* how nested Prism's tokens can become
*/
// deno-lint-ignore no-explicit-any
export function normalizeTokens(tokens) {
const typeArrStack = [[]];
const tokenArrStack = [tokens];
const tokenArrIndexStack = [0];
const tokenArrSizeStack = [tokens.length];
let i = 0;
let stackIndex = 0;
// deno-lint-ignore no-explicit-any
let currentLine = [];
const acc = [currentLine];
while (stackIndex > -1) {
while (
(i = tokenArrIndexStack[stackIndex]++) < tokenArrSizeStack[stackIndex]
) {
let content;
let types = typeArrStack[stackIndex];
const tokenArr = tokenArrStack[stackIndex];
const token = tokenArr[i];
// Determine content and append type to types if necessary
if (typeof token === "string") {
types = stackIndex > 0 ? types : ["plain"];
content = token;
} else {
types = appendTypes(types, token.type);
if (token.alias) {
types = appendTypes(types, token.alias);
}
content = token.content;
}
// If token.content is an array, increase the stack depth and repeat this while-loop
if (typeof content !== "string") {
stackIndex++;
typeArrStack.push(types);
tokenArrStack.push(content);
tokenArrIndexStack.push(0);
tokenArrSizeStack.push(content.length);
continue;
}
// Split by newlines
const splitByNewlines = content.split(newlineRe);
const newlineCount = splitByNewlines.length;
currentLine.push({ types, content: splitByNewlines[0] });
// Create a new line for each string on a new line
for (let i = 1; i < newlineCount; i++) {
normalizeEmptyLines(currentLine);
acc.push(currentLine = []);
currentLine.push({ types, content: splitByNewlines[i] });
}
}
// Decrease the stack depth
stackIndex--;
typeArrStack.pop();
tokenArrStack.pop();
tokenArrIndexStack.pop();
tokenArrSizeStack.pop();
}
normalizeEmptyLines(currentLine);
return acc;
}
|
9d2d566c3244dace3ee13e70b803ed5074da4243 | 5,730 | ts | TypeScript | src/easyquotation-ts/indicator.ts | FEYeh/stock-analysis | 7434d5f743ba8147e88b3bdb25b5c6efa6f6564b | [
"MulanPSL-1.0"
] | 3 | 2022-02-04T04:29:27.000Z | 2022-02-07T02:18:44.000Z | src/easyquotation-ts/indicator.ts | FEYeh/stock-analysis | 7434d5f743ba8147e88b3bdb25b5c6efa6f6564b | [
"MulanPSL-1.0"
] | null | null | null | src/easyquotation-ts/indicator.ts | FEYeh/stock-analysis | 7434d5f743ba8147e88b3bdb25b5c6efa6f6564b | [
"MulanPSL-1.0"
] | null | null | null |
/**
* 计算obv指标
*
* @method OBV
* @param {Array} ticks
* ticks为二维数组类型,其中内层数组第一个值为收盘价,第二个值为成交量
* @return {Array} obvs
*/
export const OBV = (ticks: string | any[]) => {
let lastTick;
const obvs = [];
const length = ticks.length;
for (let i = 0; i < length; i++) {
let value = 0;
const curTick = ticks[i];
if (i != 0) {
const lastObvValue = obvs[i - 1];
if (curTick[0] >= lastTick[0]) {
value = lastObvValue + curTick[1];
} else {
value = lastObvValue - curTick[1];
}
}
obvs.push(value);
lastTick = curTick;
}
return obvs;
};
const ema = (lastEma: number, closePrice: number, units: number) => {
return (lastEma * (units - 1) + closePrice * 2) / (units + 1);
};
const dea = (lastDea: number, curDiff: number) => {
return (lastDea * 8 + curDiff * 2) / 10;
};
/**
*
* 计算macd指标,快速和慢速移动平均线的周期分别取12和26
*
* @method MACD
* @param {Array} ticks
* 一维数组类型,每个元素为tick的收盘价格
* @return {Object} 返回一个包含diffs deas bars属性的对象,每个属性对应的类型为{Array[Number]}
*/
export const MACD = function (ticks: string | any[]) {
const ema12: any[] = [], ema26: any[] = [], diffs = [], deas = [], bars = [];
for (let i = 0; i < ticks.length; i++) {
const c = ticks[i];
if (i == 0) {
ema12.push(c);
ema26.push(c);
deas.push(0);
} else {
ema12.push(ema(ema12[i - 1], c, 12));
ema26.push(ema(ema26[i - 1], c, 26));
}
diffs.push(ema12[i] - ema26[i]);
if (i != 0) {
deas.push(dea(deas[i - 1], diffs[i]));
}
bars.push((diffs[i] - deas[i]) * 2);
}
return { diffs: diffs, deas: deas, bars: bars };
};
const getMaxHighAndMinLow = function (ticks: string | any[]) {
let maxHigh = ticks[0][0], minLow = ticks[0][1];
for (let i = 0; i < ticks.length; i++) {
const t = ticks[i], high = t[0], low = t[1];
if (high > maxHigh) {
maxHigh = high;
}
if (low < minLow) {
minLow = low;
}
}
return [maxHigh, minLow];
};
/**
*
* 计算kdj指标,rsv的周期为9日
*
* @method KDJ
* @param {Array} ticks
* 二维数组类型,其中内层数组包含三个元素值,第一个值表示当前Tick的最高价格,第二个表示当前Tick的最低价格,第三个表示当前Tick的收盘价格
* @return {Object} 返回一个包含k d j属性的对象,每个属性对应的类型为{Array[Number]}
*/
export const kdj = function (ticks: string | any[]) {
const nineDaysTicks = [], days = 9, rsvs = [];
const ks = [], ds = [], js = [];
let lastK = 0, lastD = 0, curK, curD;
let maxAndMin, max, min;
for (let i = 0; i < ticks.length; i++) {
const t = ticks[i], close = t[2];
nineDaysTicks.push(t);
maxAndMin = getMaxHighAndMinLow(nineDaysTicks);
max = maxAndMin[0];
min = maxAndMin[1];
if (max == min) {
rsvs.push(0);
} else {
rsvs.push((close - min) / (max - min) * 100);
}
if (nineDaysTicks.length == days) {
nineDaysTicks.shift();
}
if (i == 0) {
lastK = lastD = rsvs[i];
}
curK = 2 / 3 * lastK + 1 / 3 * rsvs[i];
ks.push(curK);
lastK = curK;
curD = 2 / 3 * lastD + 1 / 3 * curK;
ds.push(curD);
lastD = curD;
js.push(3 * curK - 2 * curD);
}
return { "k": ks, "d": ds, "j": js };
};
/**
*
* 计算移动平均线指标, ma的周期为days
*
* @method MA
* @param {Array} ticks
* @param Number days
* 一维数组类型,每个元素为当前Tick的收盘价格
* @return {Array} mas
*/
export const MA = function (ticks: string | any[], days: number) {
let maSum = 0;
const mas = [];
for (let i = 0; i < ticks.length; i++) {
maSum += ticks[i];
const _ma = maSum / days;
mas.push(_ma);
}
return mas;
};
/**
*
* 计算boll指标,ma的周期为20日
*
* @method BOLL
* @param {Array} ticks
* 一维数组类型,每个元素为当前Tick的收盘价格
* @return {Object} 返回一个包含upper mid lower属性的对象,每个属性对应的类型为{Array[Number]}
*/
export const BOLL = function (ticks: any[]) {
//移动平均线周期为20
const maDays = 20;
const tickBegin = maDays - 1;
let maSum = 0, p = 0;
const ups = [], mas = [], lows = [];
for (let i = 0; i < ticks.length; i++) {
const c = ticks[i];
let ma: number, md, bstart, mdSum;
maSum += c;
if (i >= tickBegin) {
maSum = maSum - p;
ma = maSum / maDays;
mas.push(ma);
bstart = i - tickBegin;
p = ticks[bstart];
mdSum = ticks.slice(bstart, bstart + maDays).reduce(function (a: number, b: number) { return a + Math.pow(b - ma, 2); }, 0);
md = Math.sqrt(mdSum / maDays);
ups.push(ma + 2 * md);
lows.push(ma - 2 * md);
} else {
//ugly constant, just keep the same type for client
ups.push(-1);
mas.push(-1);
lows.push(-1);
}
}
return { "upper": ups, "mid": mas, "lower": lows };
};
/**
*
* 计算rsi指标,分别返回以6日,12日,24日为参考基期的RSI值
*
* @method RSI
* @param {Array} ticks
* 一维数组类型,每个元素为当前Tick的收盘价格
* @return {Object} 返回一个包含rsi6 rsi12 rsi24属性的对象,每个属性对应的类型为{Array[Number]}
*/
export const RSI = function (ticks: string | any[]) {
let lastClosePx = ticks[0];
const days = [6, 12, 24], result: any = {};
for (let i = 0; i < ticks.length; i++) {
const c = ticks[i];
const m = Math.max(c - lastClosePx, 0), a = Math.abs(c - lastClosePx);
for (let di = 0; di < days.length; di++) {
const d = days[di];
// eslint-disable-next-line no-prototype-builtins
if (!result.hasOwnProperty("rsi" + d)) {
result["lastSm" + d] = result["lastSa" + d] = 0;
result["rsi" + d] = [0];
} else {
result["lastSm" + d] = (m + (d - 1) * result["lastSm" + d]) / d;
result["lastSa" + d] = (a + (d - 1) * result["lastSa" + d]) / d;
if (result["lastSa" + d] != 0) {
result["rsi" + d].push(result["lastSm" + d] / result["lastSa" + d] * 100);
} else {
result["rsi" + d].push(0);
}
}
}
lastClosePx = c;
}
return { "rsi6": result["rsi6"], "rsi12": result["rsi12"], "rsi24": result["rsi24"] };
};
| 25.810811 | 130 | 0.544677 | 153 | 10 | 0 | 15 | 71 | 0 | 3 | 10 | 15 | 0 | 0 | 13.6 | 2,290 | 0.010917 | 0.031004 | 0 | 0 | 0 | 0.104167 | 0.15625 | 0.295826 |
/**
* 计算obv指标
*
* @method OBV
* @param {Array} ticks
* ticks为二维数组类型,其中内层数组第一个值为收盘价,第二个值为成交量
* @return {Array} obvs
*/
export const OBV = (ticks) => {
let lastTick;
const obvs = [];
const length = ticks.length;
for (let i = 0; i < length; i++) {
let value = 0;
const curTick = ticks[i];
if (i != 0) {
const lastObvValue = obvs[i - 1];
if (curTick[0] >= lastTick[0]) {
value = lastObvValue + curTick[1];
} else {
value = lastObvValue - curTick[1];
}
}
obvs.push(value);
lastTick = curTick;
}
return obvs;
};
/* Example usages of 'ema' are shown below:
ema12.push(ema(ema12[i - 1], c, 12));
ema26.push(ema(ema26[i - 1], c, 26));
*/
const ema = (lastEma, closePrice, units) => {
return (lastEma * (units - 1) + closePrice * 2) / (units + 1);
};
/* Example usages of 'dea' are shown below:
deas.push(dea(deas[i - 1], diffs[i]));
*/
const dea = (lastDea, curDiff) => {
return (lastDea * 8 + curDiff * 2) / 10;
};
/**
*
* 计算macd指标,快速和慢速移动平均线的周期分别取12和26
*
* @method MACD
* @param {Array} ticks
* 一维数组类型,每个元素为tick的收盘价格
* @return {Object} 返回一个包含diffs deas bars属性的对象,每个属性对应的类型为{Array[Number]}
*/
export const MACD = function (ticks) {
const ema12 = [], ema26 = [], diffs = [], deas = [], bars = [];
for (let i = 0; i < ticks.length; i++) {
const c = ticks[i];
if (i == 0) {
ema12.push(c);
ema26.push(c);
deas.push(0);
} else {
ema12.push(ema(ema12[i - 1], c, 12));
ema26.push(ema(ema26[i - 1], c, 26));
}
diffs.push(ema12[i] - ema26[i]);
if (i != 0) {
deas.push(dea(deas[i - 1], diffs[i]));
}
bars.push((diffs[i] - deas[i]) * 2);
}
return { diffs: diffs, deas: deas, bars: bars };
};
/* Example usages of 'getMaxHighAndMinLow' are shown below:
maxAndMin = getMaxHighAndMinLow(nineDaysTicks);
*/
const getMaxHighAndMinLow = function (ticks) {
let maxHigh = ticks[0][0], minLow = ticks[0][1];
for (let i = 0; i < ticks.length; i++) {
const t = ticks[i], high = t[0], low = t[1];
if (high > maxHigh) {
maxHigh = high;
}
if (low < minLow) {
minLow = low;
}
}
return [maxHigh, minLow];
};
/**
*
* 计算kdj指标,rsv的周期为9日
*
* @method KDJ
* @param {Array} ticks
* 二维数组类型,其中内层数组包含三个元素值,第一个值表示当前Tick的最高价格,第二个表示当前Tick的最低价格,第三个表示当前Tick的收盘价格
* @return {Object} 返回一个包含k d j属性的对象,每个属性对应的类型为{Array[Number]}
*/
export const kdj = function (ticks) {
const nineDaysTicks = [], days = 9, rsvs = [];
const ks = [], ds = [], js = [];
let lastK = 0, lastD = 0, curK, curD;
let maxAndMin, max, min;
for (let i = 0; i < ticks.length; i++) {
const t = ticks[i], close = t[2];
nineDaysTicks.push(t);
maxAndMin = getMaxHighAndMinLow(nineDaysTicks);
max = maxAndMin[0];
min = maxAndMin[1];
if (max == min) {
rsvs.push(0);
} else {
rsvs.push((close - min) / (max - min) * 100);
}
if (nineDaysTicks.length == days) {
nineDaysTicks.shift();
}
if (i == 0) {
lastK = lastD = rsvs[i];
}
curK = 2 / 3 * lastK + 1 / 3 * rsvs[i];
ks.push(curK);
lastK = curK;
curD = 2 / 3 * lastD + 1 / 3 * curK;
ds.push(curD);
lastD = curD;
js.push(3 * curK - 2 * curD);
}
return { "k": ks, "d": ds, "j": js };
};
/**
*
* 计算移动平均线指标, ma的周期为days
*
* @method MA
* @param {Array} ticks
* @param Number days
* 一维数组类型,每个元素为当前Tick的收盘价格
* @return {Array} mas
*/
export const MA = function (ticks, days) {
let maSum = 0;
const mas = [];
for (let i = 0; i < ticks.length; i++) {
maSum += ticks[i];
const _ma = maSum / days;
mas.push(_ma);
}
return mas;
};
/**
*
* 计算boll指标,ma的周期为20日
*
* @method BOLL
* @param {Array} ticks
* 一维数组类型,每个元素为当前Tick的收盘价格
* @return {Object} 返回一个包含upper mid lower属性的对象,每个属性对应的类型为{Array[Number]}
*/
export const BOLL = function (ticks) {
//移动平均线周期为20
const maDays = 20;
const tickBegin = maDays - 1;
let maSum = 0, p = 0;
const ups = [], mas = [], lows = [];
for (let i = 0; i < ticks.length; i++) {
const c = ticks[i];
let ma, md, bstart, mdSum;
maSum += c;
if (i >= tickBegin) {
maSum = maSum - p;
ma = maSum / maDays;
mas.push(ma);
bstart = i - tickBegin;
p = ticks[bstart];
mdSum = ticks.slice(bstart, bstart + maDays).reduce(function (a, b) { return a + Math.pow(b - ma, 2); }, 0);
md = Math.sqrt(mdSum / maDays);
ups.push(ma + 2 * md);
lows.push(ma - 2 * md);
} else {
//ugly constant, just keep the same type for client
ups.push(-1);
mas.push(-1);
lows.push(-1);
}
}
return { "upper": ups, "mid": mas, "lower": lows };
};
/**
*
* 计算rsi指标,分别返回以6日,12日,24日为参考基期的RSI值
*
* @method RSI
* @param {Array} ticks
* 一维数组类型,每个元素为当前Tick的收盘价格
* @return {Object} 返回一个包含rsi6 rsi12 rsi24属性的对象,每个属性对应的类型为{Array[Number]}
*/
export const RSI = function (ticks) {
let lastClosePx = ticks[0];
const days = [6, 12, 24], result = {};
for (let i = 0; i < ticks.length; i++) {
const c = ticks[i];
const m = Math.max(c - lastClosePx, 0), a = Math.abs(c - lastClosePx);
for (let di = 0; di < days.length; di++) {
const d = days[di];
// eslint-disable-next-line no-prototype-builtins
if (!result.hasOwnProperty("rsi" + d)) {
result["lastSm" + d] = result["lastSa" + d] = 0;
result["rsi" + d] = [0];
} else {
result["lastSm" + d] = (m + (d - 1) * result["lastSm" + d]) / d;
result["lastSa" + d] = (a + (d - 1) * result["lastSa" + d]) / d;
if (result["lastSa" + d] != 0) {
result["rsi" + d].push(result["lastSm" + d] / result["lastSa" + d] * 100);
} else {
result["rsi" + d].push(0);
}
}
}
lastClosePx = c;
}
return { "rsi6": result["rsi6"], "rsi12": result["rsi12"], "rsi24": result["rsi24"] };
};
|
9d3356dc252d0a156c06c36e698d23701b6776da | 2,202 | ts | TypeScript | src/components/CalculatorApplication/structs.ts | tommyip/webdows-10 | 771cd0ff0e39a102dc8d7d746485e7c2c007c9b6 | [
"MIT"
] | null | null | null | src/components/CalculatorApplication/structs.ts | tommyip/webdows-10 | 771cd0ff0e39a102dc8d7d746485e7c2c007c9b6 | [
"MIT"
] | 1 | 2022-02-13T19:49:23.000Z | 2022-02-13T19:49:23.000Z | src/components/CalculatorApplication/structs.ts | tommyip/webdows-10 | 771cd0ff0e39a102dc8d7d746485e7c2c007c9b6 | [
"MIT"
] | null | null | null | export function prettify(x: number): string {
return x.toLocaleString('en', { useGrouping: true });
}
export type digit = 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9;
interface InnerNumber {
integer: number;
fractional: boolean | digit[];
}
interface Number {
x?: InnerNumber;
}
export class WorkingNumber {
n: Number;
constructor() {
this.n = { x: undefined };
}
unset() {
this.n.x = undefined;
}
toNumber(): number | undefined {
const x = this.n.x;
if (x) {
const fractional = Array.isArray(x.fractional) && x.fractional.length > 0 ?
Number.parseFloat('.' + x.fractional.join('')) : 0;
return x.integer + fractional;
}
return undefined;
}
toString(): string {
if (this.n.x) {
let out = prettify(this.n.x.integer);
if (this.n.x.fractional !== false) {
out += '.';
}
if (Array.isArray(this.n.x.fractional)) {
out += this.n.x.fractional.join('');
}
return out;
}
return "0";
}
appendDigit(digit: digit) {
if (this.n.x == undefined) {
this.zeroOut();
}
this.n.x = <InnerNumber> this.n.x; // TS hint
if (this.n.x.fractional === true) {
this.n.x.fractional = [];
}
if (this.n.x.fractional) {
this.n.x.fractional.push(digit);
} else {
this.n.x.integer = this.n.x.integer * 10 + digit;
}
}
enterFractional() {
if (this.n.x === undefined) {
this.zeroOut();
}
this.n.x = <InnerNumber> this.n.x; // TS hint
if (typeof this.n.x.fractional === 'boolean') {
this.n.x.fractional = !this.n.x.fractional;
}
}
deleteDigit() {
if (this.n.x) {
if (Array.isArray(this.n.x.fractional)) {
this.n.x.fractional.pop();
if (this.n.x.fractional.length === 0) {
this.n.x.fractional = true;
}
} else if (this.n.x.fractional === true) {
this.n.x.fractional = false;
} else {
this.n.x.integer = Math.trunc(this.n.x.integer / 10);
if (this.n.x.integer === 0) {
this.unset();
}
}
}
}
private zeroOut() {
this.n.x = {
integer: 0,
fractional: false,
};
}
}
| 20.773585 | 81 | 0.529519 | 88 | 9 | 0 | 2 | 3 | 4 | 3 | 0 | 6 | 4 | 1 | 6.555556 | 738 | 0.014905 | 0.004065 | 0.00542 | 0.00542 | 0.001355 | 0 | 0.333333 | 0.227062 | export /* Example usages of 'prettify' are shown below:
prettify(this.n.x.integer);
*/
function prettify(x) {
return x.toLocaleString('en', { useGrouping: true });
}
export type digit = 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9;
interface InnerNumber {
integer;
fractional;
}
interface Number {
x?;
}
export class WorkingNumber {
n;
constructor() {
this.n = { x: undefined };
}
unset() {
this.n.x = undefined;
}
toNumber() {
const x = this.n.x;
if (x) {
const fractional = Array.isArray(x.fractional) && x.fractional.length > 0 ?
Number.parseFloat('.' + x.fractional.join('')) : 0;
return x.integer + fractional;
}
return undefined;
}
toString() {
if (this.n.x) {
let out = prettify(this.n.x.integer);
if (this.n.x.fractional !== false) {
out += '.';
}
if (Array.isArray(this.n.x.fractional)) {
out += this.n.x.fractional.join('');
}
return out;
}
return "0";
}
appendDigit(digit) {
if (this.n.x == undefined) {
this.zeroOut();
}
this.n.x = <InnerNumber> this.n.x; // TS hint
if (this.n.x.fractional === true) {
this.n.x.fractional = [];
}
if (this.n.x.fractional) {
this.n.x.fractional.push(digit);
} else {
this.n.x.integer = this.n.x.integer * 10 + digit;
}
}
enterFractional() {
if (this.n.x === undefined) {
this.zeroOut();
}
this.n.x = <InnerNumber> this.n.x; // TS hint
if (typeof this.n.x.fractional === 'boolean') {
this.n.x.fractional = !this.n.x.fractional;
}
}
deleteDigit() {
if (this.n.x) {
if (Array.isArray(this.n.x.fractional)) {
this.n.x.fractional.pop();
if (this.n.x.fractional.length === 0) {
this.n.x.fractional = true;
}
} else if (this.n.x.fractional === true) {
this.n.x.fractional = false;
} else {
this.n.x.integer = Math.trunc(this.n.x.integer / 10);
if (this.n.x.integer === 0) {
this.unset();
}
}
}
}
private zeroOut() {
this.n.x = {
integer: 0,
fractional: false,
};
}
}
|