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
|
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
a4ed260679d8b286c4673afc0b0a13beaf142e07 | 3,264 | ts | TypeScript | Code/Websites/DanpheEMR/wwwroot/DanpheApp/src/app/accounting/reports/shared/balance-sheet-reportVM.model.ts | MenkaChaugule/hospital-management-emr | 6c9afb0cda5ca4f8ea726e083f57b7a16a35a58d | [
"MIT"
] | 1 | 2022-03-03T09:53:27.000Z | 2022-03-03T09:53:27.000Z | Code/Websites/DanpheEMR/wwwroot/DanpheApp/src/app/accounting/reports/shared/balance-sheet-reportVM.model.ts | MenkaChaugule/hospital-management-emr | 6c9afb0cda5ca4f8ea726e083f57b7a16a35a58d | [
"MIT"
] | null | null | null | Code/Websites/DanpheEMR/wwwroot/DanpheApp/src/app/accounting/reports/shared/balance-sheet-reportVM.model.ts | MenkaChaugule/hospital-management-emr | 6c9afb0cda5ca4f8ea726e083f57b7a16a35a58d | [
"MIT"
] | 3 | 2022-02-01T03:55:18.000Z | 2022-02-02T07:31:08.000Z |
export class BalanceSheetReportVMModel {
public ChartOfAccount: Array<ChartOfAccountModel> = new Array<ChartOfAccountModel>();
public LedgerGroupCategory: Array<LedGroupCategory> = new Array<LedGroupCategory>();
public LedgerGroup: Array<LedGroup> = new Array<LedGroup>();
public Ledger: Array<Led> = new Array<Led>();
public balanceSheetReportVM: Array<ChartOfAccountModel> = new Array<ChartOfAccountModel>();
constructor() {
this.ChartOfAccount = new Array<ChartOfAccountModel>();
this.LedgerGroupCategory = new Array<LedGroupCategory>();
this.LedgerGroup = new Array<LedGroup>();
this.Ledger = new Array<Led>();
this.balanceSheetReportVM = new Array<ChartOfAccountModel>();
}
//this method for mapp tree like data
public MappingReportData() {
this.ChartOfAccount.forEach(coa => {
let temp: ChartOfAccountModel = new ChartOfAccountModel();
temp.ChartOfAccountId = coa.ChartOfAccountId;
temp.ChartOfAccountName = coa.ChartOfAccountName;
this.balanceSheetReportVM.push(temp);
});
this.balanceSheetReportVM.forEach(itm => {
this.LedgerGroupCategory.forEach(itm1 => {
if (itm1.ChartOfAccountId == itm.ChartOfAccountId) {
var temp = new LedGroupCategory();
temp = Object.assign(temp, itm1);
itm.LedGroupCategoryList.push(temp);
}
});
});
this.balanceSheetReportVM.forEach(itm => {
itm.LedGroupCategoryList.forEach(itm1 => {
this.LedgerGroup.forEach(itm2 => {
if (itm2.LedgerGroupCategoryId == itm1.LedgerGroupCategoryId) {
var ledGrpTemp = new LedGroup();
ledGrpTemp = Object.assign(ledGrpTemp, itm2);
itm1.LedGroupList.push(ledGrpTemp);
}
});
});
});
this.balanceSheetReportVM.forEach(itm => {
itm.LedGroupCategoryList.forEach(itm1 => {
itm1.LedGroupList.forEach(itm2 => {
this.Ledger.forEach(itm3 => {
if (itm3.LedgerGroupId == itm2.LedgerGroupId) {
itm2.LedList.push(itm3);
}
});
});
});
});
}
}
class ChartOfAccountModel {
public ChartOfAccountId: number = 0;
public ChartOfAccountName: string = null;
public LedGroupCategoryList: Array<LedGroupCategory> = new Array<LedGroupCategory>();
}
class LedGroupCategory {
LedgerGroupCategoryId: number = 0;
LedgerGroupCategoryName: string = null;
ChartOfAccountId: number = 0;
public LedGroupList: Array<LedGroup> = new Array<LedGroup>();
}
class LedGroup {
public LedgerGroupId: number = 0;
public LedgerGroupCategoryId: number = 0;
public LedgerGroupName: string = null;
public LedList: Array<Led> = new Array<Led>();
}
class Led {
public LedgerGroupId: number = 0;
public LedgerId: number = 0;
public LedgerName: string = null;
public Amount: number = 0;
} | 39.804878 | 95 | 0.588848 | 77 | 12 | 0 | 10 | 3 | 20 | 0 | 0 | 12 | 5 | 0 | 8.583333 | 763 | 0.028834 | 0.003932 | 0.026212 | 0.006553 | 0 | 0 | 0.266667 | 0.260594 |
export class BalanceSheetReportVMModel {
public ChartOfAccount = new Array<ChartOfAccountModel>();
public LedgerGroupCategory = new Array<LedGroupCategory>();
public LedgerGroup = new Array<LedGroup>();
public Ledger = new Array<Led>();
public balanceSheetReportVM = new Array<ChartOfAccountModel>();
constructor() {
this.ChartOfAccount = new Array<ChartOfAccountModel>();
this.LedgerGroupCategory = new Array<LedGroupCategory>();
this.LedgerGroup = new Array<LedGroup>();
this.Ledger = new Array<Led>();
this.balanceSheetReportVM = new Array<ChartOfAccountModel>();
}
//this method for mapp tree like data
public MappingReportData() {
this.ChartOfAccount.forEach(coa => {
let temp = new ChartOfAccountModel();
temp.ChartOfAccountId = coa.ChartOfAccountId;
temp.ChartOfAccountName = coa.ChartOfAccountName;
this.balanceSheetReportVM.push(temp);
});
this.balanceSheetReportVM.forEach(itm => {
this.LedgerGroupCategory.forEach(itm1 => {
if (itm1.ChartOfAccountId == itm.ChartOfAccountId) {
var temp = new LedGroupCategory();
temp = Object.assign(temp, itm1);
itm.LedGroupCategoryList.push(temp);
}
});
});
this.balanceSheetReportVM.forEach(itm => {
itm.LedGroupCategoryList.forEach(itm1 => {
this.LedgerGroup.forEach(itm2 => {
if (itm2.LedgerGroupCategoryId == itm1.LedgerGroupCategoryId) {
var ledGrpTemp = new LedGroup();
ledGrpTemp = Object.assign(ledGrpTemp, itm2);
itm1.LedGroupList.push(ledGrpTemp);
}
});
});
});
this.balanceSheetReportVM.forEach(itm => {
itm.LedGroupCategoryList.forEach(itm1 => {
itm1.LedGroupList.forEach(itm2 => {
this.Ledger.forEach(itm3 => {
if (itm3.LedgerGroupId == itm2.LedgerGroupId) {
itm2.LedList.push(itm3);
}
});
});
});
});
}
}
class ChartOfAccountModel {
public ChartOfAccountId = 0;
public ChartOfAccountName = null;
public LedGroupCategoryList = new Array<LedGroupCategory>();
}
class LedGroupCategory {
LedgerGroupCategoryId = 0;
LedgerGroupCategoryName = null;
ChartOfAccountId = 0;
public LedGroupList = new Array<LedGroup>();
}
class LedGroup {
public LedgerGroupId = 0;
public LedgerGroupCategoryId = 0;
public LedgerGroupName = null;
public LedList = new Array<Led>();
}
class Led {
public LedgerGroupId = 0;
public LedgerId = 0;
public LedgerName = null;
public Amount = 0;
} |
56013b675d2c5276fca785f74daf84664803de98 | 5,038 | ts | TypeScript | src/packages/DaysPicker/date/interface.ts | hanbingxu82/tinkerbell-ui-react | 522ead95c735c3990cda9ba7566f4e54646b734b | [
"MIT"
] | 3 | 2022-03-03T02:08:09.000Z | 2022-03-26T10:52:19.000Z | src/packages/DaysPicker/date/interface.ts | hanbingxu82/tinkerbell-ui-react | 522ead95c735c3990cda9ba7566f4e54646b734b | [
"MIT"
] | null | null | null | src/packages/DaysPicker/date/interface.ts | hanbingxu82/tinkerbell-ui-react | 522ead95c735c3990cda9ba7566f4e54646b734b | [
"MIT"
] | null | null | null | /*
* @Author: your name
* @Date: 2022-04-24 10:11:23
* @LastEditTime: 2022-04-24 16:14:52
* @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/date/interface.ts
*/
// props 天
export interface dayProps {
year: number;
month: number;
active: number;
change: Function;
visible: boolean;
monthRef: any;
show: boolean;
limit: boolean;
}
// props 月
export interface monthProps {
visible: boolean;
active: number;
change: Function;
year: number;
plateChange: Function;
limit: boolean;
}
// props 年
export interface yearProps {
visible: boolean;
active: number;
change: Function;
plateChange: Function;
limit: boolean;
}
// pageday-item type
export type dayItem = {
label: string;
value: number;
disabled: boolean; //禁用
prev: boolean; // 是否属于上一月份
next: boolean; // 是否属于上一月份
week: number; // 星期下标
weekLabel: string; // 星期明文
};
// pageMonth-item type
export type monthItem = {
value: number;
label: string;
disabled: boolean;
};
// 年份
export function getYearList(year: number, limit: boolean) {
let list: Array<monthItem> = [];
let newYear = new Date().getFullYear();
let maxYear = year + 9;
for (let i = year - 3; i < maxYear; i++) {
list.push({
value: i,
label: `${i}`,
disabled: i < newYear && limit,
});
}
return list;
}
// 月份
export function getMonthList(year: number, limit: boolean) {
let list: Array<monthItem> = [];
for (let i = 1; i < 13; i++) {
list.push({
value: i,
label: `${i}月`,
disabled: checkDisabledMonth(year, i) && limit,
});
}
return list;
}
// 月-禁用判定
function checkDisabledMonth(prevYear: number, prevMonth: number) {
const prevTime = new Date(`${prevYear}/${prevMonth}/01`).getTime();
const newDate = new Date();
const year: number = newDate.getFullYear();
let month: number = newDate.getMonth() + 1;
const newTime = new Date(`${year}/${month}/01`).getTime();
return prevTime < newTime;
}
// 日期对照月份表
const monthAsDay = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]; //月份
// 星期列表
export const weekList = ["一", "二", "三", "四", "五", "六", "日"];
// 日-数据列表生成type:0当前月份,1上一月,2下一月
export function getDayList(
year: number,
month: number,
type: number,
limit: boolean
) {
let list: Array<dayItem> = [];
let max: number = year % 4 === 0 && month === 2 ? 1 : 0; // 闰年判定
max = monthAsDay[month - 1] + max; // 定位月份
for (let i = 0; i < max; i++) {
let value = i + 1;
let weekParam = checkWeek(year, month, value);
list.push({
label: value.toString(),
value: value,
disabled: checkDisabled(year, month, value) && limit,
prev: type === 1,
next: type === 2,
week: weekParam.value,
weekLabel: weekParam.label,
});
}
if (type !== 0) {
return list;
} else {
return dayListSupply(list, year, month, limit);
}
}
// 日-数据按周补充
function dayListSupply(
arr: Array<dayItem>,
year: number,
month: number,
limit: boolean
) {
let prevList = getDayList(
month === 1 ? year - 1 : year,
month === 1 ? 12 : month - 1,
1,
limit
);
let nextList = getDayList(
month === 12 ? year + 1 : year,
month === 12 ? 1 : month + 1,
2,
limit
);
// 上月
for (let i = prevList.length - 1; i > 0; i--) {
if (prevList[i].week === 7) {
break;
}
arr.unshift(prevList[i]);
}
// 下月
for (let i = 0; i < nextList.length - 1; i++) {
if (arr.length === 42) {
break;
}
arr.push(nextList[i]);
}
return arr;
}
// 日-禁用判定
export function checkDisabled(
prevYear: number,
prevMonth: number,
prevDay: number
) {
const prevTime = new Date(`${prevYear}/${prevMonth}/${prevDay}`).getTime();
const newDate = new Date();
const year: number = newDate.getFullYear();
let month: number = newDate.getMonth() + 1;
let day: number = newDate.getDate();
const newTime = new Date(`${year}/${month}/${day}`).getTime();
return prevTime < newTime;
}
// 周期-判定星期几
function checkWeek(year: number, month: number, day: number) {
let weekday = [
"星期日",
"星期一",
"星期二",
"星期三",
"星期四",
"星期五",
"星期六",
];
let newDate = new Date(`${year}/${month}/${day}`);
let mark = newDate.getDay();
return {
value: mark === 0 ? 7 : mark,
label: weekday[mark],
};
}
| 25.19 | 111 | 0.526796 | 163 | 7 | 0 | 20 | 31 | 29 | 5 | 6 | 48 | 5 | 0 | 13.428571 | 1,612 | 0.016749 | 0.019231 | 0.01799 | 0.003102 | 0 | 0.068966 | 0.551724 | 0.276572 | /*
* @Author: your name
* @Date: 2022-04-24 10:11:23
* @LastEditTime: 2022-04-24 16:14:52
* @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/date/interface.ts
*/
// props 天
export interface dayProps {
year;
month;
active;
change;
visible;
monthRef;
show;
limit;
}
// props 月
export interface monthProps {
visible;
active;
change;
year;
plateChange;
limit;
}
// props 年
export interface yearProps {
visible;
active;
change;
plateChange;
limit;
}
// pageday-item type
export type dayItem = {
label;
value;
disabled; //禁用
prev; // 是否属于上一月份
next; // 是否属于上一月份
week; // 星期下标
weekLabel; // 星期明文
};
// pageMonth-item type
export type monthItem = {
value;
label;
disabled;
};
// 年份
export function getYearList(year, limit) {
let list = [];
let newYear = new Date().getFullYear();
let maxYear = year + 9;
for (let i = year - 3; i < maxYear; i++) {
list.push({
value: i,
label: `${i}`,
disabled: i < newYear && limit,
});
}
return list;
}
// 月份
export function getMonthList(year, limit) {
let list = [];
for (let i = 1; i < 13; i++) {
list.push({
value: i,
label: `${i}月`,
disabled: checkDisabledMonth(year, i) && limit,
});
}
return list;
}
// 月-禁用判定
/* Example usages of 'checkDisabledMonth' are shown below:
checkDisabledMonth(year, i) && limit;
*/
function checkDisabledMonth(prevYear, prevMonth) {
const prevTime = new Date(`${prevYear}/${prevMonth}/01`).getTime();
const newDate = new Date();
const year = newDate.getFullYear();
let month = newDate.getMonth() + 1;
const newTime = new Date(`${year}/${month}/01`).getTime();
return prevTime < newTime;
}
// 日期对照月份表
const monthAsDay = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]; //月份
// 星期列表
export const weekList = ["一", "二", "三", "四", "五", "六", "日"];
// 日-数据列表生成type:0当前月份,1上一月,2下一月
export /* Example usages of 'getDayList' are shown below:
getDayList(month === 1 ? year - 1 : year, month === 1 ? 12 : month - 1, 1, limit);
getDayList(month === 12 ? year + 1 : year, month === 12 ? 1 : month + 1, 2, limit);
*/
function getDayList(
year,
month,
type,
limit
) {
let list = [];
let max = year % 4 === 0 && month === 2 ? 1 : 0; // 闰年判定
max = monthAsDay[month - 1] + max; // 定位月份
for (let i = 0; i < max; i++) {
let value = i + 1;
let weekParam = checkWeek(year, month, value);
list.push({
label: value.toString(),
value: value,
disabled: checkDisabled(year, month, value) && limit,
prev: type === 1,
next: type === 2,
week: weekParam.value,
weekLabel: weekParam.label,
});
}
if (type !== 0) {
return list;
} else {
return dayListSupply(list, year, month, limit);
}
}
// 日-数据按周补充
/* Example usages of 'dayListSupply' are shown below:
dayListSupply(list, year, month, limit);
*/
function dayListSupply(
arr,
year,
month,
limit
) {
let prevList = getDayList(
month === 1 ? year - 1 : year,
month === 1 ? 12 : month - 1,
1,
limit
);
let nextList = getDayList(
month === 12 ? year + 1 : year,
month === 12 ? 1 : month + 1,
2,
limit
);
// 上月
for (let i = prevList.length - 1; i > 0; i--) {
if (prevList[i].week === 7) {
break;
}
arr.unshift(prevList[i]);
}
// 下月
for (let i = 0; i < nextList.length - 1; i++) {
if (arr.length === 42) {
break;
}
arr.push(nextList[i]);
}
return arr;
}
// 日-禁用判定
export /* Example usages of 'checkDisabled' are shown below:
checkDisabled(year, month, value) && limit;
*/
function checkDisabled(
prevYear,
prevMonth,
prevDay
) {
const prevTime = new Date(`${prevYear}/${prevMonth}/${prevDay}`).getTime();
const newDate = new Date();
const year = newDate.getFullYear();
let month = newDate.getMonth() + 1;
let day = newDate.getDate();
const newTime = new Date(`${year}/${month}/${day}`).getTime();
return prevTime < newTime;
}
// 周期-判定星期几
/* Example usages of 'checkWeek' are shown below:
checkWeek(year, month, value);
*/
function checkWeek(year, month, day) {
let weekday = [
"星期日",
"星期一",
"星期二",
"星期三",
"星期四",
"星期五",
"星期六",
];
let newDate = new Date(`${year}/${month}/${day}`);
let mark = newDate.getDay();
return {
value: mark === 0 ? 7 : mark,
label: weekday[mark],
};
}
|
560ae0186189dfad2554057500eed85afff12d85 | 2,769 | ts | TypeScript | src/shared/tiny-big/helpers.ts | Earnifi/essential-eth | a95999c88a3aad31b90d440bb05ea5a63413ad9f | [
"MIT"
] | 5 | 2022-02-24T16:21:55.000Z | 2022-03-30T20:30:20.000Z | src/shared/tiny-big/helpers.ts | Earnifi/essential-eth | a95999c88a3aad31b90d440bb05ea5a63413ad9f | [
"MIT"
] | 19 | 2022-02-14T15:45:21.000Z | 2022-03-31T20:45:25.000Z | src/shared/tiny-big/helpers.ts | Earnifi/essential-eth | a95999c88a3aad31b90d440bb05ea5a63413ad9f | [
"MIT"
] | 1 | 2022-03-23T21:08:56.000Z | 2022-03-23T21:08:56.000Z | // strips both leading and trailing zeroes
function stripTrailingZeroes(numberString: string) {
const isNegative = numberString.startsWith('-');
numberString = numberString.replace('-', '');
numberString = numberString.replace(
/\.0*$/g,
'' /* for numbers like "1.0" -> "1" */,
);
numberString = numberString.replace(/^0+/, '');
// for numbers like "1.10" -> "1.1"
if (numberString.includes('.')) {
numberString = numberString.replace(/0+$/, '');
}
if (numberString.startsWith('.')) {
// so that ".1" returns as "0.1"
numberString = `0${numberString}`;
}
return `${isNegative ? '-' : ''}${numberString}`;
}
export function scientificStrToDecimalStr(scientificString: string): string {
// Does not contain "e" nor "E"
if (!scientificString.match(/e/i /* lowercase and uppercase E */)) {
return stripTrailingZeroes(scientificString);
}
// eslint-disable-next-line prefer-const
let [base, power] = scientificString.split(
/e/i /* lowercase and uppercase E */,
);
// remove the leading "-" if negative
const isNegative = Number(base) < 0;
base = base.replace('-', '');
base = stripTrailingZeroes(base);
const [wholeNumber, fraction /* move decimal this many places */ = ''] =
base.split('.');
if (Number(power) === 0) {
return `${isNegative ? '-' : ''}${stripTrailingZeroes(base)}`;
} else {
const includesDecimal = base.includes('.');
if (!includesDecimal) {
base = `${base}.`;
}
base = base.replace('.', '');
const baseLength = base.length;
let splitPaddedNumber;
if (Number(power) < 0) {
// move decimal left
if (wholeNumber.length < Math.abs(Number(power))) {
base = base.padStart(
baseLength + Math.abs(Number(power)) - wholeNumber.length,
'0',
);
}
splitPaddedNumber = base.split('');
if (wholeNumber.length < Math.abs(Number(power))) {
// starts with zeroes
splitPaddedNumber = ['.', ...splitPaddedNumber];
} else {
splitPaddedNumber.splice(
splitPaddedNumber.length - Math.abs(Number(power)),
0,
'.',
);
}
} else {
// move decimal right
if (fraction.length < Math.abs(Number(power))) {
base = base.padEnd(
baseLength + Math.abs(Number(power)) - fraction.length,
'0',
);
}
splitPaddedNumber = base.split('');
if (fraction.length > Math.abs(Number(power))) {
splitPaddedNumber.splice(
splitPaddedNumber.length - Math.abs(Number(power)),
0,
'.',
);
}
}
const toReturn = stripTrailingZeroes(splitPaddedNumber.join(''));
return `${isNegative ? '-' : ''}${toReturn}`;
}
}
| 30.766667 | 77 | 0.581076 | 75 | 2 | 0 | 2 | 8 | 0 | 1 | 0 | 3 | 0 | 0 | 35.5 | 737 | 0.005427 | 0.010855 | 0 | 0 | 0 | 0 | 0.25 | 0.218253 | // strips both leading and trailing zeroes
/* Example usages of 'stripTrailingZeroes' are shown below:
stripTrailingZeroes(scientificString);
base = stripTrailingZeroes(base);
stripTrailingZeroes(base);
stripTrailingZeroes(splitPaddedNumber.join(''));
*/
function stripTrailingZeroes(numberString) {
const isNegative = numberString.startsWith('-');
numberString = numberString.replace('-', '');
numberString = numberString.replace(
/\.0*$/g,
'' /* for numbers like "1.0" -> "1" */,
);
numberString = numberString.replace(/^0+/, '');
// for numbers like "1.10" -> "1.1"
if (numberString.includes('.')) {
numberString = numberString.replace(/0+$/, '');
}
if (numberString.startsWith('.')) {
// so that ".1" returns as "0.1"
numberString = `0${numberString}`;
}
return `${isNegative ? '-' : ''}${numberString}`;
}
export function scientificStrToDecimalStr(scientificString) {
// Does not contain "e" nor "E"
if (!scientificString.match(/e/i /* lowercase and uppercase E */)) {
return stripTrailingZeroes(scientificString);
}
// eslint-disable-next-line prefer-const
let [base, power] = scientificString.split(
/e/i /* lowercase and uppercase E */,
);
// remove the leading "-" if negative
const isNegative = Number(base) < 0;
base = base.replace('-', '');
base = stripTrailingZeroes(base);
const [wholeNumber, fraction /* move decimal this many places */ = ''] =
base.split('.');
if (Number(power) === 0) {
return `${isNegative ? '-' : ''}${stripTrailingZeroes(base)}`;
} else {
const includesDecimal = base.includes('.');
if (!includesDecimal) {
base = `${base}.`;
}
base = base.replace('.', '');
const baseLength = base.length;
let splitPaddedNumber;
if (Number(power) < 0) {
// move decimal left
if (wholeNumber.length < Math.abs(Number(power))) {
base = base.padStart(
baseLength + Math.abs(Number(power)) - wholeNumber.length,
'0',
);
}
splitPaddedNumber = base.split('');
if (wholeNumber.length < Math.abs(Number(power))) {
// starts with zeroes
splitPaddedNumber = ['.', ...splitPaddedNumber];
} else {
splitPaddedNumber.splice(
splitPaddedNumber.length - Math.abs(Number(power)),
0,
'.',
);
}
} else {
// move decimal right
if (fraction.length < Math.abs(Number(power))) {
base = base.padEnd(
baseLength + Math.abs(Number(power)) - fraction.length,
'0',
);
}
splitPaddedNumber = base.split('');
if (fraction.length > Math.abs(Number(power))) {
splitPaddedNumber.splice(
splitPaddedNumber.length - Math.abs(Number(power)),
0,
'.',
);
}
}
const toReturn = stripTrailingZeroes(splitPaddedNumber.join(''));
return `${isNegative ? '-' : ''}${toReturn}`;
}
}
|
564ce4c05304b95e15c8469b2dbae42861df1d5d | 3,415 | ts | TypeScript | src/lib/parsers/UrlEncoder.ts | api-client/core | aa157d09b39efa77d49f2d425e7b37828abe0c5b | [
"Apache-2.0"
] | null | null | null | src/lib/parsers/UrlEncoder.ts | api-client/core | aa157d09b39efa77d49f2d425e7b37828abe0c5b | [
"Apache-2.0"
] | 1 | 2022-02-14T00:01:04.000Z | 2022-02-14T00:04:07.000Z | src/lib/parsers/UrlEncoder.ts | advanced-rest-client/core | 2efb946f786d8b46e7131c62e0011f6e090ddec3 | [
"Apache-2.0"
] | null | null | null | export class UrlEncoder {
/**
* Returns a string where all characters that are not valid for a URL
* component have been escaped. The escaping of a character is done by
* converting it into its UTF-8 encoding and then encoding each of the
* resulting bytes as a %xx hexadecimal escape sequence.
* <p>
* Note: this method will convert any the space character into its escape
* short form, '+' rather than %20. It should therefore only be used for
* query-string parts.
*
* <p>
* The following character sets are <em>not</em> escaped by this method:
* <ul>
* <li>ASCII digits or letters</li>
* <li>ASCII punctuation characters:
*
* <pre>- _ . ! ~ * ' ( )</pre>
* </li>
* </ul>
* </p>
*
* <p>
* Notice that this method <em>does</em> encode the URL component delimiter
* characters:<blockquote>
*
* <pre>
* ; / ? : & = + $ , #
* </pre>
*
* </blockquote>
* </p>
*
* @param str A string containing invalid URL characters
* @param replacePlus When set it replaces `%20` with `+`.
* @returns a string with all invalid URL characters escaped
*/
static encodeQueryString(str: string, replacePlus?: boolean): string {
if (!str) {
return str;
}
// normalize
let result = str.toString().replace(/\r?\n/g, "\r\n");
// encode
result = encodeURIComponent(result);
if (replacePlus) {
// replace "%20" with "+" when needed
result = result.replace(/%20/g, "+");
}
return result;
}
/**
* Returns a string where all URL component escape sequences have been
* converted back to their original character representations.
*
* Note: this method will convert the space character escape short form, '+',
* into a space. It should therefore only be used for query-string parts.
*
* @param str A string containing encoded URL component sequences
* @param replacePlus When set it replaces `+` with `%20`.
* @returns string with no encoded URL component encoded sequences
*/
static decodeQueryString(str: string, replacePlus?: boolean): string {
if (!str) {
return str;
}
let result = str;
if (replacePlus) {
result = str.replace(/\+/g, "%20");
}
return decodeURIComponent(result);
}
static strictEncode(str: string): string {
if (!str) {
return str;
}
const escaped = {
'!': '%21',
"'": '%27',
'(': '%28',
')': '%29',
};
return encodeURIComponent(str).replace(/\*/g, '%2A')
// @ts-ignore
.replace(/[!'()*]/g, (c) => escaped[c] );
}
/**
* For URI templates encodes the URL string without encoding the reserved characters.
*/
static encodeReserved(str: string): string {
if (!str) {
return str;
}
const expression = /%(21|23|24|26|27|28|29|2A|2B|2C|2F|3A|3B|3D|3F|40|5B|5D)/ig;
const map = {
// gen-delims
'%3A': ':',
'%2F': '/',
'%3F': '?',
'%23': '#',
'%5B': '[',
'%5D': ']',
'%40': '@',
// sub-delims
'%21': '!',
'%24': '$',
'%26': '&',
'%27': '\'',
'%28': '(',
'%29': ')',
'%2A': '*',
'%2B': '+',
'%2C': ',',
'%3B': ';',
'%3D': '='
};
let result = UrlEncoder.strictEncode(str);
// @ts-ignore
result = result.replace(expression, (c) => map[c]);
return result;
}
}
| 27.103175 | 87 | 0.552562 | 65 | 6 | 0 | 8 | 6 | 0 | 1 | 0 | 10 | 1 | 0 | 9.5 | 973 | 0.014388 | 0.006166 | 0 | 0.001028 | 0 | 0 | 0.5 | 0.225124 | export class UrlEncoder {
/**
* Returns a string where all characters that are not valid for a URL
* component have been escaped. The escaping of a character is done by
* converting it into its UTF-8 encoding and then encoding each of the
* resulting bytes as a %xx hexadecimal escape sequence.
* <p>
* Note: this method will convert any the space character into its escape
* short form, '+' rather than %20. It should therefore only be used for
* query-string parts.
*
* <p>
* The following character sets are <em>not</em> escaped by this method:
* <ul>
* <li>ASCII digits or letters</li>
* <li>ASCII punctuation characters:
*
* <pre>- _ . ! ~ * ' ( )</pre>
* </li>
* </ul>
* </p>
*
* <p>
* Notice that this method <em>does</em> encode the URL component delimiter
* characters:<blockquote>
*
* <pre>
* ; / ? : & = + $ , #
* </pre>
*
* </blockquote>
* </p>
*
* @param str A string containing invalid URL characters
* @param replacePlus When set it replaces `%20` with `+`.
* @returns a string with all invalid URL characters escaped
*/
static encodeQueryString(str, replacePlus?) {
if (!str) {
return str;
}
// normalize
let result = str.toString().replace(/\r?\n/g, "\r\n");
// encode
result = encodeURIComponent(result);
if (replacePlus) {
// replace "%20" with "+" when needed
result = result.replace(/%20/g, "+");
}
return result;
}
/**
* Returns a string where all URL component escape sequences have been
* converted back to their original character representations.
*
* Note: this method will convert the space character escape short form, '+',
* into a space. It should therefore only be used for query-string parts.
*
* @param str A string containing encoded URL component sequences
* @param replacePlus When set it replaces `+` with `%20`.
* @returns string with no encoded URL component encoded sequences
*/
static decodeQueryString(str, replacePlus?) {
if (!str) {
return str;
}
let result = str;
if (replacePlus) {
result = str.replace(/\+/g, "%20");
}
return decodeURIComponent(result);
}
static strictEncode(str) {
if (!str) {
return str;
}
const escaped = {
'!': '%21',
"'": '%27',
'(': '%28',
')': '%29',
};
return encodeURIComponent(str).replace(/\*/g, '%2A')
// @ts-ignore
.replace(/[!'()*]/g, (c) => escaped[c] );
}
/**
* For URI templates encodes the URL string without encoding the reserved characters.
*/
static encodeReserved(str) {
if (!str) {
return str;
}
const expression = /%(21|23|24|26|27|28|29|2A|2B|2C|2F|3A|3B|3D|3F|40|5B|5D)/ig;
const map = {
// gen-delims
'%3A': ':',
'%2F': '/',
'%3F': '?',
'%23': '#',
'%5B': '[',
'%5D': ']',
'%40': '@',
// sub-delims
'%21': '!',
'%24': '$',
'%26': '&',
'%27': '\'',
'%28': '(',
'%29': ')',
'%2A': '*',
'%2B': '+',
'%2C': ',',
'%3B': ';',
'%3D': '='
};
let result = UrlEncoder.strictEncode(str);
// @ts-ignore
result = result.replace(expression, (c) => map[c]);
return result;
}
}
|
566e0bf1c5e4eafebc876c82fc048623ab53ab35 | 1,858 | ts | TypeScript | source/client/components/AddRecipeModal/AddRecipeModal.reducer.ts | vladimir-skvortsov/recipe-app | c6705bc6ea80effeb3eed68cb0142f708e35acb4 | [
"Apache-2.0"
] | null | null | null | source/client/components/AddRecipeModal/AddRecipeModal.reducer.ts | vladimir-skvortsov/recipe-app | c6705bc6ea80effeb3eed68cb0142f708e35acb4 | [
"Apache-2.0"
] | 1 | 2022-01-27T16:06:47.000Z | 2022-01-27T16:06:47.000Z | source/client/components/AddRecipeModal/AddRecipeModal.reducer.ts | vladimir-skvortsov/recipe-app | c6705bc6ea80effeb3eed68cb0142f708e35acb4 | [
"Apache-2.0"
] | null | null | null | type Action =
| { type: 'closeTag', tag: string }
| { type: 'showInput' }
| { type: 'confirmInput', tag?: string }
| { type: 'reset' }
| { type: 'addIngredient' }
| { type: 'removeIngredient', id: number }
| { type: 'addDirection' }
| { type: 'removeDirection', id: number }
interface State {
tags: string[]
inputVisible: boolean
ingredients: number[]
directions: number[]
}
let ingredientId = 0
let directionId = 0
export const initialState = {
tags: [],
inputVisible: false,
ingredients: [ingredientId],
directions: [directionId],
}
const reducer = (state: State, action: Action) => {
switch (action.type) {
case 'closeTag':
return { ...state, tags: state.tags.filter(tag => tag !== action.tag) }
case 'reset':
return initialState
case 'showInput':
return { ...state, inputVisible: true }
case 'confirmInput':
let tag = action.tag
if (!tag) return { ...state, inputVisible: false }
tag = tag.trim()
const { tags } = state
let newTags = tags
if (tag && tags.indexOf(tag) === -1) newTags = [...tags, tag]
return { ...state, inputVisible: false, tags: newTags }
case 'addIngredient':
ingredientId += 1
return {
...state,
ingredients: [...state.ingredients, ingredientId],
}
case 'removeIngredient':
return {
...state,
ingredients: state.ingredients.filter(index => index !== action.id),
}
case 'addDirection':
directionId += 1
return {
...state,
directions: [...state.directions, directionId],
}
case 'removeDirection':
return {
...state,
directions: state.directions.filter(index => index !== action.id),
}
default:
throw new Error('Unexpected action.')
}
}
export default reducer
| 22.658537 | 77 | 0.582347 | 66 | 4 | 0 | 5 | 7 | 4 | 0 | 0 | 8 | 2 | 0 | 10.75 | 482 | 0.018672 | 0.014523 | 0.008299 | 0.004149 | 0 | 0 | 0.4 | 0.267378 | type Action =
| { type, tag }
| { type }
| { type, tag? }
| { type }
| { type }
| { type, id }
| { type }
| { type, id }
interface State {
tags
inputVisible
ingredients
directions
}
let ingredientId = 0
let directionId = 0
export const initialState = {
tags: [],
inputVisible: false,
ingredients: [ingredientId],
directions: [directionId],
}
/* Example usages of 'reducer' are shown below:
;
*/
const reducer = (state, action) => {
switch (action.type) {
case 'closeTag':
return { ...state, tags: state.tags.filter(tag => tag !== action.tag) }
case 'reset':
return initialState
case 'showInput':
return { ...state, inputVisible: true }
case 'confirmInput':
let tag = action.tag
if (!tag) return { ...state, inputVisible: false }
tag = tag.trim()
const { tags } = state
let newTags = tags
if (tag && tags.indexOf(tag) === -1) newTags = [...tags, tag]
return { ...state, inputVisible: false, tags: newTags }
case 'addIngredient':
ingredientId += 1
return {
...state,
ingredients: [...state.ingredients, ingredientId],
}
case 'removeIngredient':
return {
...state,
ingredients: state.ingredients.filter(index => index !== action.id),
}
case 'addDirection':
directionId += 1
return {
...state,
directions: [...state.directions, directionId],
}
case 'removeDirection':
return {
...state,
directions: state.directions.filter(index => index !== action.id),
}
default:
throw new Error('Unexpected action.')
}
}
export default reducer
|
56adb91b1ef4948b08a70815c7446daa4083f9e4 | 2,444 | ts | TypeScript | play/resolver.ts | cabinet-fe/element-pro | defa43df639958ba5c17df6d0f5eb1d0b63ba5f6 | [
"MIT"
] | null | null | null | play/resolver.ts | cabinet-fe/element-pro | defa43df639958ba5c17df6d0f5eb1d0b63ba5f6 | [
"MIT"
] | 12 | 2022-03-14T10:10:26.000Z | 2022-03-22T09:56:29.000Z | play/resolver.ts | cabinet-fe/element-pro | defa43df639958ba5c17df6d0f5eb1d0b63ba5f6 | [
"MIT"
] | null | null | null | export interface ElementUltraResolverOptions {
/**
* use commonjs lib & source css or scss for ssr
*/
ssr?: boolean
/**
* auto import for directives
*
* @default true
*/
directives?: boolean
/**
* exclude component name, if match do not resolve the name
*/
exclude?: RegExp
}
type ElementUltraResolverOptionsResolved = Required<
Omit<ElementUltraResolverOptions, 'exclude'>
> &
Pick<ElementUltraResolverOptions, 'exclude'>
function getSideEffects(dirName: string): any {
const esComponentsFolder = '@element-ultra/components'
return `${esComponentsFolder}/${dirName}/style/index`
}
function kebabCase(key: string) {
const result = key.replace(/([A-Z])/g, ' $1').trim()
return result.split(' ').join('-').toLowerCase()
}
function resolveComponent(name: string): any | undefined {
if (!name.match(/^El[A-Z]/)) return
const partialName = kebabCase(name.slice(2)) // ElTableColumn -> table-column
return {
importName: name,
path: `element-ultra`,
sideEffects: getSideEffects(partialName),
}
}
function resolveDirective(
name: string,
options: ElementUltraResolverOptionsResolved
): any | undefined {
if (!options.directives) return
const directives: Record<string, { importName: string; styleName: string }> =
{
Loading: { importName: 'ElLoadingDirective', styleName: 'loading' },
Popover: { importName: 'ElPopoverDirective', styleName: 'popover' },
InfiniteScroll: {
importName: 'ElInfiniteScroll',
styleName: 'infinite-scroll',
},
}
const directive = directives[name]
if (!directive) return
return {
importName: directive.importName,
path: `element-ultra`,
sideEffects: getSideEffects(directive.styleName),
}
}
export function ElementUltraResolver(
options: ElementUltraResolverOptions = {}
): any[] {
let optionsResolved: ElementUltraResolverOptionsResolved
async function resolveOptions() {
if (optionsResolved) return optionsResolved
optionsResolved = {
ssr: false,
directives: true,
exclude: undefined,
...options,
}
return optionsResolved
}
return [
{
type: 'component',
resolve: async (name: string) => {
return resolveComponent(name)
},
},
{
type: 'directive',
resolve: async (name: string) => {
return resolveDirective(name, await resolveOptions())
},
},
]
}
| 23.5 | 79 | 0.663257 | 77 | 8 | 0 | 8 | 6 | 3 | 5 | 4 | 11 | 2 | 0 | 7.875 | 621 | 0.025765 | 0.009662 | 0.004831 | 0.003221 | 0 | 0.16 | 0.44 | 0.265266 | export interface ElementUltraResolverOptions {
/**
* use commonjs lib & source css or scss for ssr
*/
ssr?
/**
* auto import for directives
*
* @default true
*/
directives?
/**
* exclude component name, if match do not resolve the name
*/
exclude?
}
type ElementUltraResolverOptionsResolved = Required<
Omit<ElementUltraResolverOptions, 'exclude'>
> &
Pick<ElementUltraResolverOptions, 'exclude'>
/* Example usages of 'getSideEffects' are shown below:
getSideEffects(partialName);
getSideEffects(directive.styleName);
*/
function getSideEffects(dirName) {
const esComponentsFolder = '@element-ultra/components'
return `${esComponentsFolder}/${dirName}/style/index`
}
/* Example usages of 'kebabCase' are shown below:
kebabCase(name.slice(2)) // ElTableColumn -> table-column
;
*/
function kebabCase(key) {
const result = key.replace(/([A-Z])/g, ' $1').trim()
return result.split(' ').join('-').toLowerCase()
}
/* Example usages of 'resolveComponent' are shown below:
resolveComponent(name);
*/
function resolveComponent(name) {
if (!name.match(/^El[A-Z]/)) return
const partialName = kebabCase(name.slice(2)) // ElTableColumn -> table-column
return {
importName: name,
path: `element-ultra`,
sideEffects: getSideEffects(partialName),
}
}
/* Example usages of 'resolveDirective' are shown below:
resolveDirective(name, await resolveOptions());
*/
function resolveDirective(
name,
options
) {
if (!options.directives) return
const directives =
{
Loading: { importName: 'ElLoadingDirective', styleName: 'loading' },
Popover: { importName: 'ElPopoverDirective', styleName: 'popover' },
InfiniteScroll: {
importName: 'ElInfiniteScroll',
styleName: 'infinite-scroll',
},
}
const directive = directives[name]
if (!directive) return
return {
importName: directive.importName,
path: `element-ultra`,
sideEffects: getSideEffects(directive.styleName),
}
}
export function ElementUltraResolver(
options = {}
) {
let optionsResolved
/* Example usages of 'resolveOptions' are shown below:
resolveOptions();
*/
async function resolveOptions() {
if (optionsResolved) return optionsResolved
optionsResolved = {
ssr: false,
directives: true,
exclude: undefined,
...options,
}
return optionsResolved
}
return [
{
type: 'component',
resolve: async (name) => {
return resolveComponent(name)
},
},
{
type: 'directive',
resolve: async (name) => {
return resolveDirective(name, await resolveOptions())
},
},
]
}
|
c2899385bbb147afefc59113ba8c23e621b080b1 | 12,785 | ts | TypeScript | packages/crypto/src/hashes/sha256.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/sha256.ts | eike-hass/iota.js | 18ddf1ab7ffdd2ef59c6b345fe9ec70a4629bb48 | [
"Apache-2.0"
] | null | null | null | packages/crypto/src/hashes/sha256.ts | eike-hass/iota.js | 18ddf1ab7ffdd2ef59c6b345fe9ec70a4629bb48 | [
"Apache-2.0"
] | null | null | null | // Copyright 2020 IOTA Stiftung
// SPDX-License-Identifier: Apache-2.0
/* eslint-disable no-bitwise */
/* eslint-disable unicorn/prefer-math-trunc */
/**
* Class to help with Sha256 scheme.
* TypeScript conversion from https://github.com/emn178/js-sha256.
*/
export class Sha256 {
/**
* Sha256 256.
*/
public static readonly SIZE_256: number = 256;
/**
* Sha256 224.
*/
public static readonly SIZE_224: number = 224;
/**
* Extra constants.
* @internal
*/
private static readonly EXTRA: number[] = [-2147483648, 8388608, 32768, 128];
/**
* Shift constants.
* @internal
*/
private static readonly SHIFT: number[] = [24, 16, 8, 0];
/**
* K.
* @internal
*/
private static readonly K: Uint32Array = Uint32Array.from([
0x428a2f98, 0x71374491, 0xb5c0fbcf, 0xe9b5dba5, 0x3956c25b, 0x59f111f1, 0x923f82a4, 0xab1c5ed5, 0xd807aa98,
0x12835b01, 0x243185be, 0x550c7dc3, 0x72be5d74, 0x80deb1fe, 0x9bdc06a7, 0xc19bf174, 0xe49b69c1, 0xefbe4786,
0x0fc19dc6, 0x240ca1cc, 0x2de92c6f, 0x4a7484aa, 0x5cb0a9dc, 0x76f988da, 0x983e5152, 0xa831c66d, 0xb00327c8,
0xbf597fc7, 0xc6e00bf3, 0xd5a79147, 0x06ca6351, 0x14292967, 0x27b70a85, 0x2e1b2138, 0x4d2c6dfc, 0x53380d13,
0x650a7354, 0x766a0abb, 0x81c2c92e, 0x92722c85, 0xa2bfe8a1, 0xa81a664b, 0xc24b8b70, 0xc76c51a3, 0xd192e819,
0xd6990624, 0xf40e3585, 0x106aa070, 0x19a4c116, 0x1e376c08, 0x2748774c, 0x34b0bcb5, 0x391c0cb3, 0x4ed8aa4a,
0x5b9cca4f, 0x682e6ff3, 0x748f82ee, 0x78a5636f, 0x84c87814, 0x8cc70208, 0x90befffa, 0xa4506ceb, 0xbef9a3f7,
0xc67178f2
]);
/**
* Blocks.
* @internal
*/
private readonly _blocks: number[] = [];
/**
* Bits.
* @internal
*/
private readonly _bits: number;
/**
* H0.
* @internal
*/
private _h0: number;
/**
* H1.
* @internal
*/
private _h1: number;
/**
* H2.
* @internal
*/
private _h2: number;
/**
* H3.
* @internal
*/
private _h3: number;
/**
* H4.
* @internal
*/
private _h4: number;
/**
* H5.
* @internal
*/
private _h5: number;
/**
* H6.
* @internal
*/
private _h6: number;
/**
* H7.
* @internal
*/
private _h7: number;
/**
* Block.
* @internal
*/
private _block: number;
/**
* Start.
* @internal
*/
private _start: number;
/**
* Bytes.
* @internal
*/
private _bytes: number;
/**
* h Bytes.
* @internal
*/
private _hBytes: number;
/**
* Last byte index.
* @internal
*/
private _lastByteIndex: number;
/**
* Is it finalized.
* @internal
*/
private _finalized: boolean;
/**
* Is it hashed.
* @internal
*/
private _hashed: boolean;
/**
* Is this the first pass.
* @internal
*/
private _first: boolean;
/**
* Create a new instance of Sha256.
* @param bits The number of bits.
*/
constructor(bits: number = Sha256.SIZE_256) {
if (bits !== Sha256.SIZE_224 && bits !== Sha256.SIZE_256) {
throw new Error("Only 224 or 256 bits are supported");
}
this._blocks = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0];
if (bits === Sha256.SIZE_224) {
this._h0 = 0xc1059ed8;
this._h1 = 0x367cd507;
this._h2 = 0x3070dd17;
this._h3 = 0xf70e5939;
this._h4 = 0xffc00b31;
this._h5 = 0x68581511;
this._h6 = 0x64f98fa7;
this._h7 = 0xbefa4fa4;
} else {
this._h0 = 0x6a09e667;
this._h1 = 0xbb67ae85;
this._h2 = 0x3c6ef372;
this._h3 = 0xa54ff53a;
this._h4 = 0x510e527f;
this._h5 = 0x9b05688c;
this._h6 = 0x1f83d9ab;
this._h7 = 0x5be0cd19;
}
this._bits = bits;
this._block = 0;
this._start = 0;
this._bytes = 0;
this._hBytes = 0;
this._lastByteIndex = 0;
this._finalized = false;
this._hashed = false;
this._first = true;
}
/**
* Perform Sum 256 on the data.
* @param data The data to operate on.
* @returns The sum 256 of the data.
*/
public static sum256(data: Uint8Array): Uint8Array {
const b2b = new Sha256(Sha256.SIZE_256);
b2b.update(data);
return b2b.digest();
}
/**
* Perform Sum 224 on the data.
* @param data The data to operate on.
* @returns The sum 224 of the data.
*/
public static sum224(data: Uint8Array): Uint8Array {
const b2b = new Sha256(Sha256.SIZE_224);
b2b.update(data);
return b2b.digest();
}
/**
* Update the hash with the data.
* @param message The data to update the hash with.
* @returns The instance for chaining.
*/
public update(message: Uint8Array): Sha256 {
if (this._finalized) {
throw new Error("The hash has already been finalized.");
}
let index = 0;
let i;
const length = message.length;
const blocks = this._blocks;
while (index < length) {
if (this._hashed) {
this._hashed = false;
blocks[0] = this._block;
blocks[1] = 0;
blocks[2] = 0;
blocks[3] = 0;
blocks[4] = 0;
blocks[5] = 0;
blocks[6] = 0;
blocks[7] = 0;
blocks[8] = 0;
blocks[9] = 0;
blocks[10] = 0;
blocks[11] = 0;
blocks[12] = 0;
blocks[13] = 0;
blocks[14] = 0;
blocks[15] = 0;
blocks[16] = 0;
}
for (i = this._start; index < length && i < 64; ++index) {
blocks[i >> 2] |= message[index] << Sha256.SHIFT[i++ & 3];
}
this._lastByteIndex = i;
this._bytes += i - this._start;
if (i >= 64) {
this._block = blocks[16];
this._start = i - 64;
this.hash();
this._hashed = true;
} else {
this._start = i;
}
}
if (this._bytes > 4294967295) {
this._hBytes += Math.trunc(this._bytes / 4294967296);
this._bytes %= 4294967296;
}
return this;
}
/**
* Get the digest.
* @returns The digest.
*/
public digest(): Uint8Array {
this.finalize();
const h0 = this._h0;
const h1 = this._h1;
const h2 = this._h2;
const h3 = this._h3;
const h4 = this._h4;
const h5 = this._h5;
const h6 = this._h6;
const h7 = this._h7;
const arr = [
(h0 >> 24) & 0xff,
(h0 >> 16) & 0xff,
(h0 >> 8) & 0xff,
h0 & 0xff,
(h1 >> 24) & 0xff,
(h1 >> 16) & 0xff,
(h1 >> 8) & 0xff,
h1 & 0xff,
(h2 >> 24) & 0xff,
(h2 >> 16) & 0xff,
(h2 >> 8) & 0xff,
h2 & 0xff,
(h3 >> 24) & 0xff,
(h3 >> 16) & 0xff,
(h3 >> 8) & 0xff,
h3 & 0xff,
(h4 >> 24) & 0xff,
(h4 >> 16) & 0xff,
(h4 >> 8) & 0xff,
h4 & 0xff,
(h5 >> 24) & 0xff,
(h5 >> 16) & 0xff,
(h5 >> 8) & 0xff,
h5 & 0xff,
(h6 >> 24) & 0xff,
(h6 >> 16) & 0xff,
(h6 >> 8) & 0xff,
h6 & 0xff
];
if (this._bits === Sha256.SIZE_256) {
arr.push((h7 >> 24) & 0xff, (h7 >> 16) & 0xff, (h7 >> 8) & 0xff, h7 & 0xff);
}
return Uint8Array.from(arr);
}
/**
* Finalize the hash.
* @internal
*/
private finalize(): void {
if (this._finalized) {
return;
}
this._finalized = true;
const blocks = this._blocks;
const i = this._lastByteIndex;
blocks[16] = this._block;
blocks[i >> 2] |= Sha256.EXTRA[i & 3];
this._block = blocks[16];
if (i >= 56) {
if (!this._hashed) {
this.hash();
}
blocks[0] = this._block;
blocks[1] = 0;
blocks[2] = 0;
blocks[3] = 0;
blocks[4] = 0;
blocks[5] = 0;
blocks[6] = 0;
blocks[7] = 0;
blocks[8] = 0;
blocks[9] = 0;
blocks[10] = 0;
blocks[11] = 0;
blocks[12] = 0;
blocks[13] = 0;
blocks[14] = 0;
blocks[15] = 0;
blocks[16] = 0;
}
blocks[14] = (this._hBytes << 3) | (this._bytes >>> 29);
blocks[15] = this._bytes << 3;
this.hash();
}
/**
* Perform the hash.
* @internal
*/
private hash(): void {
let a = this._h0;
let b = this._h1;
let c = this._h2;
let d = this._h3;
let e = this._h4;
let f = this._h5;
let g = this._h6;
let h = this._h7;
const blocks = this._blocks;
let j;
let s0;
let s1;
let maj;
let t1;
let t2;
let ch;
let ab;
let da;
let cd;
let bc;
for (j = 16; j < 64; ++j) {
// rightrotate
t1 = blocks[j - 15];
s0 = ((t1 >>> 7) | (t1 << 25)) ^ ((t1 >>> 18) | (t1 << 14)) ^ (t1 >>> 3);
t1 = blocks[j - 2];
s1 = ((t1 >>> 17) | (t1 << 15)) ^ ((t1 >>> 19) | (t1 << 13)) ^ (t1 >>> 10);
blocks[j] = (blocks[j - 16] + s0 + blocks[j - 7] + s1) << 0;
}
bc = b & c;
for (j = 0; j < 64; j += 4) {
if (this._first) {
if (this._bits === Sha256.SIZE_224) {
ab = 300032;
t1 = blocks[0] - 1413257819;
h = (t1 - 150054599) << 0;
d = (t1 + 24177077) << 0;
} else {
ab = 704751109;
t1 = blocks[0] - 210244248;
h = (t1 - 1521486534) << 0;
d = (t1 + 143694565) << 0;
}
this._first = false;
} else {
s0 = ((a >>> 2) | (a << 30)) ^ ((a >>> 13) | (a << 19)) ^ ((a >>> 22) | (a << 10));
s1 = ((e >>> 6) | (e << 26)) ^ ((e >>> 11) | (e << 21)) ^ ((e >>> 25) | (e << 7));
ab = a & b;
maj = ab ^ (a & c) ^ bc;
ch = (e & f) ^ (~e & g);
t1 = h + s1 + ch + Sha256.K[j] + blocks[j];
t2 = s0 + maj;
h = (d + t1) << 0;
d = (t1 + t2) << 0;
}
s0 = ((d >>> 2) | (d << 30)) ^ ((d >>> 13) | (d << 19)) ^ ((d >>> 22) | (d << 10));
s1 = ((h >>> 6) | (h << 26)) ^ ((h >>> 11) | (h << 21)) ^ ((h >>> 25) | (h << 7));
da = d & a;
maj = da ^ (d & b) ^ ab;
ch = (h & e) ^ (~h & f);
t1 = g + s1 + ch + Sha256.K[j + 1] + blocks[j + 1];
t2 = s0 + maj;
g = (c + t1) << 0;
c = (t1 + t2) << 0;
s0 = ((c >>> 2) | (c << 30)) ^ ((c >>> 13) | (c << 19)) ^ ((c >>> 22) | (c << 10));
s1 = ((g >>> 6) | (g << 26)) ^ ((g >>> 11) | (g << 21)) ^ ((g >>> 25) | (g << 7));
cd = c & d;
maj = cd ^ (c & a) ^ da;
ch = (g & h) ^ (~g & e);
t1 = f + s1 + ch + Sha256.K[j + 2] + blocks[j + 2];
t2 = s0 + maj;
f = (b + t1) << 0;
b = (t1 + t2) << 0;
s0 = ((b >>> 2) | (b << 30)) ^ ((b >>> 13) | (b << 19)) ^ ((b >>> 22) | (b << 10));
s1 = ((f >>> 6) | (f << 26)) ^ ((f >>> 11) | (f << 21)) ^ ((f >>> 25) | (f << 7));
bc = b & c;
maj = bc ^ (b & d) ^ cd;
ch = (f & g) ^ (~f & h);
t1 = e + s1 + ch + Sha256.K[j + 3] + blocks[j + 3];
t2 = s0 + maj;
e = (a + t1) << 0;
a = (t1 + t2) << 0;
}
this._h0 += Math.trunc(a);
this._h1 += Math.trunc(b);
this._h2 += Math.trunc(c);
this._h3 += Math.trunc(d);
this._h4 += Math.trunc(e);
this._h5 += Math.trunc(f);
this._h6 += Math.trunc(g);
this._h7 += Math.trunc(h);
}
}
| 27.029598 | 115 | 0.416269 | 299 | 7 | 0 | 4 | 37 | 23 | 4 | 0 | 25 | 1 | 0 | 35.857143 | 4,903 | 0.002244 | 0.007546 | 0.004691 | 0.000204 | 0 | 0 | 0.352113 | 0.200955 | // Copyright 2020 IOTA Stiftung
// SPDX-License-Identifier: Apache-2.0
/* eslint-disable no-bitwise */
/* eslint-disable unicorn/prefer-math-trunc */
/**
* Class to help with Sha256 scheme.
* TypeScript conversion from https://github.com/emn178/js-sha256.
*/
export class Sha256 {
/**
* Sha256 256.
*/
public static readonly SIZE_256 = 256;
/**
* Sha256 224.
*/
public static readonly SIZE_224 = 224;
/**
* Extra constants.
* @internal
*/
private static readonly EXTRA = [-2147483648, 8388608, 32768, 128];
/**
* Shift constants.
* @internal
*/
private static readonly SHIFT = [24, 16, 8, 0];
/**
* K.
* @internal
*/
private static readonly K = Uint32Array.from([
0x428a2f98, 0x71374491, 0xb5c0fbcf, 0xe9b5dba5, 0x3956c25b, 0x59f111f1, 0x923f82a4, 0xab1c5ed5, 0xd807aa98,
0x12835b01, 0x243185be, 0x550c7dc3, 0x72be5d74, 0x80deb1fe, 0x9bdc06a7, 0xc19bf174, 0xe49b69c1, 0xefbe4786,
0x0fc19dc6, 0x240ca1cc, 0x2de92c6f, 0x4a7484aa, 0x5cb0a9dc, 0x76f988da, 0x983e5152, 0xa831c66d, 0xb00327c8,
0xbf597fc7, 0xc6e00bf3, 0xd5a79147, 0x06ca6351, 0x14292967, 0x27b70a85, 0x2e1b2138, 0x4d2c6dfc, 0x53380d13,
0x650a7354, 0x766a0abb, 0x81c2c92e, 0x92722c85, 0xa2bfe8a1, 0xa81a664b, 0xc24b8b70, 0xc76c51a3, 0xd192e819,
0xd6990624, 0xf40e3585, 0x106aa070, 0x19a4c116, 0x1e376c08, 0x2748774c, 0x34b0bcb5, 0x391c0cb3, 0x4ed8aa4a,
0x5b9cca4f, 0x682e6ff3, 0x748f82ee, 0x78a5636f, 0x84c87814, 0x8cc70208, 0x90befffa, 0xa4506ceb, 0xbef9a3f7,
0xc67178f2
]);
/**
* Blocks.
* @internal
*/
private readonly _blocks = [];
/**
* Bits.
* @internal
*/
private readonly _bits;
/**
* H0.
* @internal
*/
private _h0;
/**
* H1.
* @internal
*/
private _h1;
/**
* H2.
* @internal
*/
private _h2;
/**
* H3.
* @internal
*/
private _h3;
/**
* H4.
* @internal
*/
private _h4;
/**
* H5.
* @internal
*/
private _h5;
/**
* H6.
* @internal
*/
private _h6;
/**
* H7.
* @internal
*/
private _h7;
/**
* Block.
* @internal
*/
private _block;
/**
* Start.
* @internal
*/
private _start;
/**
* Bytes.
* @internal
*/
private _bytes;
/**
* h Bytes.
* @internal
*/
private _hBytes;
/**
* Last byte index.
* @internal
*/
private _lastByteIndex;
/**
* Is it finalized.
* @internal
*/
private _finalized;
/**
* Is it hashed.
* @internal
*/
private _hashed;
/**
* Is this the first pass.
* @internal
*/
private _first;
/**
* Create a new instance of Sha256.
* @param bits The number of bits.
*/
constructor(bits = Sha256.SIZE_256) {
if (bits !== Sha256.SIZE_224 && bits !== Sha256.SIZE_256) {
throw new Error("Only 224 or 256 bits are supported");
}
this._blocks = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0];
if (bits === Sha256.SIZE_224) {
this._h0 = 0xc1059ed8;
this._h1 = 0x367cd507;
this._h2 = 0x3070dd17;
this._h3 = 0xf70e5939;
this._h4 = 0xffc00b31;
this._h5 = 0x68581511;
this._h6 = 0x64f98fa7;
this._h7 = 0xbefa4fa4;
} else {
this._h0 = 0x6a09e667;
this._h1 = 0xbb67ae85;
this._h2 = 0x3c6ef372;
this._h3 = 0xa54ff53a;
this._h4 = 0x510e527f;
this._h5 = 0x9b05688c;
this._h6 = 0x1f83d9ab;
this._h7 = 0x5be0cd19;
}
this._bits = bits;
this._block = 0;
this._start = 0;
this._bytes = 0;
this._hBytes = 0;
this._lastByteIndex = 0;
this._finalized = false;
this._hashed = false;
this._first = true;
}
/**
* Perform Sum 256 on the data.
* @param data The data to operate on.
* @returns The sum 256 of the data.
*/
public static sum256(data) {
const b2b = new Sha256(Sha256.SIZE_256);
b2b.update(data);
return b2b.digest();
}
/**
* Perform Sum 224 on the data.
* @param data The data to operate on.
* @returns The sum 224 of the data.
*/
public static sum224(data) {
const b2b = new Sha256(Sha256.SIZE_224);
b2b.update(data);
return b2b.digest();
}
/**
* Update the hash with the data.
* @param message The data to update the hash with.
* @returns The instance for chaining.
*/
public update(message) {
if (this._finalized) {
throw new Error("The hash has already been finalized.");
}
let index = 0;
let i;
const length = message.length;
const blocks = this._blocks;
while (index < length) {
if (this._hashed) {
this._hashed = false;
blocks[0] = this._block;
blocks[1] = 0;
blocks[2] = 0;
blocks[3] = 0;
blocks[4] = 0;
blocks[5] = 0;
blocks[6] = 0;
blocks[7] = 0;
blocks[8] = 0;
blocks[9] = 0;
blocks[10] = 0;
blocks[11] = 0;
blocks[12] = 0;
blocks[13] = 0;
blocks[14] = 0;
blocks[15] = 0;
blocks[16] = 0;
}
for (i = this._start; index < length && i < 64; ++index) {
blocks[i >> 2] |= message[index] << Sha256.SHIFT[i++ & 3];
}
this._lastByteIndex = i;
this._bytes += i - this._start;
if (i >= 64) {
this._block = blocks[16];
this._start = i - 64;
this.hash();
this._hashed = true;
} else {
this._start = i;
}
}
if (this._bytes > 4294967295) {
this._hBytes += Math.trunc(this._bytes / 4294967296);
this._bytes %= 4294967296;
}
return this;
}
/**
* Get the digest.
* @returns The digest.
*/
public digest() {
this.finalize();
const h0 = this._h0;
const h1 = this._h1;
const h2 = this._h2;
const h3 = this._h3;
const h4 = this._h4;
const h5 = this._h5;
const h6 = this._h6;
const h7 = this._h7;
const arr = [
(h0 >> 24) & 0xff,
(h0 >> 16) & 0xff,
(h0 >> 8) & 0xff,
h0 & 0xff,
(h1 >> 24) & 0xff,
(h1 >> 16) & 0xff,
(h1 >> 8) & 0xff,
h1 & 0xff,
(h2 >> 24) & 0xff,
(h2 >> 16) & 0xff,
(h2 >> 8) & 0xff,
h2 & 0xff,
(h3 >> 24) & 0xff,
(h3 >> 16) & 0xff,
(h3 >> 8) & 0xff,
h3 & 0xff,
(h4 >> 24) & 0xff,
(h4 >> 16) & 0xff,
(h4 >> 8) & 0xff,
h4 & 0xff,
(h5 >> 24) & 0xff,
(h5 >> 16) & 0xff,
(h5 >> 8) & 0xff,
h5 & 0xff,
(h6 >> 24) & 0xff,
(h6 >> 16) & 0xff,
(h6 >> 8) & 0xff,
h6 & 0xff
];
if (this._bits === Sha256.SIZE_256) {
arr.push((h7 >> 24) & 0xff, (h7 >> 16) & 0xff, (h7 >> 8) & 0xff, h7 & 0xff);
}
return Uint8Array.from(arr);
}
/**
* Finalize the hash.
* @internal
*/
private finalize() {
if (this._finalized) {
return;
}
this._finalized = true;
const blocks = this._blocks;
const i = this._lastByteIndex;
blocks[16] = this._block;
blocks[i >> 2] |= Sha256.EXTRA[i & 3];
this._block = blocks[16];
if (i >= 56) {
if (!this._hashed) {
this.hash();
}
blocks[0] = this._block;
blocks[1] = 0;
blocks[2] = 0;
blocks[3] = 0;
blocks[4] = 0;
blocks[5] = 0;
blocks[6] = 0;
blocks[7] = 0;
blocks[8] = 0;
blocks[9] = 0;
blocks[10] = 0;
blocks[11] = 0;
blocks[12] = 0;
blocks[13] = 0;
blocks[14] = 0;
blocks[15] = 0;
blocks[16] = 0;
}
blocks[14] = (this._hBytes << 3) | (this._bytes >>> 29);
blocks[15] = this._bytes << 3;
this.hash();
}
/**
* Perform the hash.
* @internal
*/
private hash() {
let a = this._h0;
let b = this._h1;
let c = this._h2;
let d = this._h3;
let e = this._h4;
let f = this._h5;
let g = this._h6;
let h = this._h7;
const blocks = this._blocks;
let j;
let s0;
let s1;
let maj;
let t1;
let t2;
let ch;
let ab;
let da;
let cd;
let bc;
for (j = 16; j < 64; ++j) {
// rightrotate
t1 = blocks[j - 15];
s0 = ((t1 >>> 7) | (t1 << 25)) ^ ((t1 >>> 18) | (t1 << 14)) ^ (t1 >>> 3);
t1 = blocks[j - 2];
s1 = ((t1 >>> 17) | (t1 << 15)) ^ ((t1 >>> 19) | (t1 << 13)) ^ (t1 >>> 10);
blocks[j] = (blocks[j - 16] + s0 + blocks[j - 7] + s1) << 0;
}
bc = b & c;
for (j = 0; j < 64; j += 4) {
if (this._first) {
if (this._bits === Sha256.SIZE_224) {
ab = 300032;
t1 = blocks[0] - 1413257819;
h = (t1 - 150054599) << 0;
d = (t1 + 24177077) << 0;
} else {
ab = 704751109;
t1 = blocks[0] - 210244248;
h = (t1 - 1521486534) << 0;
d = (t1 + 143694565) << 0;
}
this._first = false;
} else {
s0 = ((a >>> 2) | (a << 30)) ^ ((a >>> 13) | (a << 19)) ^ ((a >>> 22) | (a << 10));
s1 = ((e >>> 6) | (e << 26)) ^ ((e >>> 11) | (e << 21)) ^ ((e >>> 25) | (e << 7));
ab = a & b;
maj = ab ^ (a & c) ^ bc;
ch = (e & f) ^ (~e & g);
t1 = h + s1 + ch + Sha256.K[j] + blocks[j];
t2 = s0 + maj;
h = (d + t1) << 0;
d = (t1 + t2) << 0;
}
s0 = ((d >>> 2) | (d << 30)) ^ ((d >>> 13) | (d << 19)) ^ ((d >>> 22) | (d << 10));
s1 = ((h >>> 6) | (h << 26)) ^ ((h >>> 11) | (h << 21)) ^ ((h >>> 25) | (h << 7));
da = d & a;
maj = da ^ (d & b) ^ ab;
ch = (h & e) ^ (~h & f);
t1 = g + s1 + ch + Sha256.K[j + 1] + blocks[j + 1];
t2 = s0 + maj;
g = (c + t1) << 0;
c = (t1 + t2) << 0;
s0 = ((c >>> 2) | (c << 30)) ^ ((c >>> 13) | (c << 19)) ^ ((c >>> 22) | (c << 10));
s1 = ((g >>> 6) | (g << 26)) ^ ((g >>> 11) | (g << 21)) ^ ((g >>> 25) | (g << 7));
cd = c & d;
maj = cd ^ (c & a) ^ da;
ch = (g & h) ^ (~g & e);
t1 = f + s1 + ch + Sha256.K[j + 2] + blocks[j + 2];
t2 = s0 + maj;
f = (b + t1) << 0;
b = (t1 + t2) << 0;
s0 = ((b >>> 2) | (b << 30)) ^ ((b >>> 13) | (b << 19)) ^ ((b >>> 22) | (b << 10));
s1 = ((f >>> 6) | (f << 26)) ^ ((f >>> 11) | (f << 21)) ^ ((f >>> 25) | (f << 7));
bc = b & c;
maj = bc ^ (b & d) ^ cd;
ch = (f & g) ^ (~f & h);
t1 = e + s1 + ch + Sha256.K[j + 3] + blocks[j + 3];
t2 = s0 + maj;
e = (a + t1) << 0;
a = (t1 + t2) << 0;
}
this._h0 += Math.trunc(a);
this._h1 += Math.trunc(b);
this._h2 += Math.trunc(c);
this._h3 += Math.trunc(d);
this._h4 += Math.trunc(e);
this._h5 += Math.trunc(f);
this._h6 += Math.trunc(g);
this._h7 += Math.trunc(h);
}
}
|
c298ed154379748f886b5730212f7fd071c0652c | 3,840 | ts | TypeScript | src/utils/abi.ts | DeFiFoFum/etherscan-sdk | c221349f73d6bb0dcd6d9d215b568a949889900e | [
"MIT"
] | null | null | null | src/utils/abi.ts | DeFiFoFum/etherscan-sdk | c221349f73d6bb0dcd6d9d215b568a949889900e | [
"MIT"
] | null | null | null | src/utils/abi.ts | DeFiFoFum/etherscan-sdk | c221349f73d6bb0dcd6d9d215b568a949889900e | [
"MIT"
] | 1 | 2021-12-31T05:13:15.000Z | 2021-12-31T05:13:15.000Z | // https://docs.soliditylang.org/en/v0.8.9/abi-spec.html
type VariableType =
'uint' |
'uint256' |
'uint128' |
'uint64' |
'uint32' |
'uint16' |
'uint8' |
'int' |
'int256' |
'int128' |
'int64' |
'int32' |
'int16' |
'int8' |
'address' |
'bool' |
'function' |
'bytes' |
'bytes32' |
'bytes16' |
'bytes8' |
'bytes7' |
'bytes6' |
'bytes5' |
'bytes4' |
'bytes3' |
'bytes2' |
'bytes1'
interface VariableDeclaration {
internalType: VariableType | string;
name: string;
type: VariableType;
}
interface EventVariableDeclaration extends VariableDeclaration {
indexed: boolean;
}
export interface ReceiveABIDeclaration {
stateMutability: 'payable';
type: 'receive'
}
export interface ConstructorABIDeclaration {
stateMutability: 'payable';
inputs: VariableDeclaration[];
type: 'constructor';
}
export interface FallbackABIDeclaration extends Omit<ConstructorABIDeclaration, 'stateMutability' |'type'> {
stateMutability: 'nonpayable' | 'payable' | 'pure' | 'view';
type: 'fallback';
}
export interface FunctionABIDeclaration extends Omit<ConstructorABIDeclaration, 'type'> {
name: string;
outputs: VariableDeclaration[];
type: 'function';
}
export interface EventABIDeclaration {
inputs: EventVariableDeclaration[];
name: string;
type: 'event';
anonymous: boolean;
}
export type ContractABI = Array<ConstructorABIDeclaration | FallbackABIDeclaration | ReceiveABIDeclaration | FunctionABIDeclaration | EventABIDeclaration>;
export interface ParsedABI {
ABI: ContractABI;
constructor: ConstructorABIDeclaration | undefined;
fallback: FallbackABIDeclaration | undefined;
receive: ReceiveABIDeclaration | undefined;
functionList: string[];
functions: FunctionABIDeclaration[];
getFunctionByName: (name: string) => FunctionABIDeclaration;
eventList: string[];
events: EventABIDeclaration[];
getEventByName: (name: string) => EventABIDeclaration;
canReceive: boolean;
}
/**
* Loop through the ABI and separate out the functions and events
*
* @param abi
* @returns ParsedABI
*/
export function parseABI(abi: ContractABI | string): ParsedABI {
let parsedABI = abi as ContractABI;
if(typeof abi == 'string') {
parsedABI = JSON.parse(abi) as ContractABI;
}
const functions = [] as FunctionABIDeclaration[];
const events = [] as EventABIDeclaration[];
let constructor;
let fallback;
let receive;
let canReceive = false;
for (const entity of parsedABI) {
if(entity.type == 'function') {
functions.push(entity);
if(entity.stateMutability === 'payable') {
canReceive = true;
}
} else if(entity.type == 'event') {
events.push(entity);
} else if(entity.type == 'constructor') {
constructor = entity;
} else if(entity.type == 'fallback') {
fallback = entity;
if(entity.stateMutability === 'payable') {
canReceive = true;
}
} else if(entity.type == 'receive') {
receive = entity;
canReceive = true;
}
}
const functionList = functions.map(functionObject => functionObject.name);
const eventList = events.map(eventObject => eventObject.name);
return {
ABI: parsedABI,
constructor,
fallback,
receive,
functionList,
functions,
getFunctionByName: (name: string) => functions.find(functionObject => functionObject.name === name),
eventList,
events,
getEventByName: (name: string) => events.find(eventObject => eventObject.name === name),
canReceive,
}
} | 26.666667 | 155 | 0.623958 | 122 | 7 | 0 | 7 | 9 | 29 | 0 | 0 | 14 | 10 | 5 | 7.285714 | 981 | 0.014271 | 0.009174 | 0.029562 | 0.010194 | 0.005097 | 0 | 0.269231 | 0.248735 | // https://docs.soliditylang.org/en/v0.8.9/abi-spec.html
type VariableType =
'uint' |
'uint256' |
'uint128' |
'uint64' |
'uint32' |
'uint16' |
'uint8' |
'int' |
'int256' |
'int128' |
'int64' |
'int32' |
'int16' |
'int8' |
'address' |
'bool' |
'function' |
'bytes' |
'bytes32' |
'bytes16' |
'bytes8' |
'bytes7' |
'bytes6' |
'bytes5' |
'bytes4' |
'bytes3' |
'bytes2' |
'bytes1'
interface VariableDeclaration {
internalType;
name;
type;
}
interface EventVariableDeclaration extends VariableDeclaration {
indexed;
}
export interface ReceiveABIDeclaration {
stateMutability;
type
}
export interface ConstructorABIDeclaration {
stateMutability;
inputs;
type;
}
export interface FallbackABIDeclaration extends Omit<ConstructorABIDeclaration, 'stateMutability' |'type'> {
stateMutability;
type;
}
export interface FunctionABIDeclaration extends Omit<ConstructorABIDeclaration, 'type'> {
name;
outputs;
type;
}
export interface EventABIDeclaration {
inputs;
name;
type;
anonymous;
}
export type ContractABI = Array<ConstructorABIDeclaration | FallbackABIDeclaration | ReceiveABIDeclaration | FunctionABIDeclaration | EventABIDeclaration>;
export interface ParsedABI {
ABI;
constructor;
fallback;
receive;
functionList;
functions;
getFunctionByName;
eventList;
events;
getEventByName;
canReceive;
}
/**
* Loop through the ABI and separate out the functions and events
*
* @param abi
* @returns ParsedABI
*/
export function parseABI(abi) {
let parsedABI = abi as ContractABI;
if(typeof abi == 'string') {
parsedABI = JSON.parse(abi) as ContractABI;
}
const functions = [] as FunctionABIDeclaration[];
const events = [] as EventABIDeclaration[];
let constructor;
let fallback;
let receive;
let canReceive = false;
for (const entity of parsedABI) {
if(entity.type == 'function') {
functions.push(entity);
if(entity.stateMutability === 'payable') {
canReceive = true;
}
} else if(entity.type == 'event') {
events.push(entity);
} else if(entity.type == 'constructor') {
constructor = entity;
} else if(entity.type == 'fallback') {
fallback = entity;
if(entity.stateMutability === 'payable') {
canReceive = true;
}
} else if(entity.type == 'receive') {
receive = entity;
canReceive = true;
}
}
const functionList = functions.map(functionObject => functionObject.name);
const eventList = events.map(eventObject => eventObject.name);
return {
ABI: parsedABI,
constructor,
fallback,
receive,
functionList,
functions,
getFunctionByName: (name) => functions.find(functionObject => functionObject.name === name),
eventList,
events,
getEventByName: (name) => events.find(eventObject => eventObject.name === name),
canReceive,
}
} |
c2b01e876c720ebdffc149d4e5bc60c3692580e5 | 8,424 | ts | TypeScript | lib/meco.ts | arjan-kuiper/nxs-three | 0b7940ce08218a47e6b54dc5878127de1fbafdb8 | [
"MIT"
] | 1 | 2022-03-12T20:29:42.000Z | 2022-03-12T20:29:42.000Z | lib/meco.ts | arjan-kuiper/nxs-three | 0b7940ce08218a47e6b54dc5878127de1fbafdb8 | [
"MIT"
] | null | null | null | lib/meco.ts | arjan-kuiper/nxs-three | 0b7940ce08218a47e6b54dc5878127de1fbafdb8 | [
"MIT"
] | null | null | null | export class ZPoint {
private lo: number;
private hi: number;
constructor(h: number, l: number) {
this.lo = l;
this.hi = h;
}
public copy(z: ZPoint): void {
this.lo = z.lo;
this.hi = z.hi;
}
public setBit(d: number): void {
if (d < 32) {
this.lo = (this.lo | (1 << d)) >>> 0;
} else {
this.hi = (this.hi | (1 << (d - 32))) >>> 0;
}
}
public toPoint(min: any, step: any, buffer: any, pos: any): void {
let x = this.morton3(this.lo, this.hi >>> 1);
let y = this.morton3(this.lo >>> 1, this.hi >>> 2);
let z = this.morton3((this.lo >>> 2 | (this.hi & 0x1) << 30) >>> 0, this.hi >>> 3);
buffer[pos + 0] = (x + min[0]) * step;
buffer[pos + 1] = (y + min[1]) * step;
buffer[pos + 2] = (z + min[2]) * step;
}
public morton3(lo: number, hi: number): number {
lo = (lo & 0x49249249) >>> 0;
lo = ((lo | (lo >>> 2 )) & 0xc30c30c3) >>> 0;
lo = ((lo | (lo >>> 4 )) & 0x0f00f00f) >>> 0;
lo = ((lo | (lo >>> 8 )) & 0xff0000ff) >>> 0;
lo = ((lo | (lo >>> 16)) & 0x0000ffff) >>> 0;
hi = ( hi & 0x49249249) >>> 0;
hi = ((hi | (hi >> 2 )) & 0xc30c30c3) >>> 0;
hi = ((hi | (hi >> 4 )) & 0x0f00f00f) >>> 0;
hi = ((hi | (hi >> 8 )) & 0xff0000ff) >>> 0;
hi = ((hi | (hi >> 16)) & 0x0000ffff) >>> 0;
return ((hi << 11) | lo) >>> 0;
}
}
export class Tunstall {
private wordSize: number;
private lookupSize: number;
private probabilities: Uint8Array;
private index: Uint32Array;
private lenghts: Uint32Array;
private tables: Uint8Array
constructor(wordSize?: number, lookupSize?: number) {
this.wordSize = wordSize ? wordSize : 8;
this.lookupSize = lookupSize ? lookupSize : 8;
this.probabilities = new Uint8Array(0);
this.index = new Uint32Array(0);
this.lenghts = new Uint32Array(0);
this.tables = new Uint8Array(0);
}
public decompress(stream: Stream): Uint8Array {
let nSymbols = stream.readUChar();
this.probabilities = stream.readArray(nSymbols * 2);
this.createDecodingTables();
let size = stream.readInt();
let data = new Uint8Array(size);
let compressedSize = stream.readInt();
let compressedData = stream.readArray(compressedSize);
if (size) {
this._decompress(compressedData, compressedSize, data, size);
}
return data;
}
public _decompress(input: Uint8Array, inputSize: number, output: Uint8Array, outputSize: number) {
let inputPos = 0;
let outputPos = 0;
if (this.probabilities.length == 2) {
let symbol = this.probabilities[0];
for (let i = 0; i < outputSize; i++) {
output[i] = symbol;
}
return;
}
while (inputPos < inputSize - 1) {
let symbol = input[inputPos++];
let start = this.index[symbol];
let end = start + this.lenghts[symbol];
for (let i = start; i < end; i++) {
output[outputPos++] = this.tables[i];
}
}
let symbol = input[inputPos];
let start = this.index[symbol];
let end = start + outputSize - outputPos;
let length = outputSize - outputPos;
for (let i = start; i < end; i++) {
output[outputPos++] = this.tables[i];
}
return output;
}
public createDecodingTables(): void {
let nSymbols = this.probabilities?.length / 2;
if (nSymbols <= 1) return;
let queues = [];
let buffer = [];
for (let i = 0; i < nSymbols; i++) {
let symbol = this.probabilities[i * 2];
let s = [(this.probabilities[i * 2 + 1]) << 8, buffer.length, 1];
queues[i] = [s];
buffer.push(symbol);
}
let dictionarySize = 1 << this.wordSize;
let nWords = nSymbols;
let tableLength = nSymbols;
while (nWords < dictionarySize - nSymbols + 1) {
let best = 0;
let maxProb = 0;
for (let i = 0; i < nSymbols; i++) {
let p = queues[i][0][0];
if (p > maxProb) {
best = i;
maxProb = p;
}
}
let symbol = queues[best][0];
let pos: number = buffer.length;
for (let i = 0; i < nSymbols; i++) {
let sym = this.probabilities[i * 2];
let prob = this.probabilities[i * 2 + 1] << 8;
let s = [((prob * symbol[0]) >>> 16), pos, symbol[2] + 1];
for (let k = 0; k < symbol[2]; k++) {
buffer[pos + k] = buffer[symbol[1] + k];
}
pos += symbol[2];
buffer[pos++] = sym;
queues[i].push(s);
}
tableLength += (nSymbols - 1) * (symbol[2] + 1) + 1;
nWords += nSymbols - 1;
queues[best].shift();
}
this.index = new Uint32Array(nWords);
this.lenghts = new Uint32Array(nWords);
this.tables = new Uint8Array(tableLength);
let word = 0;
let pos = 0;
for (let i = 0; i < queues.length; i++) {
let queue = queues[i];
for (let k = 0; k < queue.length; k++) {
let s = queue[k];
this.index[word] = pos;
this.lenghts[word] = s[2];
word++;
for (let j = 0; j < s[2]; j++) {
this.tables[pos + j] = buffer[s[1] + j];
}
pos += s[2];
}
}
}
}
export class Stream {
private data: any;
private buffer: Uint8Array;
private pos: number;
constructor(buffer: any) {
this.data = buffer;
this.buffer = new Uint8Array(buffer);
this.pos = 0;
}
public readChar(): number {
var c = this.buffer[this.pos++];
if (c > 127) {
c -= 256
}
return c;
}
public readUChar(): number {
return this.buffer[this.pos++];
}
public readInt(): number {
var c = this.buffer[this.pos + 3]
c <<= 8;
c |= this.buffer[this.pos + 2];
c <<= 8;
c |= this.buffer[this.pos + 1];
c <<= 8;
c |= this.buffer[this.pos + 0];
this.pos += 4;
return c;
}
public readArray(n: number): Uint8Array {
var a = this.buffer.subarray(this.pos, this.pos + n);
this.pos += n;
return a;
}
public readBitStream(): BitStream {
var n = this.readInt();
var pad = this.pos & 0x3;
if (pad != 0) {
this.pos += 4 - pad;
}
var b = new BitStream(new Uint32Array(this.data, this.pos, n * 2));
this.pos += n*8;
return b;
}
}
export class BitStream {
private array: Uint32Array;
private position: number;
private bitsPending: number;
constructor(array: Uint32Array) {
this.array = array;
for (let i = 0; i < array.length; i += 2) {
const s = array[i];
array[i] = array[i + 1];
array[i + 1] = s;
}
this.position = 0;
this.bitsPending = 0;
}
public read(bits: number): number {
let bitBuffer = 0;
while (bits > 0) {
let partial;
let bitsConsumed;
if (this.bitsPending > 0) {
let byte = (this.array[this.position - 1] & (0xffffffff >>> (32 - this.bitsPending))) >>> 0;
bitsConsumed = Math.min(this.bitsPending, bits);
this.bitsPending -= bitsConsumed;
partial = byte >>> this.bitsPending;
} else {
bitsConsumed = Math.min(32, bits);
this.bitsPending = 32 - bitsConsumed;
partial = this.array[this.position++] >>> this.bitsPending;
}
bits -= bitsConsumed;
bitBuffer = ((bitBuffer << bitsConsumed) | partial) >>> 0;
}
return bitBuffer;
}
public replace(bits: number, value: number): number {
value = (value & (0xffffffff >>> 32 - bits)) >>> 0;
value = (value | this.read(bits)) >>> 0;
return value;
}
} | 30.302158 | 108 | 0.477208 | 242 | 18 | 0 | 23 | 60 | 14 | 7 | 6 | 31 | 4 | 0 | 10.222222 | 2,540 | 0.016142 | 0.023622 | 0.005512 | 0.001575 | 0 | 0.052174 | 0.269565 | 0.288161 | export class ZPoint {
private lo;
private hi;
constructor(h, l) {
this.lo = l;
this.hi = h;
}
public copy(z) {
this.lo = z.lo;
this.hi = z.hi;
}
public setBit(d) {
if (d < 32) {
this.lo = (this.lo | (1 << d)) >>> 0;
} else {
this.hi = (this.hi | (1 << (d - 32))) >>> 0;
}
}
public toPoint(min, step, buffer, pos) {
let x = this.morton3(this.lo, this.hi >>> 1);
let y = this.morton3(this.lo >>> 1, this.hi >>> 2);
let z = this.morton3((this.lo >>> 2 | (this.hi & 0x1) << 30) >>> 0, this.hi >>> 3);
buffer[pos + 0] = (x + min[0]) * step;
buffer[pos + 1] = (y + min[1]) * step;
buffer[pos + 2] = (z + min[2]) * step;
}
public morton3(lo, hi) {
lo = (lo & 0x49249249) >>> 0;
lo = ((lo | (lo >>> 2 )) & 0xc30c30c3) >>> 0;
lo = ((lo | (lo >>> 4 )) & 0x0f00f00f) >>> 0;
lo = ((lo | (lo >>> 8 )) & 0xff0000ff) >>> 0;
lo = ((lo | (lo >>> 16)) & 0x0000ffff) >>> 0;
hi = ( hi & 0x49249249) >>> 0;
hi = ((hi | (hi >> 2 )) & 0xc30c30c3) >>> 0;
hi = ((hi | (hi >> 4 )) & 0x0f00f00f) >>> 0;
hi = ((hi | (hi >> 8 )) & 0xff0000ff) >>> 0;
hi = ((hi | (hi >> 16)) & 0x0000ffff) >>> 0;
return ((hi << 11) | lo) >>> 0;
}
}
export class Tunstall {
private wordSize;
private lookupSize;
private probabilities;
private index;
private lenghts;
private tables
constructor(wordSize?, lookupSize?) {
this.wordSize = wordSize ? wordSize : 8;
this.lookupSize = lookupSize ? lookupSize : 8;
this.probabilities = new Uint8Array(0);
this.index = new Uint32Array(0);
this.lenghts = new Uint32Array(0);
this.tables = new Uint8Array(0);
}
public decompress(stream) {
let nSymbols = stream.readUChar();
this.probabilities = stream.readArray(nSymbols * 2);
this.createDecodingTables();
let size = stream.readInt();
let data = new Uint8Array(size);
let compressedSize = stream.readInt();
let compressedData = stream.readArray(compressedSize);
if (size) {
this._decompress(compressedData, compressedSize, data, size);
}
return data;
}
public _decompress(input, inputSize, output, outputSize) {
let inputPos = 0;
let outputPos = 0;
if (this.probabilities.length == 2) {
let symbol = this.probabilities[0];
for (let i = 0; i < outputSize; i++) {
output[i] = symbol;
}
return;
}
while (inputPos < inputSize - 1) {
let symbol = input[inputPos++];
let start = this.index[symbol];
let end = start + this.lenghts[symbol];
for (let i = start; i < end; i++) {
output[outputPos++] = this.tables[i];
}
}
let symbol = input[inputPos];
let start = this.index[symbol];
let end = start + outputSize - outputPos;
let length = outputSize - outputPos;
for (let i = start; i < end; i++) {
output[outputPos++] = this.tables[i];
}
return output;
}
public createDecodingTables() {
let nSymbols = this.probabilities?.length / 2;
if (nSymbols <= 1) return;
let queues = [];
let buffer = [];
for (let i = 0; i < nSymbols; i++) {
let symbol = this.probabilities[i * 2];
let s = [(this.probabilities[i * 2 + 1]) << 8, buffer.length, 1];
queues[i] = [s];
buffer.push(symbol);
}
let dictionarySize = 1 << this.wordSize;
let nWords = nSymbols;
let tableLength = nSymbols;
while (nWords < dictionarySize - nSymbols + 1) {
let best = 0;
let maxProb = 0;
for (let i = 0; i < nSymbols; i++) {
let p = queues[i][0][0];
if (p > maxProb) {
best = i;
maxProb = p;
}
}
let symbol = queues[best][0];
let pos = buffer.length;
for (let i = 0; i < nSymbols; i++) {
let sym = this.probabilities[i * 2];
let prob = this.probabilities[i * 2 + 1] << 8;
let s = [((prob * symbol[0]) >>> 16), pos, symbol[2] + 1];
for (let k = 0; k < symbol[2]; k++) {
buffer[pos + k] = buffer[symbol[1] + k];
}
pos += symbol[2];
buffer[pos++] = sym;
queues[i].push(s);
}
tableLength += (nSymbols - 1) * (symbol[2] + 1) + 1;
nWords += nSymbols - 1;
queues[best].shift();
}
this.index = new Uint32Array(nWords);
this.lenghts = new Uint32Array(nWords);
this.tables = new Uint8Array(tableLength);
let word = 0;
let pos = 0;
for (let i = 0; i < queues.length; i++) {
let queue = queues[i];
for (let k = 0; k < queue.length; k++) {
let s = queue[k];
this.index[word] = pos;
this.lenghts[word] = s[2];
word++;
for (let j = 0; j < s[2]; j++) {
this.tables[pos + j] = buffer[s[1] + j];
}
pos += s[2];
}
}
}
}
export class Stream {
private data;
private buffer;
private pos;
constructor(buffer) {
this.data = buffer;
this.buffer = new Uint8Array(buffer);
this.pos = 0;
}
public readChar() {
var c = this.buffer[this.pos++];
if (c > 127) {
c -= 256
}
return c;
}
public readUChar() {
return this.buffer[this.pos++];
}
public readInt() {
var c = this.buffer[this.pos + 3]
c <<= 8;
c |= this.buffer[this.pos + 2];
c <<= 8;
c |= this.buffer[this.pos + 1];
c <<= 8;
c |= this.buffer[this.pos + 0];
this.pos += 4;
return c;
}
public readArray(n) {
var a = this.buffer.subarray(this.pos, this.pos + n);
this.pos += n;
return a;
}
public readBitStream() {
var n = this.readInt();
var pad = this.pos & 0x3;
if (pad != 0) {
this.pos += 4 - pad;
}
var b = new BitStream(new Uint32Array(this.data, this.pos, n * 2));
this.pos += n*8;
return b;
}
}
export class BitStream {
private array;
private position;
private bitsPending;
constructor(array) {
this.array = array;
for (let i = 0; i < array.length; i += 2) {
const s = array[i];
array[i] = array[i + 1];
array[i + 1] = s;
}
this.position = 0;
this.bitsPending = 0;
}
public read(bits) {
let bitBuffer = 0;
while (bits > 0) {
let partial;
let bitsConsumed;
if (this.bitsPending > 0) {
let byte = (this.array[this.position - 1] & (0xffffffff >>> (32 - this.bitsPending))) >>> 0;
bitsConsumed = Math.min(this.bitsPending, bits);
this.bitsPending -= bitsConsumed;
partial = byte >>> this.bitsPending;
} else {
bitsConsumed = Math.min(32, bits);
this.bitsPending = 32 - bitsConsumed;
partial = this.array[this.position++] >>> this.bitsPending;
}
bits -= bitsConsumed;
bitBuffer = ((bitBuffer << bitsConsumed) | partial) >>> 0;
}
return bitBuffer;
}
public replace(bits, value) {
value = (value & (0xffffffff >>> 32 - bits)) >>> 0;
value = (value | this.read(bits)) >>> 0;
return value;
}
} |
c2b14b81b62c01560c1b8c7c6479278316c265b6 | 2,426 | ts | TypeScript | solutions/day11.ts | GiyoMoon/aoc2021 | 83d7e9018ed3b628353bc9a0a37b70a1462ecd74 | [
"Unlicense"
] | null | null | null | solutions/day11.ts | GiyoMoon/aoc2021 | 83d7e9018ed3b628353bc9a0a37b70a1462ecd74 | [
"Unlicense"
] | 1 | 2022-02-03T11:04:17.000Z | 2022-02-03T11:04:17.000Z | solutions/day11.ts | GiyoMoon/aoc2021 | 83d7e9018ed3b628353bc9a0a37b70a1462ecd74 | [
"Unlicense"
] | null | null | null | export default class Day11 {
private _octos: number[][];
private _flashCount = 0;
private _alreadyFlashed: number[][] = [];
public solve(input: string): { part1: any, part2: any; } {
this._octos = input.split('\n').map(line => line.split('').map(o => parseInt(o)));
for (let step = 0; step < 100; step++) {
this._runStep();
}
this._octos = input.split('\n').map(line => line.split('').map(o => parseInt(o)));
let allFlashed = false;
let stepWhereAllFlashed: number;
for (let step = 1; !allFlashed; step++) {
this._runStep();
let notFlashed = false;
this._octos.forEach((l) => {
l.forEach((o) => {
if (o !== 0) {
notFlashed = true;
}
});
});
if (!notFlashed) {
allFlashed = true;
stepWhereAllFlashed = step;
}
}
return { part1: this._flashCount, part2: stepWhereAllFlashed };
}
private _runStep() {
this._octos = this._octos.map(line => line.map(o => o + 1));
this._checkFlashes();
this._resetFlashedOctos();
}
private _checkFlashes() {
let hadFlashes = false;
this._octos.forEach((l, li) => {
l.forEach((o, oi) => {
if (o > 9) {
if (this._alreadyFlashed.some((coords: number[]) => coords[0] === li && coords[1] === oi)) {
return;
}
this._alreadyFlashed.push([li, oi]);
this._flashCount += 1;
// left, right, top left, top, top right, bot left, bot, bot right
const y = [li, li, li - 1, li - 1, li - 1, li + 1, li + 1, li + 1];
const x = [oi - 1, oi + 1, oi - 1, oi, oi + 1, oi - 1, oi, oi + 1];
for (let n = 0; n < y.length; n++) {
if (
this._octos[y[n]] &&
this._octos[y[n]][x[n]] <= 9 &&
!this._alreadyFlashed.some((coords: number[]) => coords[0] === y[n] && coords[1] === x[n])
) {
this._octos[y[n]][x[n]] += 1;
if (this._octos[y[n]][x[n]] > 9) {
hadFlashes = true;
}
}
}
}
});
});
if (hadFlashes) {
this._checkFlashes();
}
}
private _resetFlashedOctos() {
this._octos.forEach((l, li) => {
l.forEach((o, oi) => {
if (o > 9) {
this._octos[li][oi] = 0;
}
});
});
this._alreadyFlashed = [];
}
}
| 26.659341 | 104 | 0.471146 | 76 | 18 | 0 | 19 | 9 | 3 | 3 | 2 | 6 | 1 | 0 | 7.277778 | 792 | 0.046717 | 0.011364 | 0.003788 | 0.001263 | 0 | 0.040816 | 0.122449 | 0.318504 | export default class Day11 {
private _octos;
private _flashCount = 0;
private _alreadyFlashed = [];
public solve(input) {
this._octos = input.split('\n').map(line => line.split('').map(o => parseInt(o)));
for (let step = 0; step < 100; step++) {
this._runStep();
}
this._octos = input.split('\n').map(line => line.split('').map(o => parseInt(o)));
let allFlashed = false;
let stepWhereAllFlashed;
for (let step = 1; !allFlashed; step++) {
this._runStep();
let notFlashed = false;
this._octos.forEach((l) => {
l.forEach((o) => {
if (o !== 0) {
notFlashed = true;
}
});
});
if (!notFlashed) {
allFlashed = true;
stepWhereAllFlashed = step;
}
}
return { part1: this._flashCount, part2: stepWhereAllFlashed };
}
private _runStep() {
this._octos = this._octos.map(line => line.map(o => o + 1));
this._checkFlashes();
this._resetFlashedOctos();
}
private _checkFlashes() {
let hadFlashes = false;
this._octos.forEach((l, li) => {
l.forEach((o, oi) => {
if (o > 9) {
if (this._alreadyFlashed.some((coords) => coords[0] === li && coords[1] === oi)) {
return;
}
this._alreadyFlashed.push([li, oi]);
this._flashCount += 1;
// left, right, top left, top, top right, bot left, bot, bot right
const y = [li, li, li - 1, li - 1, li - 1, li + 1, li + 1, li + 1];
const x = [oi - 1, oi + 1, oi - 1, oi, oi + 1, oi - 1, oi, oi + 1];
for (let n = 0; n < y.length; n++) {
if (
this._octos[y[n]] &&
this._octos[y[n]][x[n]] <= 9 &&
!this._alreadyFlashed.some((coords) => coords[0] === y[n] && coords[1] === x[n])
) {
this._octos[y[n]][x[n]] += 1;
if (this._octos[y[n]][x[n]] > 9) {
hadFlashes = true;
}
}
}
}
});
});
if (hadFlashes) {
this._checkFlashes();
}
}
private _resetFlashedOctos() {
this._octos.forEach((l, li) => {
l.forEach((o, oi) => {
if (o > 9) {
this._octos[li][oi] = 0;
}
});
});
this._alreadyFlashed = [];
}
}
|
c2dc8f4b06b04cbfe8c66ae83924e18992baa024 | 1,028 | ts | TypeScript | FLG-Client/src/app/boards/board.ts | TomPrice0/FLG-Client | 1b4d95c1bb2a136b9aa5615ecbd4dd073bbbfa8d | [
"MIT"
] | null | null | null | FLG-Client/src/app/boards/board.ts | TomPrice0/FLG-Client | 1b4d95c1bb2a136b9aa5615ecbd4dd073bbbfa8d | [
"MIT"
] | 1 | 2022-03-02T07:47:51.000Z | 2022-03-02T07:47:51.000Z | FLG-Client/src/app/boards/board.ts | TomPrice0/FLG-Client | 1b4d95c1bb2a136b9aa5615ecbd4dd073bbbfa8d | [
"MIT"
] | null | null | null | /* Defines the board entity */
export interface Board {
address1: string;
address2: string;
city: string;
contact: string;
coordId: string;
email: string;
fax: string;
id: number;
multipleLocation: boolean;
department: string;
division: string;
board: string;
officeHours: string;
st: string;
teleExt: string;
telephone: string;
url: string;
zip: string;
zipExt: string;
haslicenses: boolean;
}
export interface BoardResolved {
authority: Board;
error?: any;
}
export function newBoard(): Board{
const a: Board={
address1: '',
address2: '',
city: '',
contact: '',
coordId: null,
email: '',
fax: '',
id: 0,
multipleLocation: false,
department: '',
division: '',
board: '',
officeHours: '',
st: 'NC',
teleExt: '',
telephone: '',
url: '',
zip: '',
zipExt: '',
haslicenses: false
};
return a;
}
| 18.357143 | 36 | 0.530156 | 51 | 1 | 0 | 0 | 1 | 22 | 0 | 1 | 20 | 2 | 0 | 23 | 260 | 0.003846 | 0.003846 | 0.084615 | 0.007692 | 0 | 0.041667 | 0.833333 | 0.202337 | /* Defines the board entity */
export interface Board {
address1;
address2;
city;
contact;
coordId;
email;
fax;
id;
multipleLocation;
department;
division;
board;
officeHours;
st;
teleExt;
telephone;
url;
zip;
zipExt;
haslicenses;
}
export interface BoardResolved {
authority;
error?;
}
export function newBoard(){
const a={
address1: '',
address2: '',
city: '',
contact: '',
coordId: null,
email: '',
fax: '',
id: 0,
multipleLocation: false,
department: '',
division: '',
board: '',
officeHours: '',
st: 'NC',
teleExt: '',
telephone: '',
url: '',
zip: '',
zipExt: '',
haslicenses: false
};
return a;
}
|
d171afdd095c6a0b2c063d5f106a47799ad110b9 | 1,347 | ts | TypeScript | src/gen/decorators/lazy.ts | jordyfontoura/kitlib | e5aa18f6ddeec7c481697c6e5745498e2fb5da8a | [
"MIT"
] | null | null | null | src/gen/decorators/lazy.ts | jordyfontoura/kitlib | e5aa18f6ddeec7c481697c6e5745498e2fb5da8a | [
"MIT"
] | 1 | 2022-03-11T17:55:03.000Z | 2022-03-11T17:55:03.000Z | src/gen/decorators/lazy.ts | jordyfontoura/kitlib | e5aa18f6ddeec7c481697c6e5745498e2fb5da8a | [
"MIT"
] | null | null | null | export function lazy(
generator: () => any
): (target: any, propertyKey: string, descriptor: PropertyDescriptor) => any;
export function lazy<T=any>(
target: T,
propertyKey: string,
descriptor: PropertyDescriptor
): any;
export function lazy(
target: any | (() => any),
propertyKey?: string,
descriptor?: PropertyDescriptor
) {
if (target instanceof Function && !propertyKey && !descriptor) {
const generator = target;
return function (
target: any,
propertyKey: string,
descriptor: PropertyDescriptor
) {
delete descriptor.get;
Object.defineProperty(target, propertyKey, {
configurable: true,
get() {
const value = generator();
Object.defineProperty(this, propertyKey, {
value,
configurable: true,
});
return value;
},
});
return target;
};
}
if (!descriptor || !propertyKey) {
throw new Error();
}
const generator = descriptor.get ? descriptor.get : () => undefined;
delete descriptor.get;
Object.defineProperty(target, propertyKey, {
configurable: true,
get() {
const value = generator.call(this);
Object.defineProperty(this, propertyKey, {
value,
configurable: true,
});
return value;
},
});
return target;
}
| 24.944444 | 77 | 0.603563 | 53 | 5 | 2 | 10 | 4 | 0 | 0 | 8 | 4 | 0 | 1 | 13 | 305 | 0.04918 | 0.013115 | 0 | 0 | 0.003279 | 0.380952 | 0.190476 | 0.321224 | export function lazy(
generator
);
export function lazy<T=any>(
target,
propertyKey,
descriptor
);
export function lazy(
target,
propertyKey?,
descriptor?
) {
if (target instanceof Function && !propertyKey && !descriptor) {
const generator = target;
return function (
target,
propertyKey,
descriptor
) {
delete descriptor.get;
Object.defineProperty(target, propertyKey, {
configurable: true,
get() {
const value = generator();
Object.defineProperty(this, propertyKey, {
value,
configurable: true,
});
return value;
},
});
return target;
};
}
if (!descriptor || !propertyKey) {
throw new Error();
}
const generator = descriptor.get ? descriptor.get : () => undefined;
delete descriptor.get;
Object.defineProperty(target, propertyKey, {
configurable: true,
get() {
const value = generator.call(this);
Object.defineProperty(this, propertyKey, {
value,
configurable: true,
});
return value;
},
});
return target;
}
|
5015731de39d782d56f8a1e23bb6486643ab39bb | 2,238 | ts | TypeScript | src/assets/data/data.ts | SocialOpenSenseMap/openSenseMapX | aa9bf43eb8c5eb592129acd616e9933eed6801a9 | [
"MIT"
] | null | null | null | src/assets/data/data.ts | SocialOpenSenseMap/openSenseMapX | aa9bf43eb8c5eb592129acd616e9933eed6801a9 | [
"MIT"
] | 1 | 2022-01-22T11:30:38.000Z | 2022-01-22T11:30:38.000Z | src/assets/data/data.ts | SocialOpenSenseMap/openSenseMapX | aa9bf43eb8c5eb592129acd616e9933eed6801a9 | [
"MIT"
] | null | null | null | interface IRowGenerateData {
emailNotification: boolean | null;
boxName: string;
boxSensor: string;
boxExposure: string;
thresholdValue: string | number;
date: Date;
actions: string;
}
export function GetData(rowscount?: number, last?: number, hasNullValues?: boolean): IRowGenerateData[] {
const data: IRowGenerateData[] = new Array();
if (rowscount === undefined) {
rowscount = 100;
}
let startIndex = 0;
if (last) {
startIndex = rowscount;
rowscount = last - rowscount;
}
const boxNames =
[
'PGKN FS02 - Rumphorst', 'BalkonBox Mindener Str.', 'BalkonBox Mindener Str.', 'Hoersterstr. 17', 'SteffenDroste', 'OC-WETTER', 'Fühlerbüchse', 'PGKN FS01 - Schule', 'KiTa Glühwürmchen', 'Westfälisches Pferdemuseum Münster', 'Hawerkamp 31', 'Martin', 'Botanischer Garten', 'Noise Sensor', 'CYBER Box', 'fancyBox3000', 'wullewup', 'Deipen4_A'
];
const boxSensors =
[
'Temperatur', 'rel. Luftfeuchte', 'Luftdruck', 'Beleuchtungsstärke', 'UV-Intensität', 'PM10', 'PM2.5'
];
const exposure =
[
'outdoor', 'indoor'
];
const actions =
[
'more than', 'less than'
];
const thresholdValues =
[
'2.25', '1.5', '3.0', '3.3', '4.5', '3.6', '3.8', '2.5', '5.0', '1.75', '3.25', '4.0'
];
for (let i = 0; i < rowscount; i++) {
const row = {} as IRowGenerateData;
const exposureindex = Math.floor(Math.random() * 2);
const actionindex = Math.floor(Math.random() * actions.length);
const thresholdValue = parseFloat(thresholdValues[exposureindex]);
row.emailNotification = exposureindex % 2 === 0;
if (hasNullValues === true) {
if (exposureindex % 2 !== 0) {
const random = Math.floor(Math.random() * rowscount);
row.emailNotification = i % random === 0 ? null : false;
}
}
row.boxName = boxNames[Math.floor(Math.random() * boxNames.length)];
row.boxSensor = boxSensors[Math.floor(Math.random() * boxSensors.length)];
row.boxExposure = exposure[exposureindex];
row.actions = actions[actionindex];
row.thresholdValue = thresholdValue;
const date = new Date();
date.setFullYear(2016, Math.floor(Math.random() * 11), Math.floor(Math.random() * 27));
date.setHours(0, 0, 0, 0);
row.date = date;
data[i] = row;
}
return data;
} | 26.023256 | 344 | 0.651921 | 64 | 1 | 0 | 3 | 14 | 7 | 0 | 0 | 10 | 1 | 1 | 53 | 850 | 0.004706 | 0.016471 | 0.008235 | 0.001176 | 0.001176 | 0 | 0.4 | 0.236272 | interface IRowGenerateData {
emailNotification;
boxName;
boxSensor;
boxExposure;
thresholdValue;
date;
actions;
}
export function GetData(rowscount?, last?, hasNullValues?) {
const data = new Array();
if (rowscount === undefined) {
rowscount = 100;
}
let startIndex = 0;
if (last) {
startIndex = rowscount;
rowscount = last - rowscount;
}
const boxNames =
[
'PGKN FS02 - Rumphorst', 'BalkonBox Mindener Str.', 'BalkonBox Mindener Str.', 'Hoersterstr. 17', 'SteffenDroste', 'OC-WETTER', 'Fühlerbüchse', 'PGKN FS01 - Schule', 'KiTa Glühwürmchen', 'Westfälisches Pferdemuseum Münster', 'Hawerkamp 31', 'Martin', 'Botanischer Garten', 'Noise Sensor', 'CYBER Box', 'fancyBox3000', 'wullewup', 'Deipen4_A'
];
const boxSensors =
[
'Temperatur', 'rel. Luftfeuchte', 'Luftdruck', 'Beleuchtungsstärke', 'UV-Intensität', 'PM10', 'PM2.5'
];
const exposure =
[
'outdoor', 'indoor'
];
const actions =
[
'more than', 'less than'
];
const thresholdValues =
[
'2.25', '1.5', '3.0', '3.3', '4.5', '3.6', '3.8', '2.5', '5.0', '1.75', '3.25', '4.0'
];
for (let i = 0; i < rowscount; i++) {
const row = {} as IRowGenerateData;
const exposureindex = Math.floor(Math.random() * 2);
const actionindex = Math.floor(Math.random() * actions.length);
const thresholdValue = parseFloat(thresholdValues[exposureindex]);
row.emailNotification = exposureindex % 2 === 0;
if (hasNullValues === true) {
if (exposureindex % 2 !== 0) {
const random = Math.floor(Math.random() * rowscount);
row.emailNotification = i % random === 0 ? null : false;
}
}
row.boxName = boxNames[Math.floor(Math.random() * boxNames.length)];
row.boxSensor = boxSensors[Math.floor(Math.random() * boxSensors.length)];
row.boxExposure = exposure[exposureindex];
row.actions = actions[actionindex];
row.thresholdValue = thresholdValue;
const date = new Date();
date.setFullYear(2016, Math.floor(Math.random() * 11), Math.floor(Math.random() * 27));
date.setHours(0, 0, 0, 0);
row.date = date;
data[i] = row;
}
return data;
} |
50f63d99ef910edb567232e193f56b93eed65631 | 2,277 | ts | TypeScript | src/Util.ts | honungsburk/frankhampusweslien | 84d5e6bac82adf1345be2abdb9e7784602a4cf8d | [
"MIT"
] | null | null | null | src/Util.ts | honungsburk/frankhampusweslien | 84d5e6bac82adf1345be2abdb9e7784602a4cf8d | [
"MIT"
] | null | null | null | src/Util.ts | honungsburk/frankhampusweslien | 84d5e6bac82adf1345be2abdb9e7784602a4cf8d | [
"MIT"
] | 1 | 2022-03-24T09:49:37.000Z | 2022-03-24T09:49:37.000Z | /**
*
* @param start number to start from (inclusive)
* @param end number to end at (inclusive)
* @returns range including start and end
*/
export function range(start: number, end: number) {
if (start > end) {
return [];
}
return Array(end - start + 1)
.fill(0)
.map((_, idx) => start + idx);
}
/**
*
* @param fileName the filename to get the extention from
* @returns either the extention or undefined
*/
export function findFileExtention(fileName: string): string | undefined {
const re = /(?:\.([^.]+))?$/;
const res = re.exec(fileName);
if (res) {
return res[1];
}
return undefined;
}
/**
*
* @param length the length
* @returns a random string of a given length
*/
export function makeID(length: number) {
let result = "";
const characters =
"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
const charactersLength = characters.length;
for (let i = 0; i < length; i++) {
result += characters.charAt(Math.floor(Math.random() * charactersLength));
}
return result;
}
/**
* Removes trailing zeros
*
* @param str the string
* @returns
*/
export function removeTrailingZeros(str: string): string {
return str[str.length - 1] === "0"
? removeTrailingZeros(str.slice(0, -1))
: str;
}
/**
*
* @param str the string to add commas to
* @param n how often to add commas
* @param memory internal emory
* @returns a formated string
*/
export function addCommasEveryN(str: string, n = 3, memory = 1): string {
if (str.length > 1) {
if (memory === n) {
return addCommasEveryN(str.slice(0, -1), n, 1) + "," + str.slice(-1);
} else {
return addCommasEveryN(str.slice(0, -1), n, memory + 1) + str.slice(-1);
}
} else {
return str;
}
}
/**
*
* @param quantity the value as a string with no decimals
* @param decimals the number of decimals it should have
* @returns the number and the fraction
*/
export function displayUnit(quantity: string, decimals = 6): [string, string] {
const aboveDecimal = quantity.length - decimals;
const num = aboveDecimal > 0 ? quantity.slice(0, aboveDecimal) : "0";
let subNum = quantity.slice(-1 * decimals).padStart(decimals, "0");
if (decimals === 0) {
subNum = "";
}
return [num, subNum];
}
| 23.968421 | 79 | 0.640316 | 51 | 7 | 0 | 12 | 9 | 0 | 2 | 0 | 12 | 0 | 0 | 5.714286 | 681 | 0.0279 | 0.013216 | 0 | 0 | 0 | 0 | 0.428571 | 0.278463 | /**
*
* @param start number to start from (inclusive)
* @param end number to end at (inclusive)
* @returns range including start and end
*/
export function range(start, end) {
if (start > end) {
return [];
}
return Array(end - start + 1)
.fill(0)
.map((_, idx) => start + idx);
}
/**
*
* @param fileName the filename to get the extention from
* @returns either the extention or undefined
*/
export function findFileExtention(fileName) {
const re = /(?:\.([^.]+))?$/;
const res = re.exec(fileName);
if (res) {
return res[1];
}
return undefined;
}
/**
*
* @param length the length
* @returns a random string of a given length
*/
export function makeID(length) {
let result = "";
const characters =
"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
const charactersLength = characters.length;
for (let i = 0; i < length; i++) {
result += characters.charAt(Math.floor(Math.random() * charactersLength));
}
return result;
}
/**
* Removes trailing zeros
*
* @param str the string
* @returns
*/
export /* Example usages of 'removeTrailingZeros' are shown below:
str[str.length - 1] === "0"
? removeTrailingZeros(str.slice(0, -1))
: str;
*/
function removeTrailingZeros(str) {
return str[str.length - 1] === "0"
? removeTrailingZeros(str.slice(0, -1))
: str;
}
/**
*
* @param str the string to add commas to
* @param n how often to add commas
* @param memory internal emory
* @returns a formated string
*/
export /* Example usages of 'addCommasEveryN' are shown below:
addCommasEveryN(str.slice(0, -1), n, 1) + "," + str.slice(-1);
addCommasEveryN(str.slice(0, -1), n, memory + 1) + str.slice(-1);
*/
function addCommasEveryN(str, n = 3, memory = 1) {
if (str.length > 1) {
if (memory === n) {
return addCommasEveryN(str.slice(0, -1), n, 1) + "," + str.slice(-1);
} else {
return addCommasEveryN(str.slice(0, -1), n, memory + 1) + str.slice(-1);
}
} else {
return str;
}
}
/**
*
* @param quantity the value as a string with no decimals
* @param decimals the number of decimals it should have
* @returns the number and the fraction
*/
export function displayUnit(quantity, decimals = 6) {
const aboveDecimal = quantity.length - decimals;
const num = aboveDecimal > 0 ? quantity.slice(0, aboveDecimal) : "0";
let subNum = quantity.slice(-1 * decimals).padStart(decimals, "0");
if (decimals === 0) {
subNum = "";
}
return [num, subNum];
}
|
454b03c9785e73a229da1961f2d0f2cb87393932 | 4,910 | ts | TypeScript | src/termios.ts | mame/xterm-pty | 4424b40ad7b5985e217b9aabc74ed3aa3678275b | [
"MIT"
] | 5 | 2022-02-18T10:48:32.000Z | 2022-03-24T18:32:26.000Z | src/termios.ts | mame/xterm-pty | 4424b40ad7b5985e217b9aabc74ed3aa3678275b | [
"MIT"
] | null | null | null | src/termios.ts | mame/xterm-pty | 4424b40ad7b5985e217b9aabc74ed3aa3678275b | [
"MIT"
] | null | null | null | // This module provides a Termios class for termios struct data.
//
// https://man7.org/linux/man-pages/man3/termios.3.html
// c_iflag
export const ISTRIP = 0x0020;
export const INLCR = 0x0040;
export const IGNCR = 0x0080;
export const ICRNL = 0x0100;
export const IUCLC = 0x0200;
export const IXON = 0x0400;
export const IXANY = 0x0800;
export const IMAXBEL = 0x2000;
export const IUTF8 = 0x4000;
// c_oflag
export const OPOST = 0x0001;
export const OLCUC = 0x0002;
export const ONLCR = 0x0004;
export const OCRNL = 0x0008;
export const ONOCR = 0x0010;
export const ONLRET = 0x0020;
export const TABDLY = 0x1800;
export const XTABS = 0x1800;
// c_lflag
export const ISIG = 0x0001;
export const ICANON = 0x0002;
export const ECHO = 0x0008;
export const ECHOE = 0x0010;
export const ECHOK = 0x0020;
export const ECHONL = 0x0040;
export const NOFLSH = 0x0080;
export const ECHOCTL = 0x0200;
export const ECHOPRT = 0x0400;
export const ECHOKE = 0x0800;
export const IEXTEN = 0x8000;
// c_cc
export const VINTR = 0;
export const VQUIT = 1;
export const VERASE = 2;
export const VKILL = 3;
export const VEOF = 4;
export const VTIME = 5;
export const VMIN = 6;
export const VSWTCH = 7;
export const VSTART = 8;
export const VSTOP = 9;
export const VSUSP = 10;
export const VEOL = 11;
export const VREPRINT = 12;
export const VDISCARD = 13;
export const VWERASE = 14;
export const VLNEXT = 15;
export const VEOL2 = 16;
export class Termios {
constructor(
readonly iflag: number,
readonly oflag: number,
readonly cflag: number,
readonly lflag: number,
readonly cc: number[]
) {}
readonly ISTRIP_P = (this.iflag & ISTRIP) != 0;
readonly INLCR_P = (this.iflag & INLCR) != 0;
readonly IGNCR_P = (this.iflag & IGNCR) != 0;
readonly ICRNL_P = (this.iflag & ICRNL) != 0;
readonly IUCLC_P = (this.iflag & IUCLC) != 0;
readonly IXON_P = (this.iflag & IXON) != 0;
readonly IXANY_P = (this.iflag & IXANY) != 0;
readonly IUTF8_P = (this.iflag & IUTF8) != 0;
readonly OPOST_P = (this.oflag & OPOST) != 0;
readonly OLCUC_P = (this.oflag & OLCUC) != 0;
readonly ONLCR_P = (this.oflag & ONLCR) != 0;
readonly OCRNL_P = (this.oflag & OCRNL) != 0;
readonly ONOCR_P = (this.oflag & ONOCR) != 0;
readonly ONLRET_P = (this.oflag & ONLRET) != 0;
readonly TABDLY_XTABS_P = (this.oflag & TABDLY) == XTABS;
readonly ISIG_P = (this.lflag & ISIG) != 0;
readonly ICANON_P = (this.lflag & ICANON) != 0;
readonly ECHO_P = (this.lflag & ECHO) != 0;
readonly ECHOE_P = (this.lflag & ECHOE) != 0;
readonly ECHOK_P = (this.lflag & ECHOK) != 0;
readonly ECHONL_P = (this.lflag & ECHONL) != 0;
readonly NOFLSH_P = (this.lflag & NOFLSH) != 0;
readonly ECHOCTL_P = (this.lflag & ECHOCTL) != 0;
readonly ECHOPRT_P = (this.lflag & ECHOPRT) != 0;
readonly ECHOKE_P = (this.lflag & ECHOKE) != 0;
readonly IEXTEN_P = (this.lflag & IEXTEN) != 0;
readonly INTR_V = this.cc[VINTR];
readonly QUIT_V = this.cc[VQUIT];
readonly ERASE_V = this.cc[VERASE];
readonly KILL_V = this.cc[VKILL];
readonly EOF_V = this.cc[VEOF];
readonly TIME_V = this.cc[VTIME]; // not supported
readonly MIN_V = this.cc[VMIN]; // not supported
readonly SWTCH_V = this.cc[VSWTCH]; // not supported
readonly START_V = this.cc[VSTART];
readonly STOP_V = this.cc[VSTOP];
readonly SUSP_V = this.cc[VSUSP];
readonly EOL_V = this.cc[VEOL];
readonly REPRINT_V = this.cc[VREPRINT];
readonly DISCARD_V = this.cc[VDISCARD]; // not supported
readonly WERASE_V = this.cc[VWERASE];
readonly LNEXT_V = this.cc[VLNEXT];
readonly EOL2_V = this.cc[VEOL2];
clone() {
return new Termios(
this.iflag,
this.oflag,
this.cflag,
this.lflag,
this.cc.concat()
);
}
}
export const defaultTermios = new Termios(
ICRNL | IXON | IMAXBEL | IUTF8,
OPOST | ONLCR,
0x00bf, // c_cflag is not supported
ISIG | ICANON | ECHO | ECHOE | ECHOK | ECHOCTL | ECHOKE | IEXTEN,
[
0x03, 0x1c, 0x7f, 0x15, 0x04, 0x00, 0x01, 0x00, 0x11, 0x13, 0x1a, 0x00,
0x12, 0x0f, 0x17, 0x16, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
]
);
export const termiosToData = (termios: Termios) => {
const data = [termios.iflag, termios.oflag, termios.cflag, termios.lflag];
let word = 0;
let offset = 8;
for (let i = 0; i < termios.cc.length; i++) {
word |= termios.cc[i] << offset;
offset += 8;
if (offset == 32) {
data.push(word);
word = 0;
offset = 0;
}
}
data.push(word);
return data;
};
export const dataToTermios = (data: number[]): Termios => {
const cc: number[] = [];
let ptr = 4;
let word = data[ptr++];
let offset = 8;
for (let i = 0; i < 32; i++) {
cc.push((word >> offset) & 0xff);
offset += 8;
if (offset >= 32) {
word = data[ptr++];
offset = 0;
}
}
return new Termios(data[0], data[1], data[2], data[3], cc);
};
| 29.401198 | 76 | 0.654379 | 148 | 4 | 0 | 7 | 57 | 43 | 0 | 0 | 7 | 1 | 0 | 8.5 | 2,149 | 0.005119 | 0.026524 | 0.020009 | 0.000465 | 0 | 0 | 0.063063 | 0.269345 | // This module provides a Termios class for termios struct data.
//
// https://man7.org/linux/man-pages/man3/termios.3.html
// c_iflag
export const ISTRIP = 0x0020;
export const INLCR = 0x0040;
export const IGNCR = 0x0080;
export const ICRNL = 0x0100;
export const IUCLC = 0x0200;
export const IXON = 0x0400;
export const IXANY = 0x0800;
export const IMAXBEL = 0x2000;
export const IUTF8 = 0x4000;
// c_oflag
export const OPOST = 0x0001;
export const OLCUC = 0x0002;
export const ONLCR = 0x0004;
export const OCRNL = 0x0008;
export const ONOCR = 0x0010;
export const ONLRET = 0x0020;
export const TABDLY = 0x1800;
export const XTABS = 0x1800;
// c_lflag
export const ISIG = 0x0001;
export const ICANON = 0x0002;
export const ECHO = 0x0008;
export const ECHOE = 0x0010;
export const ECHOK = 0x0020;
export const ECHONL = 0x0040;
export const NOFLSH = 0x0080;
export const ECHOCTL = 0x0200;
export const ECHOPRT = 0x0400;
export const ECHOKE = 0x0800;
export const IEXTEN = 0x8000;
// c_cc
export const VINTR = 0;
export const VQUIT = 1;
export const VERASE = 2;
export const VKILL = 3;
export const VEOF = 4;
export const VTIME = 5;
export const VMIN = 6;
export const VSWTCH = 7;
export const VSTART = 8;
export const VSTOP = 9;
export const VSUSP = 10;
export const VEOL = 11;
export const VREPRINT = 12;
export const VDISCARD = 13;
export const VWERASE = 14;
export const VLNEXT = 15;
export const VEOL2 = 16;
export class Termios {
constructor(
readonly iflag,
readonly oflag,
readonly cflag,
readonly lflag,
readonly cc
) {}
readonly ISTRIP_P = (this.iflag & ISTRIP) != 0;
readonly INLCR_P = (this.iflag & INLCR) != 0;
readonly IGNCR_P = (this.iflag & IGNCR) != 0;
readonly ICRNL_P = (this.iflag & ICRNL) != 0;
readonly IUCLC_P = (this.iflag & IUCLC) != 0;
readonly IXON_P = (this.iflag & IXON) != 0;
readonly IXANY_P = (this.iflag & IXANY) != 0;
readonly IUTF8_P = (this.iflag & IUTF8) != 0;
readonly OPOST_P = (this.oflag & OPOST) != 0;
readonly OLCUC_P = (this.oflag & OLCUC) != 0;
readonly ONLCR_P = (this.oflag & ONLCR) != 0;
readonly OCRNL_P = (this.oflag & OCRNL) != 0;
readonly ONOCR_P = (this.oflag & ONOCR) != 0;
readonly ONLRET_P = (this.oflag & ONLRET) != 0;
readonly TABDLY_XTABS_P = (this.oflag & TABDLY) == XTABS;
readonly ISIG_P = (this.lflag & ISIG) != 0;
readonly ICANON_P = (this.lflag & ICANON) != 0;
readonly ECHO_P = (this.lflag & ECHO) != 0;
readonly ECHOE_P = (this.lflag & ECHOE) != 0;
readonly ECHOK_P = (this.lflag & ECHOK) != 0;
readonly ECHONL_P = (this.lflag & ECHONL) != 0;
readonly NOFLSH_P = (this.lflag & NOFLSH) != 0;
readonly ECHOCTL_P = (this.lflag & ECHOCTL) != 0;
readonly ECHOPRT_P = (this.lflag & ECHOPRT) != 0;
readonly ECHOKE_P = (this.lflag & ECHOKE) != 0;
readonly IEXTEN_P = (this.lflag & IEXTEN) != 0;
readonly INTR_V = this.cc[VINTR];
readonly QUIT_V = this.cc[VQUIT];
readonly ERASE_V = this.cc[VERASE];
readonly KILL_V = this.cc[VKILL];
readonly EOF_V = this.cc[VEOF];
readonly TIME_V = this.cc[VTIME]; // not supported
readonly MIN_V = this.cc[VMIN]; // not supported
readonly SWTCH_V = this.cc[VSWTCH]; // not supported
readonly START_V = this.cc[VSTART];
readonly STOP_V = this.cc[VSTOP];
readonly SUSP_V = this.cc[VSUSP];
readonly EOL_V = this.cc[VEOL];
readonly REPRINT_V = this.cc[VREPRINT];
readonly DISCARD_V = this.cc[VDISCARD]; // not supported
readonly WERASE_V = this.cc[VWERASE];
readonly LNEXT_V = this.cc[VLNEXT];
readonly EOL2_V = this.cc[VEOL2];
clone() {
return new Termios(
this.iflag,
this.oflag,
this.cflag,
this.lflag,
this.cc.concat()
);
}
}
export const defaultTermios = new Termios(
ICRNL | IXON | IMAXBEL | IUTF8,
OPOST | ONLCR,
0x00bf, // c_cflag is not supported
ISIG | ICANON | ECHO | ECHOE | ECHOK | ECHOCTL | ECHOKE | IEXTEN,
[
0x03, 0x1c, 0x7f, 0x15, 0x04, 0x00, 0x01, 0x00, 0x11, 0x13, 0x1a, 0x00,
0x12, 0x0f, 0x17, 0x16, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
]
);
export const termiosToData = (termios) => {
const data = [termios.iflag, termios.oflag, termios.cflag, termios.lflag];
let word = 0;
let offset = 8;
for (let i = 0; i < termios.cc.length; i++) {
word |= termios.cc[i] << offset;
offset += 8;
if (offset == 32) {
data.push(word);
word = 0;
offset = 0;
}
}
data.push(word);
return data;
};
export const dataToTermios = (data) => {
const cc = [];
let ptr = 4;
let word = data[ptr++];
let offset = 8;
for (let i = 0; i < 32; i++) {
cc.push((word >> offset) & 0xff);
offset += 8;
if (offset >= 32) {
word = data[ptr++];
offset = 0;
}
}
return new Termios(data[0], data[1], data[2], data[3], cc);
};
|
20640323096824f5dfbb3597b8f9aa2664f71056 | 2,106 | ts | TypeScript | src/utils/files/parsers/parserCSV_PMD.ts | I194/PMTools_2.0 | 313dea61275c5f8b875376578a65e08b9c2fd128 | [
"MIT"
] | null | null | null | src/utils/files/parsers/parserCSV_PMD.ts | I194/PMTools_2.0 | 313dea61275c5f8b875376578a65e08b9c2fd128 | [
"MIT"
] | 1 | 2022-03-17T12:50:14.000Z | 2022-03-17T12:51:57.000Z | src/utils/files/parsers/parserCSV_PMD.ts | I194/PMTools_2.0 | 313dea61275c5f8b875376578a65e08b9c2fd128 | [
"MIT"
] | null | null | null | const parseCSV_PMD = (data: string, name: string) => {
// eslint-disable-next-line no-control-regex
const eol = new RegExp("\r?\n");
// Get all lines except the last one (it's garbage)
let lines = data.split(eol).filter(line => line.length > 1);
const headLine = lines[1].split(',');
const metadata = {
name,
a: +headLine[0],
b: +headLine[1],
s: +headLine[2],
d: +headLine[3],
v: +headLine[4],
}
const steps = lines.slice(3).map((line, index) => {
const params = line.replace(/\s+/g, ' ').split(',');
// PAL | Xc (Am2) | Yc (Am2) | Zc (Am2) | MAG (A/m) | Dg | Ig | Ds | Is| a95
// PAL === Step (mT or temp degrees)
// it's old format and we can't just split by " " 'cause it can cause issues
const step = params[0];
const x = +(+params[1]).toExponential(2);
const y = +(+params[2]).toExponential(2);
const z = +(+params[3]).toExponential(2);
const mag = +(+params[4]).toExponential(2);
const Dgeo = +(+params[5]).toFixed(1);
const Igeo = +(+params[6]).toFixed(1);
const Dstrat = +(+params[7]).toFixed(1);
const Istrat = +(+params[8]).toFixed(1);
const a95 = +(+params[9]).toFixed(1);
let comment = '';
// comment may be with commas
for (let i = 10; i < params.length; i++) comment += params[i];
comment = comment.trim();
// there is no standard for demagnetization symbol... and idk why
const demagSmbl = line.slice(0, 1);
const thermalTypes = ['T', 't'];
const alternatingTypes = ['M', 'm'];
let demagType: 'thermal' | 'alternating field' | undefined = undefined;
if (thermalTypes.indexOf(demagSmbl) > -1) demagType = 'thermal';
else if (alternatingTypes.indexOf(demagSmbl) > -1) demagType = 'alternating field';
return {
id: index + 1,
step,
x,
y,
z,
mag,
Dgeo,
Igeo,
Dstrat,
Istrat,
a95,
comment,
demagType,
};
});
return {
metadata,
steps,
format: "CSV_PMD",
created: new Date().toISOString(),
};
}
export default parseCSV_PMD; | 26.658228 | 87 | 0.566477 | 57 | 3 | 0 | 5 | 23 | 0 | 0 | 0 | 2 | 0 | 0 | 30 | 679 | 0.011782 | 0.033873 | 0 | 0 | 0 | 0 | 0.064516 | 0.308311 | /* Example usages of 'parseCSV_PMD' are shown below:
;
*/
const parseCSV_PMD = (data, name) => {
// eslint-disable-next-line no-control-regex
const eol = new RegExp("\r?\n");
// Get all lines except the last one (it's garbage)
let lines = data.split(eol).filter(line => line.length > 1);
const headLine = lines[1].split(',');
const metadata = {
name,
a: +headLine[0],
b: +headLine[1],
s: +headLine[2],
d: +headLine[3],
v: +headLine[4],
}
const steps = lines.slice(3).map((line, index) => {
const params = line.replace(/\s+/g, ' ').split(',');
// PAL | Xc (Am2) | Yc (Am2) | Zc (Am2) | MAG (A/m) | Dg | Ig | Ds | Is| a95
// PAL === Step (mT or temp degrees)
// it's old format and we can't just split by " " 'cause it can cause issues
const step = params[0];
const x = +(+params[1]).toExponential(2);
const y = +(+params[2]).toExponential(2);
const z = +(+params[3]).toExponential(2);
const mag = +(+params[4]).toExponential(2);
const Dgeo = +(+params[5]).toFixed(1);
const Igeo = +(+params[6]).toFixed(1);
const Dstrat = +(+params[7]).toFixed(1);
const Istrat = +(+params[8]).toFixed(1);
const a95 = +(+params[9]).toFixed(1);
let comment = '';
// comment may be with commas
for (let i = 10; i < params.length; i++) comment += params[i];
comment = comment.trim();
// there is no standard for demagnetization symbol... and idk why
const demagSmbl = line.slice(0, 1);
const thermalTypes = ['T', 't'];
const alternatingTypes = ['M', 'm'];
let demagType = undefined;
if (thermalTypes.indexOf(demagSmbl) > -1) demagType = 'thermal';
else if (alternatingTypes.indexOf(demagSmbl) > -1) demagType = 'alternating field';
return {
id: index + 1,
step,
x,
y,
z,
mag,
Dgeo,
Igeo,
Dstrat,
Istrat,
a95,
comment,
demagType,
};
});
return {
metadata,
steps,
format: "CSV_PMD",
created: new Date().toISOString(),
};
}
export default parseCSV_PMD; |
5ed708ef95bc7ed97b45ff2c6c25a389e4ff18b5 | 3,694 | ts | TypeScript | problemset/longest-nice-substring/index.ts | OUDUIDUI/leet-code | 50e61ce16d1c419ccefc075ae9ead721cdd1cdbb | [
"MIT"
] | 6 | 2022-01-17T03:19:56.000Z | 2022-01-17T05:45:39.000Z | problemset/longest-nice-substring/index.ts | OUDUIDUI/leet-code | 50e61ce16d1c419ccefc075ae9ead721cdd1cdbb | [
"MIT"
] | null | null | null | problemset/longest-nice-substring/index.ts | OUDUIDUI/leet-code | 50e61ce16d1c419ccefc075ae9ead721cdd1cdbb | [
"MIT"
] | null | null | null | /**
* 暴力解法
* @desc 时间复杂度 O(N^2) 空间复杂度 O(1)
* @param s {string}
* @return {string}
*/
export function longestNiceSubstring(s: string): string {
const len = s.length
let maxPosition = 0
let maxLength = 0
for (let i = 0; i < len; i++) {
let lower = 0
let upper = 0
for (let j = i; j < len; j++) {
// 利用26位二进制来表示字母
// abcdefghijklmnopqrstuvwxyz
// 00000000000000000000000000
if (s[j] >= 'a' && s[j] <= 'z') {
// 小写
lower |= 1 << (s[j].charCodeAt(0) - 'a'.charCodeAt(0))
}
else {
// 大写
upper |= 1 << (s[j].charCodeAt(0) - 'A'.charCodeAt(0))
}
if (lower === upper && j - i + 1 > maxLength) {
maxPosition = i
maxLength = j - i + 1
}
}
}
return s.slice(maxPosition, maxPosition + maxLength)
}
/**
* 分治
* @desc 时间复杂度 O(N⋅∣Σ∣) ∣Σ∣ 为字符集的大小 空间复杂度 O(∣Σ∣)
* @param s {string}
* @return {string}
*/
export function longestNiceSubstring2(s: string): string {
let maxPosition = 0
let maxLength = 0
dfs(0, s.length - 1)
return s.substring(maxLength, maxPosition + maxPosition)
function dfs(start: number, end: number): void {
if (start >= end) return
let lower = 0
let upper = 0
for (let i = start; i <= end; i++) {
if (s[i] >= 'a' && s[i] <= 'z')
lower |= 1 << (s[i].charCodeAt(0) - 'a'.charCodeAt(0))
else
upper |= 1 << (s[i].charCodeAt(0) - 'A'.charCodeAt(0))
}
if (lower <= upper) {
if (end - start + 1 > maxLength) {
maxPosition = start
maxLength = end - start + 1
}
return
}
const valid = lower & upper
let pos = start
while (pos <= end) {
start = pos
while (
pos <= end
&& (valid
& (1 << (s[pos].toLowerCase().charCodeAt(0) - 'a'.charCodeAt(0))))
!== 0
)
pos++
dfs(start, pos - 1)
pos++
}
}
}
/**
* 滑动窗口
* @desc 时间复杂度 O(N⋅∣Σ∣) ∣Σ∣ 为字符集的大小 空间复杂度 O(∣Σ∣)
* @param s {string}
* @return {string}
*/
export function longestNiceSubstring3(s: string): string {
let maxPosition = 0
let maxLength = 0
let types = 0
for (let i = 0; i < s.length; ++i)
types |= 1 << (s[i].toLowerCase().charCodeAt(0) - 'a'.charCodeAt(0))
types = bitCount(types)
for (let i = 1; i <= types; i++)
check(s, i)
return s.slice(maxPosition, maxPosition + maxLength)
function bitCount(n: number) {
let ret = 0
while (n) {
n &= n - 1
ret++
}
return ret
}
function check(s: string, typeNum: number) {
const lowerCnt = new Array(26).fill(0)
const upperCnt = new Array(26).fill(0)
let cnt = 0
for (let l = 0, r = 0, total = 0; r < s.length; r++) {
let idx = s[r].toLowerCase().charCodeAt(0) - 'a'.charCodeAt(0)
if (s[r] >= 'a' && s[r] <= 'z') {
lowerCnt[idx]++
if (lowerCnt[idx] === 1 && upperCnt[idx] > 0)
cnt++
}
else {
upperCnt[idx]++
if (upperCnt[idx] === 1 && lowerCnt[idx] > 0)
cnt++
}
total += lowerCnt[idx] + upperCnt[idx] === 1 ? 1 : 0
while (total > typeNum) {
idx = s[l].toLowerCase().charCodeAt(0) - 'a'.charCodeAt(0)
total -= lowerCnt[idx] + upperCnt[idx] === 1 ? 1 : 0
if (s[l] >= 'a' && s[l] <= 'z') {
lowerCnt[idx]--
if (lowerCnt[idx] === 0 && upperCnt[idx] > 0)
cnt--
}
else {
upperCnt[idx]--
if (upperCnt[idx] === 0 && lowerCnt[idx] > 0)
cnt--
}
l++
}
if (cnt === typeNum && r - l + 1 > maxLength) {
maxPosition = l
maxLength = r - l + 1
}
}
}
}
| 23.987013 | 76 | 0.48836 | 117 | 6 | 0 | 8 | 27 | 0 | 3 | 0 | 12 | 0 | 0 | 30.5 | 1,329 | 0.010534 | 0.020316 | 0 | 0 | 0 | 0 | 0.292683 | 0.261561 | /**
* 暴力解法
* @desc 时间复杂度 O(N^2) 空间复杂度 O(1)
* @param s {string}
* @return {string}
*/
export function longestNiceSubstring(s) {
const len = s.length
let maxPosition = 0
let maxLength = 0
for (let i = 0; i < len; i++) {
let lower = 0
let upper = 0
for (let j = i; j < len; j++) {
// 利用26位二进制来表示字母
// abcdefghijklmnopqrstuvwxyz
// 00000000000000000000000000
if (s[j] >= 'a' && s[j] <= 'z') {
// 小写
lower |= 1 << (s[j].charCodeAt(0) - 'a'.charCodeAt(0))
}
else {
// 大写
upper |= 1 << (s[j].charCodeAt(0) - 'A'.charCodeAt(0))
}
if (lower === upper && j - i + 1 > maxLength) {
maxPosition = i
maxLength = j - i + 1
}
}
}
return s.slice(maxPosition, maxPosition + maxLength)
}
/**
* 分治
* @desc 时间复杂度 O(N⋅∣Σ∣) ∣Σ∣ 为字符集的大小 空间复杂度 O(∣Σ∣)
* @param s {string}
* @return {string}
*/
export function longestNiceSubstring2(s) {
let maxPosition = 0
let maxLength = 0
dfs(0, s.length - 1)
return s.substring(maxLength, maxPosition + maxPosition)
/* Example usages of 'dfs' are shown below:
dfs(0, s.length - 1);
dfs(start, pos - 1);
*/
function dfs(start, end) {
if (start >= end) return
let lower = 0
let upper = 0
for (let i = start; i <= end; i++) {
if (s[i] >= 'a' && s[i] <= 'z')
lower |= 1 << (s[i].charCodeAt(0) - 'a'.charCodeAt(0))
else
upper |= 1 << (s[i].charCodeAt(0) - 'A'.charCodeAt(0))
}
if (lower <= upper) {
if (end - start + 1 > maxLength) {
maxPosition = start
maxLength = end - start + 1
}
return
}
const valid = lower & upper
let pos = start
while (pos <= end) {
start = pos
while (
pos <= end
&& (valid
& (1 << (s[pos].toLowerCase().charCodeAt(0) - 'a'.charCodeAt(0))))
!== 0
)
pos++
dfs(start, pos - 1)
pos++
}
}
}
/**
* 滑动窗口
* @desc 时间复杂度 O(N⋅∣Σ∣) ∣Σ∣ 为字符集的大小 空间复杂度 O(∣Σ∣)
* @param s {string}
* @return {string}
*/
export function longestNiceSubstring3(s) {
let maxPosition = 0
let maxLength = 0
let types = 0
for (let i = 0; i < s.length; ++i)
types |= 1 << (s[i].toLowerCase().charCodeAt(0) - 'a'.charCodeAt(0))
types = bitCount(types)
for (let i = 1; i <= types; i++)
check(s, i)
return s.slice(maxPosition, maxPosition + maxLength)
/* Example usages of 'bitCount' are shown below:
types = bitCount(types);
*/
function bitCount(n) {
let ret = 0
while (n) {
n &= n - 1
ret++
}
return ret
}
/* Example usages of 'check' are shown below:
check(s, i);
*/
function check(s, typeNum) {
const lowerCnt = new Array(26).fill(0)
const upperCnt = new Array(26).fill(0)
let cnt = 0
for (let l = 0, r = 0, total = 0; r < s.length; r++) {
let idx = s[r].toLowerCase().charCodeAt(0) - 'a'.charCodeAt(0)
if (s[r] >= 'a' && s[r] <= 'z') {
lowerCnt[idx]++
if (lowerCnt[idx] === 1 && upperCnt[idx] > 0)
cnt++
}
else {
upperCnt[idx]++
if (upperCnt[idx] === 1 && lowerCnt[idx] > 0)
cnt++
}
total += lowerCnt[idx] + upperCnt[idx] === 1 ? 1 : 0
while (total > typeNum) {
idx = s[l].toLowerCase().charCodeAt(0) - 'a'.charCodeAt(0)
total -= lowerCnt[idx] + upperCnt[idx] === 1 ? 1 : 0
if (s[l] >= 'a' && s[l] <= 'z') {
lowerCnt[idx]--
if (lowerCnt[idx] === 0 && upperCnt[idx] > 0)
cnt--
}
else {
upperCnt[idx]--
if (upperCnt[idx] === 0 && lowerCnt[idx] > 0)
cnt--
}
l++
}
if (cnt === typeNum && r - l + 1 > maxLength) {
maxPosition = l
maxLength = r - l + 1
}
}
}
}
|
5ee8da532cd90e4925e467deb8769a2f6b51a942 | 1,900 | ts | TypeScript | utils/TimeCalculator.ts | alikemalcelenk/todolist-frontend | 59d2759a8ffe9ca0d90253ad951c102357db09ce | [
"MIT"
] | 1 | 2022-01-13T18:13:31.000Z | 2022-01-13T18:13:31.000Z | utils/TimeCalculator.ts | alikemalcelenk/todolist-frontend | 59d2759a8ffe9ca0d90253ad951c102357db09ce | [
"MIT"
] | null | null | null | utils/TimeCalculator.ts | alikemalcelenk/todolist-frontend | 59d2759a8ffe9ca0d90253ad951c102357db09ce | [
"MIT"
] | null | null | null | type TimeCalculatorPropsType = {
createdAt: Date
}
const TimeCalculator = ({ createdAt }: TimeCalculatorPropsType): string => {
const createdDate: Date = new Date(createdAt)
const nowDate: Date = new Date()
const months = [
'January',
'February',
'March',
'April',
'May',
'June',
'July',
'August',
'September',
'October',
'November',
'December'
]
const days = ['Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat']
const milisecond: number = nowDate.valueOf() - createdDate.valueOf()
const second = milisecond / 1000
const minute = second / 60
const hour = minute / 60
const day = hour / 24
if (second < 1) {
return 'now'
}
if (
Math.floor(minute) === 0 &&
Math.floor(hour) === 0 &&
Math.floor(day) === 0
) {
return Math.round(second) === 1
? `${Math.round(second)} second ago`
: `${Math.round(second)} seconds ago`
}
if (Math.floor(day) === 0 && Math.floor(hour) === 0) {
return Math.round(minute) === 1
? `${Math.round(minute)} minute ago`
: `${Math.round(minute)} minutes ago`
}
if (Math.floor(day) === 0) {
return Math.round(hour) === 1
? `${Math.round(hour)} hour ago`
: `${Math.round(hour)} hours ago`
}
if (Math.round(day) < 7) {
return Math.round(day) === 1
? `${Math.round(day)} day ago`
: `${Math.round(day)} days ago`
}
const dayName = days[createdDate.getDay()]
const date = createdDate.getDate()
const monthName = months[createdDate.getMonth()]
const createdYear =
createdDate.getFullYear() === nowDate.getFullYear()
? ''
: createdDate.getFullYear()
const createdTime = createdDate.toLocaleTimeString([], {
hour: '2-digit',
minute: '2-digit',
hour12: false
})
return `${createdTime} · ${dayName}, ${date} ${monthName} ${createdYear}`
}
export default TimeCalculator
| 23.45679 | 76 | 0.584211 | 68 | 1 | 0 | 1 | 15 | 1 | 0 | 0 | 2 | 1 | 0 | 62 | 583 | 0.003431 | 0.025729 | 0.001715 | 0.001715 | 0 | 0 | 0.111111 | 0.265004 | type TimeCalculatorPropsType = {
createdAt
}
/* Example usages of 'TimeCalculator' are shown below:
;
*/
const TimeCalculator = ({ createdAt }) => {
const createdDate = new Date(createdAt)
const nowDate = new Date()
const months = [
'January',
'February',
'March',
'April',
'May',
'June',
'July',
'August',
'September',
'October',
'November',
'December'
]
const days = ['Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat']
const milisecond = nowDate.valueOf() - createdDate.valueOf()
const second = milisecond / 1000
const minute = second / 60
const hour = minute / 60
const day = hour / 24
if (second < 1) {
return 'now'
}
if (
Math.floor(minute) === 0 &&
Math.floor(hour) === 0 &&
Math.floor(day) === 0
) {
return Math.round(second) === 1
? `${Math.round(second)} second ago`
: `${Math.round(second)} seconds ago`
}
if (Math.floor(day) === 0 && Math.floor(hour) === 0) {
return Math.round(minute) === 1
? `${Math.round(minute)} minute ago`
: `${Math.round(minute)} minutes ago`
}
if (Math.floor(day) === 0) {
return Math.round(hour) === 1
? `${Math.round(hour)} hour ago`
: `${Math.round(hour)} hours ago`
}
if (Math.round(day) < 7) {
return Math.round(day) === 1
? `${Math.round(day)} day ago`
: `${Math.round(day)} days ago`
}
const dayName = days[createdDate.getDay()]
const date = createdDate.getDate()
const monthName = months[createdDate.getMonth()]
const createdYear =
createdDate.getFullYear() === nowDate.getFullYear()
? ''
: createdDate.getFullYear()
const createdTime = createdDate.toLocaleTimeString([], {
hour: '2-digit',
minute: '2-digit',
hour12: false
})
return `${createdTime} · ${dayName}, ${date} ${monthName} ${createdYear}`
}
export default TimeCalculator
|
0e255207991b7ff849f8105fec830f5ed65f2299 | 3,210 | ts | TypeScript | solutions/day13.ts | GiyoMoon/aoc2021 | 83d7e9018ed3b628353bc9a0a37b70a1462ecd74 | [
"Unlicense"
] | null | null | null | solutions/day13.ts | GiyoMoon/aoc2021 | 83d7e9018ed3b628353bc9a0a37b70a1462ecd74 | [
"Unlicense"
] | 1 | 2022-02-03T11:04:17.000Z | 2022-02-03T11:04:17.000Z | solutions/day13.ts | GiyoMoon/aoc2021 | 83d7e9018ed3b628353bc9a0a37b70a1462ecd74 | [
"Unlicense"
] | null | null | null | export default class Day13 {
public solve(input: string): { part1: any, part2: any; } {
const coords = input.split('\n\n')[0].split('\n').map(coords => coords.split(',').map(c => parseInt(c)));
const folds = input.split('\n\n')[1].split('\n').map(folds => [folds.split(' ')[2].split('=')[0], parseInt(folds.split(' ')[2].split('=')[1])]) as [string, number][];
let paper = this._preparePaper(coords, folds.find(f => f[0] === 'y'));
paper = this._fold(paper, [folds.shift()]);
const dotCountPart1 = this._countDots(paper);
paper = this._fold(paper, folds);
return { part1: dotCountPart1, part2: '\n' + this._formatPaper(paper) };
}
private _fold(paper: boolean[][], folds: [string, number][]) {
for (const fold of folds) {
if (fold[0] === 'y') {
paper = this._foldY(paper, fold[1]);
} else if (fold[0] === 'x') {
paper = this._foldX(paper, fold[1]);
}
}
return paper;
}
private _foldY(paper: boolean[][], foldIndex: number) {
let firstHalf = paper.slice(0, foldIndex);
let secondHalf = paper.slice(foldIndex + 1).reverse();
return this._combineArrays(firstHalf, secondHalf);
}
private _foldX(paper: boolean[][], foldIndex: number) {
let firstHalf: boolean[][] = [];
let secondHalf: boolean[][] = [];
for (let y = 0; y < paper.length; y++) {
firstHalf.push(paper[y].slice(0, foldIndex));
secondHalf.push(paper[y].slice(foldIndex + 1).reverse());
}
return this._combineArrays(firstHalf, secondHalf);
}
private _combineArrays(first: boolean[][], second: boolean[][]) {
const result: boolean[][] = [];
for (let y = 0; y < first.length; y++) {
if (!result[y]) {
result[y] = [];
}
for (let x = 0; x < first[0].length; x++) {
if (first[y][x] || second[y][x]) {
result[y][x] = true;
} else {
result[y][x] = false;
}
}
}
return result;
}
private _preparePaper(coords: number[][], firstYFold: [string, number]): boolean[][] {
let maxY = 0;
let maxX = 0;
for (const coord of coords) {
if (coord[1] > maxY) {
maxY = coord[1];
}
if (coord[0] > maxX) {
maxX = coord[0];
}
}
const paper = [];
for (let y = 0; y <= maxY; y++) {
paper.push(new Array(maxX + 1).fill(false));
}
for (const coord of coords) {
paper[coord[1]][coord[0]] = true;
}
if (paper.length <= (firstYFold[1]) * 2) {
const toAdd = firstYFold[1] * 2 - paper.length + 1;
for (let i = 0; i < toAdd; i++) {
paper.push(new Array(maxX + 1).fill(false));
}
}
return paper;
}
private _countDots(paper: boolean[][]) {
let dotCount = 0;
paper.forEach(line => {
line.forEach(c => {
if (c) {
dotCount++;
}
});
});
return dotCount;
}
private _formatPaper(paper: boolean[][]) {
let textString = '';
paper.forEach(l => {
l.forEach((c: any) => {
if (c) {
textString += '#';
} else {
textString += ' ';
}
});
textString += '\n';
});
return textString;
}
}
| 25.887097 | 170 | 0.520249 | 102 | 16 | 0 | 21 | 20 | 0 | 7 | 3 | 21 | 1 | 1 | 6.8125 | 985 | 0.037563 | 0.020305 | 0 | 0.001015 | 0.001015 | 0.052632 | 0.368421 | 0.326261 | export default class Day13 {
public solve(input) {
const coords = input.split('\n\n')[0].split('\n').map(coords => coords.split(',').map(c => parseInt(c)));
const folds = input.split('\n\n')[1].split('\n').map(folds => [folds.split(' ')[2].split('=')[0], parseInt(folds.split(' ')[2].split('=')[1])]) as [string, number][];
let paper = this._preparePaper(coords, folds.find(f => f[0] === 'y'));
paper = this._fold(paper, [folds.shift()]);
const dotCountPart1 = this._countDots(paper);
paper = this._fold(paper, folds);
return { part1: dotCountPart1, part2: '\n' + this._formatPaper(paper) };
}
private _fold(paper, folds) {
for (const fold of folds) {
if (fold[0] === 'y') {
paper = this._foldY(paper, fold[1]);
} else if (fold[0] === 'x') {
paper = this._foldX(paper, fold[1]);
}
}
return paper;
}
private _foldY(paper, foldIndex) {
let firstHalf = paper.slice(0, foldIndex);
let secondHalf = paper.slice(foldIndex + 1).reverse();
return this._combineArrays(firstHalf, secondHalf);
}
private _foldX(paper, foldIndex) {
let firstHalf = [];
let secondHalf = [];
for (let y = 0; y < paper.length; y++) {
firstHalf.push(paper[y].slice(0, foldIndex));
secondHalf.push(paper[y].slice(foldIndex + 1).reverse());
}
return this._combineArrays(firstHalf, secondHalf);
}
private _combineArrays(first, second) {
const result = [];
for (let y = 0; y < first.length; y++) {
if (!result[y]) {
result[y] = [];
}
for (let x = 0; x < first[0].length; x++) {
if (first[y][x] || second[y][x]) {
result[y][x] = true;
} else {
result[y][x] = false;
}
}
}
return result;
}
private _preparePaper(coords, firstYFold) {
let maxY = 0;
let maxX = 0;
for (const coord of coords) {
if (coord[1] > maxY) {
maxY = coord[1];
}
if (coord[0] > maxX) {
maxX = coord[0];
}
}
const paper = [];
for (let y = 0; y <= maxY; y++) {
paper.push(new Array(maxX + 1).fill(false));
}
for (const coord of coords) {
paper[coord[1]][coord[0]] = true;
}
if (paper.length <= (firstYFold[1]) * 2) {
const toAdd = firstYFold[1] * 2 - paper.length + 1;
for (let i = 0; i < toAdd; i++) {
paper.push(new Array(maxX + 1).fill(false));
}
}
return paper;
}
private _countDots(paper) {
let dotCount = 0;
paper.forEach(line => {
line.forEach(c => {
if (c) {
dotCount++;
}
});
});
return dotCount;
}
private _formatPaper(paper) {
let textString = '';
paper.forEach(l => {
l.forEach((c) => {
if (c) {
textString += '#';
} else {
textString += ' ';
}
});
textString += '\n';
});
return textString;
}
}
|
0e7ba53e16ca02e860eb834b8b20bc6b63d10801 | 3,452 | ts | TypeScript | src/util.ts | cloudflare/opaque-ts | 4b6269bfac27e1f22c9bc7c18ecbb9c2641f333e | [
"BSD-3-Clause"
] | 15 | 2022-02-15T07:32:32.000Z | 2022-03-23T12:13:50.000Z | src/util.ts | cloudflare/opaque-ts | 4b6269bfac27e1f22c9bc7c18ecbb9c2641f333e | [
"BSD-3-Clause"
] | 1 | 2022-03-28T06:53:11.000Z | 2022-03-28T06:53:11.000Z | src/util.ts | cloudflare/opaque-ts | 4b6269bfac27e1f22c9bc7c18ecbb9c2641f333e | [
"BSD-3-Clause"
] | null | null | null | // Copyright (c) 2021 Cloudflare, Inc. and contributors.
// Copyright (c) 2021 Cloudflare, Inc.
// Licensed under the BSD-3-Clause license found in the LICENSE file or
// at https://opensource.org/licenses/BSD-3-Clause
export function joinAll(a: Uint8Array[]): Uint8Array {
let size = 0
for (let i = 0; i < a.length; i++) {
size += a[i as number].length
}
const ret = new Uint8Array(new ArrayBuffer(size))
for (let i = 0, offset = 0; i < a.length; i++) {
ret.set(a[i as number], offset)
offset += a[i as number].length
}
return ret
}
export function encode_number(n: number, bits: number): Uint8Array {
if (!(bits > 0 && bits <= 32)) {
throw new Error('only supports 32-bit encoding')
}
const max = 1 << bits
if (!(n >= 0 && n < max)) {
throw new Error(`number out of range [0,2^${bits}-1]`)
}
const numBytes = Math.ceil(bits / 8)
const out = new Uint8Array(numBytes)
for (let i = 0; i < numBytes; i++) {
out[(numBytes - 1 - i) as number] = (n >> (8 * i)) & 0xff
}
return out
}
function decode_number(a: Uint8Array, bits: number): number {
if (!(bits > 0 && bits <= 32)) {
throw new Error('only supports 32-bit encoding')
}
const numBytes = Math.ceil(bits / 8)
if (a.length !== numBytes) {
throw new Error('array has wrong size')
}
let out = 0
for (let i = 0; i < a.length; i++) {
out <<= 8
out += a[i as number]
}
return out
}
function encode_vector(a: Uint8Array, bits_header: number): Uint8Array {
return joinAll([encode_number(a.length, bits_header), a])
}
function decode_vector(
a: Uint8Array,
bits_header: number
): {
payload: Uint8Array
consumed: number
} {
if (a.length === 0) {
throw new Error('empty vector not allowed')
}
const numBytes = Math.ceil(bits_header / 8)
const header = a.subarray(0, numBytes)
const len = decode_number(header, bits_header)
const consumed = numBytes + len
const payload = a.slice(numBytes, consumed)
return { payload, consumed }
}
export function encode_vector_8(a: Uint8Array): Uint8Array {
return encode_vector(a, 8)
}
export function encode_vector_16(a: Uint8Array): Uint8Array {
return encode_vector(a, 16)
}
export function decode_vector_16(a: Uint8Array): {
payload: Uint8Array
consumed: number
} {
return decode_vector(a, 16)
}
export function checked_vector(a: Uint8Array, n: number, str = 'array'): Uint8Array {
if (a.length < n) {
throw new Error(`${str} has wrong length`)
}
return a.slice(0, n)
}
export function checked_vector_array(a: number[], n: number, str = 'array'): Uint8Array {
return checked_vector(Uint8Array.from(a), n, str)
}
export function xor(a: Uint8Array, b: Uint8Array): Uint8Array {
if (a.length !== b.length || a.length === 0) {
throw new Error('arrays of different length')
}
const n = a.length
const c = new Uint8Array(n)
for (let i = 0; i < n; i++) {
c[i as number] = a[i as number] ^ b[i as number]
}
return c
}
export function ctEqual(a: Uint8Array, b: Uint8Array): boolean {
if (a.length !== b.length || a.length === 0) {
throw new Error('arrays of different length')
}
const n = a.length
let c = 0
for (let i = 0; i < n; i++) {
c |= a[i as number] ^ b[i as number]
}
return c === 0
}
| 28.295082 | 89 | 0.604287 | 105 | 12 | 0 | 22 | 23 | 0 | 6 | 0 | 22 | 0 | 10 | 6 | 1,112 | 0.030576 | 0.020683 | 0 | 0 | 0.008993 | 0 | 0.385965 | 0.308854 | // Copyright (c) 2021 Cloudflare, Inc. and contributors.
// Copyright (c) 2021 Cloudflare, Inc.
// Licensed under the BSD-3-Clause license found in the LICENSE file or
// at https://opensource.org/licenses/BSD-3-Clause
export /* Example usages of 'joinAll' are shown below:
joinAll([encode_number(a.length, bits_header), a]);
*/
function joinAll(a) {
let size = 0
for (let i = 0; i < a.length; i++) {
size += a[i as number].length
}
const ret = new Uint8Array(new ArrayBuffer(size))
for (let i = 0, offset = 0; i < a.length; i++) {
ret.set(a[i as number], offset)
offset += a[i as number].length
}
return ret
}
export /* Example usages of 'encode_number' are shown below:
encode_number(a.length, bits_header);
*/
function encode_number(n, bits) {
if (!(bits > 0 && bits <= 32)) {
throw new Error('only supports 32-bit encoding')
}
const max = 1 << bits
if (!(n >= 0 && n < max)) {
throw new Error(`number out of range [0,2^${bits}-1]`)
}
const numBytes = Math.ceil(bits / 8)
const out = new Uint8Array(numBytes)
for (let i = 0; i < numBytes; i++) {
out[(numBytes - 1 - i) as number] = (n >> (8 * i)) & 0xff
}
return out
}
/* Example usages of 'decode_number' are shown below:
decode_number(header, bits_header);
*/
function decode_number(a, bits) {
if (!(bits > 0 && bits <= 32)) {
throw new Error('only supports 32-bit encoding')
}
const numBytes = Math.ceil(bits / 8)
if (a.length !== numBytes) {
throw new Error('array has wrong size')
}
let out = 0
for (let i = 0; i < a.length; i++) {
out <<= 8
out += a[i as number]
}
return out
}
/* Example usages of 'encode_vector' are shown below:
encode_vector(a, 8);
encode_vector(a, 16);
*/
function encode_vector(a, bits_header) {
return joinAll([encode_number(a.length, bits_header), a])
}
/* Example usages of 'decode_vector' are shown below:
decode_vector(a, 16);
*/
function decode_vector(
a,
bits_header
) {
if (a.length === 0) {
throw new Error('empty vector not allowed')
}
const numBytes = Math.ceil(bits_header / 8)
const header = a.subarray(0, numBytes)
const len = decode_number(header, bits_header)
const consumed = numBytes + len
const payload = a.slice(numBytes, consumed)
return { payload, consumed }
}
export function encode_vector_8(a) {
return encode_vector(a, 8)
}
export function encode_vector_16(a) {
return encode_vector(a, 16)
}
export function decode_vector_16(a) {
return decode_vector(a, 16)
}
export /* Example usages of 'checked_vector' are shown below:
checked_vector(Uint8Array.from(a), n, str);
*/
function checked_vector(a, n, str = 'array') {
if (a.length < n) {
throw new Error(`${str} has wrong length`)
}
return a.slice(0, n)
}
export function checked_vector_array(a, n, str = 'array') {
return checked_vector(Uint8Array.from(a), n, str)
}
export function xor(a, b) {
if (a.length !== b.length || a.length === 0) {
throw new Error('arrays of different length')
}
const n = a.length
const c = new Uint8Array(n)
for (let i = 0; i < n; i++) {
c[i as number] = a[i as number] ^ b[i as number]
}
return c
}
export function ctEqual(a, b) {
if (a.length !== b.length || a.length === 0) {
throw new Error('arrays of different length')
}
const n = a.length
let c = 0
for (let i = 0; i < n; i++) {
c |= a[i as number] ^ b[i as number]
}
return c === 0
}
|
3537e5e308e2d77a22037546084b7446fe0029ed | 1,311 | ts | TypeScript | sort-an-array/index.ts | masx200/leetcode-test | bec83c7bc30fe3387a19bf8ae0c8685ed0aba2f4 | [
"MulanPSL-1.0"
] | 1 | 2022-03-30T11:10:14.000Z | 2022-03-30T11:10:14.000Z | sort-an-array/index.ts | masx200/leetcode-test | bec83c7bc30fe3387a19bf8ae0c8685ed0aba2f4 | [
"MulanPSL-1.0"
] | null | null | null | sort-an-array/index.ts | masx200/leetcode-test | bec83c7bc30fe3387a19bf8ae0c8685ed0aba2f4 | [
"MulanPSL-1.0"
] | null | null | null | export default function sortArray(nums: number[]): number[] {
0 < nums.length - 1 && mergeSort(nums, 0, nums.length - 1);
return nums;
}
function mergeSort(nums: number[], left: number, right: number) {
if (left < right) {
const middle = Math.floor((left + right) / 2);
left < middle && mergeSort(nums, left, middle);
middle + 1 < right && mergeSort(nums, middle + 1, right);
mergeArray(nums, left, middle, middle + 1, right);
}
}
function mergeArray(
nums: number[],
left1: number,
right1: number,
left2: number,
right2: number,
) {
const temp: number[] = Array(right2 - left2 + right1 - left1 + 2);
let p1 = left1;
let p2 = left2;
let t1 = 0;
while (p1 <= right1 && p2 <= right2) {
if (nums[p1] <= nums[p2]) {
temp[t1] = nums[p1];
t1++;
p1++;
} else {
temp[t1] = nums[p2];
t1++;
p2++;
}
}
while (p1 <= right1) {
temp[t1] = nums[p1];
t1++;
p1++;
}
while (p2 <= right2) {
temp[t1] = nums[p2];
t1++;
p2++;
}
let t2 = 0;
let p3 = left1;
while (p3 <= right2) {
nums[p3] = temp[t2];
p3++;
t2++;
}
}
| 17.025974 | 70 | 0.46148 | 52 | 3 | 0 | 9 | 7 | 0 | 2 | 0 | 11 | 0 | 0 | 13.333333 | 423 | 0.028369 | 0.016548 | 0 | 0 | 0 | 0 | 0.578947 | 0.290294 | export default function sortArray(nums) {
0 < nums.length - 1 && mergeSort(nums, 0, nums.length - 1);
return nums;
}
/* Example usages of 'mergeSort' are shown below:
0 < nums.length - 1 && mergeSort(nums, 0, nums.length - 1);
left < middle && mergeSort(nums, left, middle);
middle + 1 < right && mergeSort(nums, middle + 1, right);
*/
function mergeSort(nums, left, right) {
if (left < right) {
const middle = Math.floor((left + right) / 2);
left < middle && mergeSort(nums, left, middle);
middle + 1 < right && mergeSort(nums, middle + 1, right);
mergeArray(nums, left, middle, middle + 1, right);
}
}
/* Example usages of 'mergeArray' are shown below:
mergeArray(nums, left, middle, middle + 1, right);
*/
function mergeArray(
nums,
left1,
right1,
left2,
right2,
) {
const temp = Array(right2 - left2 + right1 - left1 + 2);
let p1 = left1;
let p2 = left2;
let t1 = 0;
while (p1 <= right1 && p2 <= right2) {
if (nums[p1] <= nums[p2]) {
temp[t1] = nums[p1];
t1++;
p1++;
} else {
temp[t1] = nums[p2];
t1++;
p2++;
}
}
while (p1 <= right1) {
temp[t1] = nums[p1];
t1++;
p1++;
}
while (p2 <= right2) {
temp[t1] = nums[p2];
t1++;
p2++;
}
let t2 = 0;
let p3 = left1;
while (p3 <= right2) {
nums[p3] = temp[t2];
p3++;
t2++;
}
}
|
35b6c6d6cf43374159e7f7c86517b7faf952db91 | 5,598 | ts | TypeScript | src/target.types/base.ts | Shed-Enterprises/crypto-janitor | 88db52409569960428dbc8d3963bc9eb4db4a6b7 | [
"MIT"
] | 1 | 2022-01-24T23:31:03.000Z | 2022-01-24T23:31:03.000Z | src/target.types/base.ts | Shed-Enterprises/crypto-janitor | 88db52409569960428dbc8d3963bc9eb4db4a6b7 | [
"MIT"
] | null | null | null | src/target.types/base.ts | Shed-Enterprises/crypto-janitor | 88db52409569960428dbc8d3963bc9eb4db4a6b7 | [
"MIT"
] | 1 | 2022-03-15T23:03:13.000Z | 2022-03-15T23:03:13.000Z | /* eslint-disable max-len */
// Send, Receive, Deposit, Withdrawal, Income
export interface Transaction {
id: string;
timestamp: Date;
type: string;
baseCurrency: string;
baseQuantity: number;
baseUsdPrice: number;
feeCurrency: string;
feeQuantity: number;
feeUsdPrice: number;
feeTotal: number;
subTotal: number;
total: number;
}
// Buy, Sell, Swap
export interface Order {
id: string;
timestamp: Date;
type: string;
baseCurrency: string;
baseQuantity: number;
baseUsdPrice: number;
quoteCurrency: string;
quoteQuantity: number;
quotePrice: number;
quoteUsdPrice: number;
feeCurrency: string;
feeQuantity: number;
feeUsdPrice: number;
feeTotal: number;
subTotal: number;
total: number;
}
/**
* A base class to support general connection operations
*/
export default class BaseConnection {
name: string;
type: string;
connection: any;
credentials?: any;
balances: any;
symbols: Array<any>;
initialized: boolean;
requireSymbols: boolean;
requireUsdValuation: boolean;
stableCoins: Array<string> = ["USDC", "USDT"];
fiatCurrencies: Array<string> = ["USD"];
stableCurrencies: Array<string> = ["USD", "USDC", "USDT"];
/**
* Create BaseConnection instance
* @param {string} name - Name of connection (Ex: coinbase)
* @param {string} type - Type of connection (Ex: api)
* @param {any} params - (Optional) Additional paramaters
*/
constructor(name: string, type: string, params: any = {}) {
this.name = name;
this.type = type;
this.connection = null;
this.initialized = false;
this.symbols = [];
this.requireSymbols = params.requireSymbols
? params.requireSymbols
: false;
this.requireUsdValuation = params.requireUsdValuation
? params.requireUsdValuation
: true;
}
/**
* JSON object representing connection
* @return {any}
*/
toJSON(): any {
const baseJSON = {
name: this.name,
type: this.type,
params: {},
};
if (this.credentials) {
const updatedParams: any = baseJSON.params;
updatedParams.credentials = this.credentials;
baseJSON.params = updatedParams;
}
return baseJSON;
}
/**
* HELPER: Convert buy/sell to swap if no fiat is involved in order
*
* @param {any} order - Order instance
* @return {Order} Reformatted Order
*/
_attemptedSwapConversion(order: Order): Order {
if (!this.fiatCurrencies.includes(order.quoteCurrency)) {
if (order.type === "sell") {
const tempBC = order.baseCurrency;
const tempBQ = order.baseQuantity;
const tempBP = order.baseUsdPrice;
order.baseCurrency = order.quoteCurrency;
order.baseQuantity = order.quoteQuantity;
order.baseUsdPrice = order.quoteUsdPrice;
order.quoteCurrency = tempBC;
order.quoteQuantity = tempBQ;
order.quoteUsdPrice = tempBP;
order.quotePrice = order.baseUsdPrice / order.quoteUsdPrice;
}
order.type = "swap";
}
return order;
}
/**
* Initialize exchange by fetching balances and loading markets
* @return {void}
*/
initialize(): void {
throw Error(
`NotImplementedError: ${this.name}.initialize() has not been implemented.`
);
}
/**
* Fetch Account Balances
* @return {void}
*/
getBalances(): void {
throw Error(
`NotImplementedError: ${this.name}.getBalances() has not been implemented.`
);
}
/**
* Fetch Account Withdrawals
* @return {void}
*/
getWithdrawals(): void {
throw Error(
`NotImplementedError: ${this.name}.getWithdrawals() has not been implemented.`
);
}
/**
* Fetch Account Deposits
* @return {void}
*/
getDeposits(): void {
throw Error(
`NotImplementedError: ${this.name}.getDeposits() has not been implemented.`
);
}
/**
* Fetch Account Orders
* @return {void}
*/
getOrders(): void {
throw Error(
`NotImplementedError: ${this.name}.getOrders() has not been implemented.`
);
}
/**
* Fetch all account ledger (withdrawals, deposits, and orders)
* @return {void}
*/
getLedger(): void {
throw Error(
`NotImplementedError: ${this.name}.getLedger() has not been implemented.`
);
}
/**
* Fetch account transactions (withdrawals, deposits, and orders)
* @return {void}
*/
getTransactions(): void {
throw Error(
`NotImplementedError: ${this.name}.getTransactions() has not been implemented.`
);
}
/**
* Fetch all account transactions (withdrawals, deposits, and orders)
* @return {void}
*/
getAllTransactions(): void {
throw Error(
`NotImplementedError: ${this.name}.getAllTransactions() has not been implemented.`
);
}
/**
* Fetch all account transactions (withdrawals, deposits, and orders)
* @return {void}
*/
getTxUsdVal(): void {
throw Error(
`NotImplementedError: ${this.name}.getTxUsdVal() has not been implemented.`
);
}
}
| 26.913462 | 94 | 0.574848 | 135 | 12 | 0 | 4 | 5 | 40 | 0 | 7 | 45 | 3 | 0 | 5.416667 | 1,308 | 0.012232 | 0.003823 | 0.030581 | 0.002294 | 0 | 0.114754 | 0.737705 | 0.212055 | /* eslint-disable max-len */
// Send, Receive, Deposit, Withdrawal, Income
export interface Transaction {
id;
timestamp;
type;
baseCurrency;
baseQuantity;
baseUsdPrice;
feeCurrency;
feeQuantity;
feeUsdPrice;
feeTotal;
subTotal;
total;
}
// Buy, Sell, Swap
export interface Order {
id;
timestamp;
type;
baseCurrency;
baseQuantity;
baseUsdPrice;
quoteCurrency;
quoteQuantity;
quotePrice;
quoteUsdPrice;
feeCurrency;
feeQuantity;
feeUsdPrice;
feeTotal;
subTotal;
total;
}
/**
* A base class to support general connection operations
*/
export default class BaseConnection {
name;
type;
connection;
credentials?;
balances;
symbols;
initialized;
requireSymbols;
requireUsdValuation;
stableCoins = ["USDC", "USDT"];
fiatCurrencies = ["USD"];
stableCurrencies = ["USD", "USDC", "USDT"];
/**
* Create BaseConnection instance
* @param {string} name - Name of connection (Ex: coinbase)
* @param {string} type - Type of connection (Ex: api)
* @param {any} params - (Optional) Additional paramaters
*/
constructor(name, type, params = {}) {
this.name = name;
this.type = type;
this.connection = null;
this.initialized = false;
this.symbols = [];
this.requireSymbols = params.requireSymbols
? params.requireSymbols
: false;
this.requireUsdValuation = params.requireUsdValuation
? params.requireUsdValuation
: true;
}
/**
* JSON object representing connection
* @return {any}
*/
toJSON() {
const baseJSON = {
name: this.name,
type: this.type,
params: {},
};
if (this.credentials) {
const updatedParams = baseJSON.params;
updatedParams.credentials = this.credentials;
baseJSON.params = updatedParams;
}
return baseJSON;
}
/**
* HELPER: Convert buy/sell to swap if no fiat is involved in order
*
* @param {any} order - Order instance
* @return {Order} Reformatted Order
*/
_attemptedSwapConversion(order) {
if (!this.fiatCurrencies.includes(order.quoteCurrency)) {
if (order.type === "sell") {
const tempBC = order.baseCurrency;
const tempBQ = order.baseQuantity;
const tempBP = order.baseUsdPrice;
order.baseCurrency = order.quoteCurrency;
order.baseQuantity = order.quoteQuantity;
order.baseUsdPrice = order.quoteUsdPrice;
order.quoteCurrency = tempBC;
order.quoteQuantity = tempBQ;
order.quoteUsdPrice = tempBP;
order.quotePrice = order.baseUsdPrice / order.quoteUsdPrice;
}
order.type = "swap";
}
return order;
}
/**
* Initialize exchange by fetching balances and loading markets
* @return {void}
*/
initialize() {
throw Error(
`NotImplementedError: ${this.name}.initialize() has not been implemented.`
);
}
/**
* Fetch Account Balances
* @return {void}
*/
getBalances() {
throw Error(
`NotImplementedError: ${this.name}.getBalances() has not been implemented.`
);
}
/**
* Fetch Account Withdrawals
* @return {void}
*/
getWithdrawals() {
throw Error(
`NotImplementedError: ${this.name}.getWithdrawals() has not been implemented.`
);
}
/**
* Fetch Account Deposits
* @return {void}
*/
getDeposits() {
throw Error(
`NotImplementedError: ${this.name}.getDeposits() has not been implemented.`
);
}
/**
* Fetch Account Orders
* @return {void}
*/
getOrders() {
throw Error(
`NotImplementedError: ${this.name}.getOrders() has not been implemented.`
);
}
/**
* Fetch all account ledger (withdrawals, deposits, and orders)
* @return {void}
*/
getLedger() {
throw Error(
`NotImplementedError: ${this.name}.getLedger() has not been implemented.`
);
}
/**
* Fetch account transactions (withdrawals, deposits, and orders)
* @return {void}
*/
getTransactions() {
throw Error(
`NotImplementedError: ${this.name}.getTransactions() has not been implemented.`
);
}
/**
* Fetch all account transactions (withdrawals, deposits, and orders)
* @return {void}
*/
getAllTransactions() {
throw Error(
`NotImplementedError: ${this.name}.getAllTransactions() has not been implemented.`
);
}
/**
* Fetch all account transactions (withdrawals, deposits, and orders)
* @return {void}
*/
getTxUsdVal() {
throw Error(
`NotImplementedError: ${this.name}.getTxUsdVal() has not been implemented.`
);
}
}
|
35e572f65979baae0294e407938408f0f4aefde3 | 1,882 | ts | TypeScript | problemset/maximum-gap/index.ts | OUDUIDUI/leet-code | 50e61ce16d1c419ccefc075ae9ead721cdd1cdbb | [
"MIT"
] | 6 | 2022-01-17T03:19:56.000Z | 2022-01-17T05:45:39.000Z | problemset/maximum-gap/index.ts | OUDUIDUI/leet-code | 50e61ce16d1c419ccefc075ae9ead721cdd1cdbb | [
"MIT"
] | null | null | null | problemset/maximum-gap/index.ts | OUDUIDUI/leet-code | 50e61ce16d1c419ccefc075ae9ead721cdd1cdbb | [
"MIT"
] | null | null | null | /**
* 基数排序
* @desc 时间复杂度 O(N) 空间复杂度 O(N)
* @param nums
*/
export function maximumGap(nums: number[]): number {
const len = nums.length
if (len <= 2) return nums[len - 1] - nums[0]
const maxVal = Math.max(...nums)
const buckets: number[][] = []
let m = 1
while (m <= maxVal) {
// 清空桶
buckets.length = 0
for (const num of nums) {
const d = ~~((num % (m * 10)) / m)
if (!buckets[d])
buckets[d] = []
buckets[d].push(num)
}
nums = []
for (let i = 0; i < buckets.length; i++)
buckets[i] && nums.push(...buckets[i])
m *= 10
}
let ret = 0
for (let i = 1; i < len; i++)
ret = Math.max(ret, nums[i] - nums[i - 1])
return ret
}
/**
* 基于桶的算法
* @desc 时间复杂度 O(N) 空间复杂度 O(N)
* @param nums
*/
export function maximumGap2(nums: number[]): number {
const len = nums.length
if (len <= 2) return nums[len - 1] - nums[0]
// 找到最大值和最小值
const maxVal = Math.max(...nums)
const minVal = Math.min(...nums)
// 求出每个桶可装的数量,确保每个桶内按序差值不超过平均差值
const d = Math.max(1, Math.floor(maxVal - minVal) / (len - 1))
// 算出桶的数量
const bucketSize = Math.floor((maxVal - minVal) / d) + 1
// 初始化桶,每个桶维护这一个最小值和最大值
const buckets: [number, number][] = new Array(bucketSize)
.fill([])
.map(() => new Array(2).fill(-1) as [number, number])
for (let i = 0; i < len; i++) {
// 求出该数应该放置的桶
const idx = Math.floor((nums[i] - minVal) / d)
if (buckets[idx][0] === -1) {
buckets[idx][0] = buckets[idx][1] = nums[i]
}
else {
buckets[idx][0] = Math.min(buckets[idx][0], nums[i])
buckets[idx][1] = Math.max(buckets[idx][1], nums[i])
}
}
let ret = 0
let prev = -1
for (let i = 0; i < bucketSize; i++) {
if (buckets[i][0] === -1) continue
if (prev !== -1)
ret = Math.max(buckets[i][0] - buckets[prev][1], ret)
prev = i
}
return ret
}
| 21.632184 | 64 | 0.536132 | 54 | 3 | 0 | 2 | 19 | 0 | 0 | 0 | 9 | 0 | 1 | 17 | 751 | 0.006658 | 0.0253 | 0 | 0 | 0.001332 | 0 | 0.375 | 0.267635 | /**
* 基数排序
* @desc 时间复杂度 O(N) 空间复杂度 O(N)
* @param nums
*/
export function maximumGap(nums) {
const len = nums.length
if (len <= 2) return nums[len - 1] - nums[0]
const maxVal = Math.max(...nums)
const buckets = []
let m = 1
while (m <= maxVal) {
// 清空桶
buckets.length = 0
for (const num of nums) {
const d = ~~((num % (m * 10)) / m)
if (!buckets[d])
buckets[d] = []
buckets[d].push(num)
}
nums = []
for (let i = 0; i < buckets.length; i++)
buckets[i] && nums.push(...buckets[i])
m *= 10
}
let ret = 0
for (let i = 1; i < len; i++)
ret = Math.max(ret, nums[i] - nums[i - 1])
return ret
}
/**
* 基于桶的算法
* @desc 时间复杂度 O(N) 空间复杂度 O(N)
* @param nums
*/
export function maximumGap2(nums) {
const len = nums.length
if (len <= 2) return nums[len - 1] - nums[0]
// 找到最大值和最小值
const maxVal = Math.max(...nums)
const minVal = Math.min(...nums)
// 求出每个桶可装的数量,确保每个桶内按序差值不超过平均差值
const d = Math.max(1, Math.floor(maxVal - minVal) / (len - 1))
// 算出桶的数量
const bucketSize = Math.floor((maxVal - minVal) / d) + 1
// 初始化桶,每个桶维护这一个最小值和最大值
const buckets = new Array(bucketSize)
.fill([])
.map(() => new Array(2).fill(-1) as [number, number])
for (let i = 0; i < len; i++) {
// 求出该数应该放置的桶
const idx = Math.floor((nums[i] - minVal) / d)
if (buckets[idx][0] === -1) {
buckets[idx][0] = buckets[idx][1] = nums[i]
}
else {
buckets[idx][0] = Math.min(buckets[idx][0], nums[i])
buckets[idx][1] = Math.max(buckets[idx][1], nums[i])
}
}
let ret = 0
let prev = -1
for (let i = 0; i < bucketSize; i++) {
if (buckets[i][0] === -1) continue
if (prev !== -1)
ret = Math.max(buckets[i][0] - buckets[prev][1], ret)
prev = i
}
return ret
}
|
1d39ec473347edb072e37f629ad2a9736fad5a7a | 2,667 | ts | TypeScript | src/models/ResponseAuthorization.ts | api-client/core | aa157d09b39efa77d49f2d425e7b37828abe0c5b | [
"Apache-2.0"
] | null | null | null | src/models/ResponseAuthorization.ts | api-client/core | aa157d09b39efa77d49f2d425e7b37828abe0c5b | [
"Apache-2.0"
] | 1 | 2022-02-14T00:01:04.000Z | 2022-02-14T00:04:07.000Z | src/models/ResponseAuthorization.ts | advanced-rest-client/core | 2efb946f786d8b46e7131c62e0011f6e090ddec3 | [
"Apache-2.0"
] | null | null | null | export const Kind = 'Core#ResponseAuthorization';
export interface IResponseAuthorization {
kind: typeof Kind;
/**
* The requested by the authorization server authentication method
*/
method: string;
/**
* The current state if the authorization process. This is used by NTLM authorization helper.
*/
state?: number;
/**
* The headers association with the response.
*/
headers?: string;
/**
* When returned by the server, the value of the challenge.
*/
challengeHeader?: string;
}
export class ResponseAuthorization {
kind = Kind;
/**
* The requested by the authorization server authentication method
*/
method = 'unknown';
/**
* The current state if the authorization process. This is used by NTLM authorization helper.
*/
state?: number;
/**
* The headers association with the response.
*/
headers?: string;
/**
* When returned by the server, the value of the challenge.
*/
challengeHeader?: string;
/**
* @param input The response authorization definition used to restore the state.
*/
constructor(input?: string|IResponseAuthorization) {
let init: IResponseAuthorization;
if (typeof input === 'string') {
init = JSON.parse(input);
} else if (typeof input === 'object') {
init = input;
} else {
init = {
kind: Kind,
method: 'unknown',
};
}
this.new(init);
}
/**
* Creates a new response authorization clearing anything that is so far defined.
*
* Note, this throws an error when the object is not a response authorization.
*/
new(init: IResponseAuthorization): void {
if (!ResponseAuthorization.isResponseAuthorization(init)) {
throw new Error(`Not a response authorization.`);
}
const { method, state, headers, challengeHeader } = init;
this.kind = Kind;
this.method = method;
this.state = state;
this.headers = headers;
this.challengeHeader = challengeHeader;
}
/**
* Checks whether the input is a definition of a response authorization.
*/
static isResponseAuthorization(input: unknown): boolean {
const typed = input as IResponseAuthorization;
if (!input || !typed.method) {
return false;
}
return true;
}
toJSON(): IResponseAuthorization {
const result: IResponseAuthorization = {
kind: Kind,
method: this.method,
};
if (typeof this.state === 'number') {
result.state = this.state;
}
if (this.headers) {
result.headers = this.headers;
}
if (this.challengeHeader) {
result.challengeHeader = this.challengeHeader;
}
return result;
}
}
| 25.4 | 95 | 0.646044 | 63 | 4 | 0 | 3 | 5 | 10 | 2 | 0 | 11 | 2 | 4 | 10 | 618 | 0.011327 | 0.008091 | 0.016181 | 0.003236 | 0.006472 | 0 | 0.5 | 0.227092 | export const Kind = 'Core#ResponseAuthorization';
export interface IResponseAuthorization {
kind;
/**
* The requested by the authorization server authentication method
*/
method;
/**
* The current state if the authorization process. This is used by NTLM authorization helper.
*/
state?;
/**
* The headers association with the response.
*/
headers?;
/**
* When returned by the server, the value of the challenge.
*/
challengeHeader?;
}
export class ResponseAuthorization {
kind = Kind;
/**
* The requested by the authorization server authentication method
*/
method = 'unknown';
/**
* The current state if the authorization process. This is used by NTLM authorization helper.
*/
state?;
/**
* The headers association with the response.
*/
headers?;
/**
* When returned by the server, the value of the challenge.
*/
challengeHeader?;
/**
* @param input The response authorization definition used to restore the state.
*/
constructor(input?) {
let init;
if (typeof input === 'string') {
init = JSON.parse(input);
} else if (typeof input === 'object') {
init = input;
} else {
init = {
kind: Kind,
method: 'unknown',
};
}
this.new(init);
}
/**
* Creates a new response authorization clearing anything that is so far defined.
*
* Note, this throws an error when the object is not a response authorization.
*/
new(init) {
if (!ResponseAuthorization.isResponseAuthorization(init)) {
throw new Error(`Not a response authorization.`);
}
const { method, state, headers, challengeHeader } = init;
this.kind = Kind;
this.method = method;
this.state = state;
this.headers = headers;
this.challengeHeader = challengeHeader;
}
/**
* Checks whether the input is a definition of a response authorization.
*/
static isResponseAuthorization(input) {
const typed = input as IResponseAuthorization;
if (!input || !typed.method) {
return false;
}
return true;
}
toJSON() {
const result = {
kind: Kind,
method: this.method,
};
if (typeof this.state === 'number') {
result.state = this.state;
}
if (this.headers) {
result.headers = this.headers;
}
if (this.challengeHeader) {
result.challengeHeader = this.challengeHeader;
}
return result;
}
}
|
1df3b25a9709253afc4423d058219589f9c30b53 | 1,664 | ts | TypeScript | source/dwi/nodejs-assets/nodejs-project/src/idls/xtc.did.ts | fury02/Difiwallet | 7f4417546b0f51aa76901a720d9d64b392b13452 | [
"MIT"
] | 18 | 2022-01-21T07:50:36.000Z | 2022-01-26T16:33:22.000Z | source/dwi/nodejs-assets/nodejs-project/src/idls/xtc.did.ts | fury02/Difiwallet | 7f4417546b0f51aa76901a720d9d64b392b13452 | [
"MIT"
] | null | null | null | source/dwi/nodejs-assets/nodejs-project/src/idls/xtc.did.ts | fury02/Difiwallet | 7f4417546b0f51aa76901a720d9d64b392b13452 | [
"MIT"
] | null | null | null | /* eslint-disable @typescript-eslint/camelcase */
export default ({ IDL }) => {
const TransactionId = IDL.Nat64;
const BurnError = IDL.Variant({
InsufficientBalance: IDL.Null,
InvalidTokenContract: IDL.Null,
NotSufficientLiquidity: IDL.Null,
});
const TxReceipt = IDL.Variant({
Err: IDL.Variant({
InsufficientAllowance: IDL.Null,
InsufficientBalance: IDL.Null,
}),
Ok: IDL.Nat,
});
const BurnResult = IDL.Variant({
Ok: TransactionId,
Err: BurnError,
});
const TokenMetaData = IDL.Record({
features: IDL.Vec(IDL.Text),
name: IDL.Text,
decimal: IDL.Nat8,
symbol: IDL.Text,
});
const NotifyArgs = IDL.Record({
canister_id: IDL.Principal,
method_name: IDL.Text,
});
const TransferError = IDL.Variant({
CallFailed: IDL.Null,
InsufficientBalance: IDL.Null,
Unknown: IDL.Null,
AmountTooLarge: IDL.Null,
});
const TransferResult = IDL.Variant({
Ok: TransactionId,
Err: TransferError,
});
return IDL.Service({
meta: IDL.Func([], [TokenMetaData], ['query']),
meta_certified: IDL.Func([], [TokenMetaData], []),
balance: IDL.Func([IDL.Opt(IDL.Principal)], [IDL.Nat64], []),
burn: IDL.Func(
[IDL.Record({ canister_id: IDL.Principal, amount: IDL.Nat64 })],
[BurnResult],
[]
),
transfer: IDL.Func(
[
IDL.Record({
to: IDL.Principal,
from: IDL.Opt(IDL.Principal),
amount: IDL.Nat64,
}),
],
[TransferResult],
[]
),
transferErc20: IDL.Func([IDL.Principal, IDL.Nat], [TxReceipt], []),
});
};
export const init = () => {
return [];
};
| 24.470588 | 71 | 0.598558 | 64 | 2 | 0 | 1 | 9 | 0 | 0 | 0 | 0 | 0 | 0 | 30 | 517 | 0.005803 | 0.017408 | 0 | 0 | 0 | 0 | 0 | 0.240587 | /* eslint-disable @typescript-eslint/camelcase */
export default ({ IDL }) => {
const TransactionId = IDL.Nat64;
const BurnError = IDL.Variant({
InsufficientBalance: IDL.Null,
InvalidTokenContract: IDL.Null,
NotSufficientLiquidity: IDL.Null,
});
const TxReceipt = IDL.Variant({
Err: IDL.Variant({
InsufficientAllowance: IDL.Null,
InsufficientBalance: IDL.Null,
}),
Ok: IDL.Nat,
});
const BurnResult = IDL.Variant({
Ok: TransactionId,
Err: BurnError,
});
const TokenMetaData = IDL.Record({
features: IDL.Vec(IDL.Text),
name: IDL.Text,
decimal: IDL.Nat8,
symbol: IDL.Text,
});
const NotifyArgs = IDL.Record({
canister_id: IDL.Principal,
method_name: IDL.Text,
});
const TransferError = IDL.Variant({
CallFailed: IDL.Null,
InsufficientBalance: IDL.Null,
Unknown: IDL.Null,
AmountTooLarge: IDL.Null,
});
const TransferResult = IDL.Variant({
Ok: TransactionId,
Err: TransferError,
});
return IDL.Service({
meta: IDL.Func([], [TokenMetaData], ['query']),
meta_certified: IDL.Func([], [TokenMetaData], []),
balance: IDL.Func([IDL.Opt(IDL.Principal)], [IDL.Nat64], []),
burn: IDL.Func(
[IDL.Record({ canister_id: IDL.Principal, amount: IDL.Nat64 })],
[BurnResult],
[]
),
transfer: IDL.Func(
[
IDL.Record({
to: IDL.Principal,
from: IDL.Opt(IDL.Principal),
amount: IDL.Nat64,
}),
],
[TransferResult],
[]
),
transferErc20: IDL.Func([IDL.Principal, IDL.Nat], [TxReceipt], []),
});
};
export const init = () => {
return [];
};
|
192505c797571e60e9a59b0117aeef817a986c30 | 4,500 | ts | TypeScript | src/util.ts | Mercerenies/pan-unicode-lang | d5c283a591c0e8cfbd57b97ebd75dc4f362b1bd6 | [
"MIT"
] | null | null | null | src/util.ts | Mercerenies/pan-unicode-lang | d5c283a591c0e8cfbd57b97ebd75dc4f362b1bd6 | [
"MIT"
] | 14 | 2022-01-24T04:16:30.000Z | 2022-02-06T01:17:26.000Z | src/util.ts | Mercerenies/pan-unicode-lang | d5c283a591c0e8cfbd57b97ebd75dc4f362b1bd6 | [
"MIT"
] | null | null | null |
// Asserts that the value is of type 'never'. This function will,
// naturally, never actually be called, unless a value is cast to type
// 'never'.
export function assertNever(_x: never): never {
throw "assertNever failed";
}
// Zips the two lists together, returning a list of 2-tuples. The
// resulting list will always have length equal to that of the first
// list and will be padded with undefined as needed.
export function zip<A, B>(a: A[], b: B[]): [A, B][] {
return a.map((v, i) => [v, b[i]]);
}
// Validates that the elements of the two arrays are equal according
// to the given equality predicate. If the arrays have differing
// lengths, returns false unconditionally.
export function arrayEq<A, B>(a: A[], b: B[], fn: (a: A, b: B) => boolean) {
if (a.length !== b.length) {
return false;
}
const ref = zip(a, b);
for (const [x, y] of ref) {
if (!fn(x, y)) {
return false;
}
}
return true;
}
// Inserts sub into str, replacing the characters from index a to
// index b.
export function spliceStr(str: string, sub: string, a: number, b: number): string {
return str.substring(0, a) + sub + str.substring(b);
}
// Mathematical gcd. Returns the gcd of the two numbers.
export function gcd(a: number, b: number): number {
while (b !== 0) {
[a, b] = [b, (a % b + b) % b];
}
return a;
}
// Mathematical lcm. Returns the lcm of the two numbers.
export function lcm(a: number, b: number): number {
const d = gcd(a, b);
if (d === 0) {
return 0;
} else {
return a * b / d;
}
}
// A list of the values from a up to b. If a > b then returns the
// empty list.
export function range(a: number, b: number): number[] {
const x: number[] = [];
for (let i = a; i < b; i++) {
x.push(i);
}
return x;
}
// The built-in sort() doesn't support promises, and in the abstract
// we may be eval'ing user code during a sort function. Even though
// doing so is a Bad Idea(tm), it is technically allowed by our
// implementation, so we implement our own sort here.
//
// Note: Like the built-in sorting function, this sorts in-place; no
// copy is made.
//
// This is the first time in many years I've bothered to write a
// sorting algorithm on my own, amusingly. Using Wikipedia to get a
// nice, stable one:
// https://en.wikipedia.org/wiki/Merge_sort#Algorithm
export async function sortM<T>(arr: T[], compareFn?: (a: T, B: T) => Promise<number>): Promise<T[]> {
const comparison = compareFn ?? defaultCompare;
const tmp: T[] = arr.slice();
const merge = async function(a: T[], b: T[], begin: number, middle: number, end: number): Promise<void> {
let [i, j] = [begin, middle];
for (let k = begin; k < end; k++) {
if (i < middle && (j >= end || (await comparison(a[i], a[j])) <= 0)) {
b[k] = a[i];
i += 1;
} else {
b[k] = a[j];
j += 1;
}
}
};
const splitMerge = async function(a: T[], b: T[], begin: number, end: number): Promise<void> {
if (end - begin <= 1) {
return;
}
const middle = Math.floor((end + begin) / 2);
await splitMerge(b, a, begin, middle);
await splitMerge(b, a, middle, end);
await merge(a, b, begin, middle, end);
};
await splitMerge(tmp, arr, 0, arr.length);
return arr;
}
async function defaultCompare<T>(a: T, b: T): Promise<number> {
const aStr = ""+a;
const bStr = ""+b;
if (aStr < bStr) {
return -1;
} else if (aStr > bStr) {
return 1;
} else {
return 0;
}
}
// As the built-in reduce() function, but takes a promise as the
// reduction callback.
export function reduceM<A>(arr: A[], callback: (prev: A, next: A, index: number, array: A[]) => Promise<A>): Promise<A>;
export function reduceM<A, B>(arr: B[], callback: (prev: A, next: B, index: number, array: B[]) => Promise<A>, initial: A): Promise<A>;
export async function reduceM<A, B>(arr: B[], callback: (prev: A, next: B, index: number, array: B[]) => Promise<A>, ...v: [] | [A]): Promise<A> {
let prev: A;
let index: number;
if (v.length === 0) {
// Get the initial value from the array
if (arr.length === 0) {
throw TypeError("Empty array on reduceM and no initial value supplied.");
} else {
prev = arr[0] as unknown as A; // In this case, we're in the first overload, so A == B
index = 1;
}
} else {
prev = v[0];
index = 0;
}
for (; index < arr.length; index++) {
prev = await callback(prev, arr[index], index, arr);
}
return prev;
}
| 29.220779 | 146 | 0.604889 | 101 | 13 | 2 | 39 | 15 | 0 | 4 | 0 | 32 | 0 | 2 | 7.461538 | 1,445 | 0.035986 | 0.010381 | 0 | 0 | 0.001384 | 0 | 0.463768 | 0.288392 |
// Asserts that the value is of type 'never'. This function will,
// naturally, never actually be called, unless a value is cast to type
// 'never'.
export function assertNever(_x) {
throw "assertNever failed";
}
// Zips the two lists together, returning a list of 2-tuples. The
// resulting list will always have length equal to that of the first
// list and will be padded with undefined as needed.
export /* Example usages of 'zip' are shown below:
zip(a, b);
*/
function zip<A, B>(a, b) {
return a.map((v, i) => [v, b[i]]);
}
// Validates that the elements of the two arrays are equal according
// to the given equality predicate. If the arrays have differing
// lengths, returns false unconditionally.
export function arrayEq<A, B>(a, b, fn) {
if (a.length !== b.length) {
return false;
}
const ref = zip(a, b);
for (const [x, y] of ref) {
if (!fn(x, y)) {
return false;
}
}
return true;
}
// Inserts sub into str, replacing the characters from index a to
// index b.
export function spliceStr(str, sub, a, b) {
return str.substring(0, a) + sub + str.substring(b);
}
// Mathematical gcd. Returns the gcd of the two numbers.
export /* Example usages of 'gcd' are shown below:
gcd(a, b);
*/
function gcd(a, b) {
while (b !== 0) {
[a, b] = [b, (a % b + b) % b];
}
return a;
}
// Mathematical lcm. Returns the lcm of the two numbers.
export function lcm(a, b) {
const d = gcd(a, b);
if (d === 0) {
return 0;
} else {
return a * b / d;
}
}
// A list of the values from a up to b. If a > b then returns the
// empty list.
export function range(a, b) {
const x = [];
for (let i = a; i < b; i++) {
x.push(i);
}
return x;
}
// The built-in sort() doesn't support promises, and in the abstract
// we may be eval'ing user code during a sort function. Even though
// doing so is a Bad Idea(tm), it is technically allowed by our
// implementation, so we implement our own sort here.
//
// Note: Like the built-in sorting function, this sorts in-place; no
// copy is made.
//
// This is the first time in many years I've bothered to write a
// sorting algorithm on my own, amusingly. Using Wikipedia to get a
// nice, stable one:
// https://en.wikipedia.org/wiki/Merge_sort#Algorithm
export async function sortM<T>(arr, compareFn?) {
const comparison = compareFn ?? defaultCompare;
const tmp = arr.slice();
/* Example usages of 'merge' are shown below:
merge(a, b, begin, middle, end);
*/
const merge = async function(a, b, begin, middle, end) {
let [i, j] = [begin, middle];
for (let k = begin; k < end; k++) {
if (i < middle && (j >= end || (await comparison(a[i], a[j])) <= 0)) {
b[k] = a[i];
i += 1;
} else {
b[k] = a[j];
j += 1;
}
}
};
/* Example usages of 'splitMerge' are shown below:
splitMerge(b, a, begin, middle);
splitMerge(b, a, middle, end);
splitMerge(tmp, arr, 0, arr.length);
*/
const splitMerge = async function(a, b, begin, end) {
if (end - begin <= 1) {
return;
}
const middle = Math.floor((end + begin) / 2);
await splitMerge(b, a, begin, middle);
await splitMerge(b, a, middle, end);
await merge(a, b, begin, middle, end);
};
await splitMerge(tmp, arr, 0, arr.length);
return arr;
}
/* Example usages of 'defaultCompare' are shown below:
compareFn ?? defaultCompare;
*/
async function defaultCompare<T>(a, b) {
const aStr = ""+a;
const bStr = ""+b;
if (aStr < bStr) {
return -1;
} else if (aStr > bStr) {
return 1;
} else {
return 0;
}
}
// As the built-in reduce() function, but takes a promise as the
// reduction callback.
export function reduceM<A>(arr, callback);
export function reduceM<A, B>(arr, callback, initial);
export async function reduceM<A, B>(arr, callback, ...v) {
let prev;
let index;
if (v.length === 0) {
// Get the initial value from the array
if (arr.length === 0) {
throw TypeError("Empty array on reduceM and no initial value supplied.");
} else {
prev = arr[0] as unknown as A; // In this case, we're in the first overload, so A == B
index = 1;
}
} else {
prev = v[0];
index = 0;
}
for (; index < arr.length; index++) {
prev = await callback(prev, arr[index], index, arr);
}
return prev;
}
|
1942b6b08f1aea40481f0b76c0f95f441675e192 | 2,974 | ts | TypeScript | src/app/models/platform-api/requests/liquidity-pools/liquidity-pool-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/liquidity-pools/liquidity-pool-filter.ts | Opdex/opdex-v1-ui | 2ece9c2405d6e6b0b1aec342e381d5aad6a2a1e7 | [
"MIT"
] | null | null | null | src/app/models/platform-api/requests/liquidity-pools/liquidity-pool-filter.ts | Opdex/opdex-v1-ui | 2ece9c2405d6e6b0b1aec342e381d5aad6a2a1e7 | [
"MIT"
] | null | null | null | export interface ILiquidityPoolsFilter {
keyword?: string;
tokens?: string[];
liquidityPools?: string[];
markets?: string[];
stakingStatus?: StakingStatus;
miningStatus?: MiningStatus;
nominationStatus?: NominationStatus;
orderBy?: LpOrderBy;
limit?: number;
direction?: string;
cursor?: string
}
export enum StakingStatus {
Any = 'Any',
Enabled = 'Enabled',
Disabled = 'Disabled'
}
export enum MiningStatus {
Any = 'Any',
Enabled = 'Enabled',
Disabled = 'Disabled'
}
export enum NominationStatus {
Any = 'Any',
Nominated = 'Nominated',
Excluded = 'Excluded'
}
export enum LpOrderBy {
Default = 'Default',
Liquidity = 'Liquidity',
Volume = 'Volume',
StakingWeight = 'StakingWeight'
}
export class LiquidityPoolsFilter implements ILiquidityPoolsFilter {
keyword: string;
tokens?: string[];
liquidityPools?: string[];
markets?: string[];
stakingStatus?: StakingStatus;
miningStatus?: MiningStatus;
nominationStatus?: NominationStatus;
orderBy?: LpOrderBy;
limit?: number;
direction?: string;
cursor?: string
constructor(filter: ILiquidityPoolsFilter) {
if (filter === null || filter === undefined) {
this.limit = 5;
this.direction = 'DESC';
return;
};
this.keyword = filter.keyword;
this.tokens = filter.tokens || [];
this.markets = filter.markets || [];
this.liquidityPools = filter.liquidityPools || [];
this.stakingStatus = filter.stakingStatus;
this.miningStatus = filter.miningStatus;
this.nominationStatus = filter.nominationStatus;
this.orderBy = filter.orderBy;
this.limit = filter.limit;
this.direction = filter.direction;
this.cursor = filter.cursor;
}
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.liquidityPools?.length > 0) {
this.liquidityPools.forEach(contract => query = this.addToQuery(query, 'liquidityPools', contract));
}
if (this.markets?.length > 0) {
this.markets.forEach(contract => query = this.addToQuery(query, 'markets', contract));
}
query = this.addToQuery(query, 'keyword', this.keyword);
query = this.addToQuery(query, 'stakingStatus', this.stakingStatus);
query = this.addToQuery(query, 'miningStatus', this.miningStatus);
query = this.addToQuery(query, 'nominationStatus', this.nominationStatus);
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.284404 | 106 | 0.669469 | 91 | 6 | 0 | 7 | 2 | 22 | 1 | 0 | 20 | 2 | 0 | 6.833333 | 797 | 0.016311 | 0.002509 | 0.027604 | 0.002509 | 0 | 0 | 0.540541 | 0.22 | export interface ILiquidityPoolsFilter {
keyword?;
tokens?;
liquidityPools?;
markets?;
stakingStatus?;
miningStatus?;
nominationStatus?;
orderBy?;
limit?;
direction?;
cursor?
}
export enum StakingStatus {
Any = 'Any',
Enabled = 'Enabled',
Disabled = 'Disabled'
}
export enum MiningStatus {
Any = 'Any',
Enabled = 'Enabled',
Disabled = 'Disabled'
}
export enum NominationStatus {
Any = 'Any',
Nominated = 'Nominated',
Excluded = 'Excluded'
}
export enum LpOrderBy {
Default = 'Default',
Liquidity = 'Liquidity',
Volume = 'Volume',
StakingWeight = 'StakingWeight'
}
export class LiquidityPoolsFilter implements ILiquidityPoolsFilter {
keyword;
tokens?;
liquidityPools?;
markets?;
stakingStatus?;
miningStatus?;
nominationStatus?;
orderBy?;
limit?;
direction?;
cursor?
constructor(filter) {
if (filter === null || filter === undefined) {
this.limit = 5;
this.direction = 'DESC';
return;
};
this.keyword = filter.keyword;
this.tokens = filter.tokens || [];
this.markets = filter.markets || [];
this.liquidityPools = filter.liquidityPools || [];
this.stakingStatus = filter.stakingStatus;
this.miningStatus = filter.miningStatus;
this.nominationStatus = filter.nominationStatus;
this.orderBy = filter.orderBy;
this.limit = filter.limit;
this.direction = filter.direction;
this.cursor = filter.cursor;
}
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.liquidityPools?.length > 0) {
this.liquidityPools.forEach(contract => query = this.addToQuery(query, 'liquidityPools', contract));
}
if (this.markets?.length > 0) {
this.markets.forEach(contract => query = this.addToQuery(query, 'markets', contract));
}
query = this.addToQuery(query, 'keyword', this.keyword);
query = this.addToQuery(query, 'stakingStatus', this.stakingStatus);
query = this.addToQuery(query, 'miningStatus', this.miningStatus);
query = this.addToQuery(query, 'nominationStatus', this.nominationStatus);
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}`;
}
}
|
196eddfafd2d46c55f2c0ee864b90bcea2e010a9 | 2,767 | ts | TypeScript | dk/utils/data/number.ts | cabinet-fe/fe-dk | 4d5567801392cbb018bc3b11051ddca3a86a5852 | [
"MIT"
] | 2 | 2022-03-07T08:03:45.000Z | 2022-03-07T08:05:10.000Z | dk/utils/data/number.ts | cabinet-fe/fe-dk | 4d5567801392cbb018bc3b11051ddca3a86a5852 | [
"MIT"
] | 8 | 2022-03-04T01:41:51.000Z | 2022-03-25T07:44:47.000Z | dk/utils/data/number.ts | cabinet-fe/fe-dk | 4d5567801392cbb018bc3b11051ddca3a86a5852 | [
"MIT"
] | null | null | null | type FormatType = 'money' | 'cn_money'
class Num {
private v!: number
private static numberFmt = new Intl.NumberFormat('zh-Hans-CN', {
maximumFractionDigits: 2
})
private money(money: number, decimal?: number) {
if (!money) return '0'
let [intPart, decPart = ''] = String(money).split('.')
const len = intPart.length - 1
let arr: string[] = []
intPart
.split('')
.reverse()
.forEach((item: string, index: number) => {
arr.push(item)
if (index && (index + 1) % 3 === 0 && index !== len) {
arr.push(',')
}
})
let result = arr.reverse().join('')
if(decimal) {
decPart = decPart?.substring(0, decimal)
result = `${result}.${decPart.padEnd(decimal, '0')}`
}else {
decPart ? result = `${result}.${decPart}` : void 0
}
return result
}
private cn_money(money: number) {
const CN_NUMS = ['零', '壹', '贰', '叁', '肆', '伍', '陆', '柒', '捌', '玖']
const CN_INT_RADICE = ['', '拾', '佰', '仟']
const CN_INT_UNITS = ['', '万', '亿', '兆']
const CN_DEC_UNITS = ['角', '分', '毫', '厘']
let result = ''
if (!money) return '零元整'
if (money >= 999999999999999.9999) return ''
const [intPart, decPart] = String(+money.toFixed(4)).split('.')
if (parseInt(intPart, 10) > 0) {
let count = 0
const IntLen = intPart.length
for (let i = 0; i < IntLen; i++) {
let n = intPart.substring(i, i + 1)
let p = IntLen - i - 1
let q = p / 4
let m = p % 4
if (n === '0') {
count++
} else {
if (count > 0) {
result += CN_NUMS[0]
}
count = 0
result += CN_NUMS[parseInt(n)] + CN_INT_RADICE[m]
}
if (m === 0 && count < 4) {
result += CN_INT_UNITS[q]
}
}
result = `${result}元`
}
if (decPart) {
const decLen = decPart.length
for (let i = 0; i < decLen; i++) {
let n = decPart.substring(i, i + 1)
if (n !== '0') result += CN_NUMS[Number(n)] + CN_DEC_UNITS[i]
}
} else {
result = `${result}整`
}
return result
}
constructor(n: number) {
this.v = n
}
/**
* 将数字格式化
* @param type 格式化类型
* @param decimal 小数位数
*/
format(type: FormatType, decimal?: number) {
return this[type](this.v, decimal)
}
/**
* 指定数字最大保留几位小数点
* @param n 位数
*/
fixed(n: number) {
const { v } = this
return +v.toFixed(n)
}
/**
* 遍历数字
*/
each(fn: (n: number) => void) {
const { v } = this
for(let i = 1; i <= v; i++) {
fn(i)
}
}
}
interface N {
(n: number): Num
}
/**
* 包裹一个数字以方便
* @param n 数字
*/
export const n = <N>function n(n: number) {
return new Num(n)
}
| 22.680328 | 70 | 0.488616 | 95 | 8 | 0 | 11 | 24 | 2 | 0 | 0 | 14 | 3 | 0 | 9.375 | 972 | 0.019547 | 0.024691 | 0.002058 | 0.003086 | 0 | 0 | 0.311111 | 0.30105 | type FormatType = 'money' | 'cn_money'
class Num {
private v!
private static numberFmt = new Intl.NumberFormat('zh-Hans-CN', {
maximumFractionDigits: 2
})
private money(money, decimal?) {
if (!money) return '0'
let [intPart, decPart = ''] = String(money).split('.')
const len = intPart.length - 1
let arr = []
intPart
.split('')
.reverse()
.forEach((item, index) => {
arr.push(item)
if (index && (index + 1) % 3 === 0 && index !== len) {
arr.push(',')
}
})
let result = arr.reverse().join('')
if(decimal) {
decPart = decPart?.substring(0, decimal)
result = `${result}.${decPart.padEnd(decimal, '0')}`
}else {
decPart ? result = `${result}.${decPart}` : void 0
}
return result
}
private cn_money(money) {
const CN_NUMS = ['零', '壹', '贰', '叁', '肆', '伍', '陆', '柒', '捌', '玖']
const CN_INT_RADICE = ['', '拾', '佰', '仟']
const CN_INT_UNITS = ['', '万', '亿', '兆']
const CN_DEC_UNITS = ['角', '分', '毫', '厘']
let result = ''
if (!money) return '零元整'
if (money >= 999999999999999.9999) return ''
const [intPart, decPart] = String(+money.toFixed(4)).split('.')
if (parseInt(intPart, 10) > 0) {
let count = 0
const IntLen = intPart.length
for (let i = 0; i < IntLen; i++) {
let n = intPart.substring(i, i + 1)
let p = IntLen - i - 1
let q = p / 4
let m = p % 4
if (n === '0') {
count++
} else {
if (count > 0) {
result += CN_NUMS[0]
}
count = 0
result += CN_NUMS[parseInt(n)] + CN_INT_RADICE[m]
}
if (m === 0 && count < 4) {
result += CN_INT_UNITS[q]
}
}
result = `${result}元`
}
if (decPart) {
const decLen = decPart.length
for (let i = 0; i < decLen; i++) {
let n = decPart.substring(i, i + 1)
if (n !== '0') result += CN_NUMS[Number(n)] + CN_DEC_UNITS[i]
}
} else {
result = `${result}整`
}
return result
}
constructor(n) {
this.v = n
}
/**
* 将数字格式化
* @param type 格式化类型
* @param decimal 小数位数
*/
format(type, decimal?) {
return this[type](this.v, decimal)
}
/**
* 指定数字最大保留几位小数点
* @param n 位数
*/
fixed(n) {
const { v } = this
return +v.toFixed(n)
}
/**
* 遍历数字
*/
each(fn) {
const { v } = this
for(let i = 1; i <= v; i++) {
fn(i)
}
}
}
interface N {
(n)
}
/**
* 包裹一个数字以方便
* @param n 数字
*/
export const n = <N>function n(n) {
return new Num(n)
}
|
19959350f6c02ef914647c1356f25d6e1ef92a56 | 3,218 | ts | TypeScript | src/utils/statistics/calculation/calculateMCFaddenIncMean.ts | I194/PMTools_2.0 | 313dea61275c5f8b875376578a65e08b9c2fd128 | [
"MIT"
] | null | null | null | src/utils/statistics/calculation/calculateMCFaddenIncMean.ts | I194/PMTools_2.0 | 313dea61275c5f8b875376578a65e08b9c2fd128 | [
"MIT"
] | 1 | 2022-03-17T12:50:14.000Z | 2022-03-17T12:51:57.000Z | src/utils/statistics/calculation/calculateMCFaddenIncMean.ts | I194/PMTools_2.0 | 313dea61275c5f8b875376578a65e08b9c2fd128 | [
"MIT"
] | null | null | null |
const gausspars = (data: Array<number>) => {
/*
calculates gaussian statistics for data
*/
const N = data.length;
if (!N || N === 1) return null;
let mean = 0;
let d = 0;
for (let i = 0; i < N; i++) mean += data[i] / N;
for (let i = 0; i < N; i++) d += Math.pow((data[i] - mean), 2);
var stdev = Math.sqrt(d * (1 / (N - 1)));
return {MI: mean, std: stdev};
};
const calculateMCFaddenIncMean = (
inclinations: Array<number>,
) => {
/*
Calculates Fisher mean inclination from inclination-only data.
Parameters
----------
inc: list of inclination values
Returns
-------
dictionary of
'n' : number of inclination values supplied
'ginc' : gaussian mean of inclinations
'inc' : estimated Fisher mean
'r' : estimated Fisher R value
'k' : estimated Fisher kappa
'alpha95' : estimated fisher alpha_95
'csd' : estimated circular standard deviation
*/
const rad = Math.PI / 180;
let SCOi = 0;
let SSOi = 0; // some definitions
const absInclinations = inclinations.map(inc => (
Math.abs(inc)
));
if (!absInclinations.length) return null;
const gaussparsRes = gausspars(absInclinations)!; // get mean inc and standard deviation
let fpars = {};
const N = inclinations.length;
if (gaussparsRes.MI < 30) { // mean inc < 30, returning gaussian mean'
fpars = {
ginc: gaussparsRes.MI,
inc: gaussparsRes.MI,
n: N,
r: 0,
k: 0,
a95: 0,
csd: 0
};
return fpars;
};
inclinations.forEach(inc => {
// sum over all incs (but take only positive inc)
const coinc = (90 - Math.abs(inc)) * rad;
SCOi += Math.cos(coinc);
SSOi += Math.sin(coinc);
});
let Oo = (90 - gaussparsRes.MI) * rad; // first guess at mean
let SCFlag = -1; // sign change flag
let epsilon = N * Math.cos(Oo); // RHS of zero equations
epsilon += (Math.pow(Math.sin(Oo), 2) - Math.pow(Math.cos(Oo), 2)) * SCOi;
epsilon -= 2 * Math.sin(Oo) * Math.cos(Oo) * SSOi;
while (SCFlag < 0) {
// loop until cross zero
if (gaussparsRes.MI > 0) Oo -= (0.01 * rad); // get steeper
if (gaussparsRes.MI < 0) Oo += (0.01 * rad); // get shallower
var prev = epsilon;
epsilon = N * Math.cos(Oo); // RHS of zero equations
epsilon += (Math.pow(Math.sin(Oo), 2) - Math.pow(Math.cos(Oo), 2)) * SCOi;
epsilon -= 2 * Math.sin(Oo) * Math.cos(Oo) * SSOi;
if (Math.abs(epsilon) > Math.abs(prev)) gaussparsRes.MI = -1 * gaussparsRes.MI; // reverse direction
if (epsilon * prev < 0) SCFlag = 1; // changed sign
};
let S = 0;
let C = 0; // initialize for summation
inclinations.forEach(inc => {
const coinc = (90 - Math.abs(inc)) * rad;
S += Math.sin(Oo - coinc);
C += Math.cos(Oo - coinc);
});
const k = (N - 1) / (2 * (N - C));
const Imle = 90 - (Oo / rad);
const R = 2 * C - N;
const f = 0; // const f = fcalc(2, N - 1);
let a95 = 1 - (0.5) * Math.pow((S / C), 2) - (f / (2. * C * k));
a95 = Math.acos(a95) * 180 / Math.PI;
const csd = 81 / Math.sqrt(k);
fpars = {ginc: gaussparsRes.MI, inc: Imle, n: N, r: R, k, a95, csd};
return fpars;
};
export default calculateMCFaddenIncMean; | 28.477876 | 104 | 0.572405 | 73 | 5 | 0 | 5 | 29 | 0 | 1 | 0 | 2 | 0 | 0 | 15 | 1,149 | 0.008703 | 0.025239 | 0 | 0 | 0 | 0 | 0.051282 | 0.273089 |
/* Example usages of 'gausspars' are shown below:
gausspars(absInclinations);
*/
const gausspars = (data) => {
/*
calculates gaussian statistics for data
*/
const N = data.length;
if (!N || N === 1) return null;
let mean = 0;
let d = 0;
for (let i = 0; i < N; i++) mean += data[i] / N;
for (let i = 0; i < N; i++) d += Math.pow((data[i] - mean), 2);
var stdev = Math.sqrt(d * (1 / (N - 1)));
return {MI: mean, std: stdev};
};
/* Example usages of 'calculateMCFaddenIncMean' are shown below:
;
*/
const calculateMCFaddenIncMean = (
inclinations,
) => {
/*
Calculates Fisher mean inclination from inclination-only data.
Parameters
----------
inc: list of inclination values
Returns
-------
dictionary of
'n' : number of inclination values supplied
'ginc' : gaussian mean of inclinations
'inc' : estimated Fisher mean
'r' : estimated Fisher R value
'k' : estimated Fisher kappa
'alpha95' : estimated fisher alpha_95
'csd' : estimated circular standard deviation
*/
const rad = Math.PI / 180;
let SCOi = 0;
let SSOi = 0; // some definitions
const absInclinations = inclinations.map(inc => (
Math.abs(inc)
));
if (!absInclinations.length) return null;
const gaussparsRes = gausspars(absInclinations)!; // get mean inc and standard deviation
let fpars = {};
const N = inclinations.length;
if (gaussparsRes.MI < 30) { // mean inc < 30, returning gaussian mean'
fpars = {
ginc: gaussparsRes.MI,
inc: gaussparsRes.MI,
n: N,
r: 0,
k: 0,
a95: 0,
csd: 0
};
return fpars;
};
inclinations.forEach(inc => {
// sum over all incs (but take only positive inc)
const coinc = (90 - Math.abs(inc)) * rad;
SCOi += Math.cos(coinc);
SSOi += Math.sin(coinc);
});
let Oo = (90 - gaussparsRes.MI) * rad; // first guess at mean
let SCFlag = -1; // sign change flag
let epsilon = N * Math.cos(Oo); // RHS of zero equations
epsilon += (Math.pow(Math.sin(Oo), 2) - Math.pow(Math.cos(Oo), 2)) * SCOi;
epsilon -= 2 * Math.sin(Oo) * Math.cos(Oo) * SSOi;
while (SCFlag < 0) {
// loop until cross zero
if (gaussparsRes.MI > 0) Oo -= (0.01 * rad); // get steeper
if (gaussparsRes.MI < 0) Oo += (0.01 * rad); // get shallower
var prev = epsilon;
epsilon = N * Math.cos(Oo); // RHS of zero equations
epsilon += (Math.pow(Math.sin(Oo), 2) - Math.pow(Math.cos(Oo), 2)) * SCOi;
epsilon -= 2 * Math.sin(Oo) * Math.cos(Oo) * SSOi;
if (Math.abs(epsilon) > Math.abs(prev)) gaussparsRes.MI = -1 * gaussparsRes.MI; // reverse direction
if (epsilon * prev < 0) SCFlag = 1; // changed sign
};
let S = 0;
let C = 0; // initialize for summation
inclinations.forEach(inc => {
const coinc = (90 - Math.abs(inc)) * rad;
S += Math.sin(Oo - coinc);
C += Math.cos(Oo - coinc);
});
const k = (N - 1) / (2 * (N - C));
const Imle = 90 - (Oo / rad);
const R = 2 * C - N;
const f = 0; // const f = fcalc(2, N - 1);
let a95 = 1 - (0.5) * Math.pow((S / C), 2) - (f / (2. * C * k));
a95 = Math.acos(a95) * 180 / Math.PI;
const csd = 81 / Math.sqrt(k);
fpars = {ginc: gaussparsRes.MI, inc: Imle, n: N, r: R, k, a95, csd};
return fpars;
};
export default calculateMCFaddenIncMean; |
199614470a268c39f9858a815b099f3ff800bdcc | 3,885 | ts | TypeScript | src/electionguard/ballot/election-object-base.ts | DJunge-w/ElectionGuard-COMP413-clean | 6c4c7ce3b34097c29a772efeaa845ea8740ae1eb | [
"MIT"
] | 2 | 2022-02-24T21:48:21.000Z | 2022-03-12T01:36:25.000Z | src/electionguard/ballot/election-object-base.ts | DJunge-w/ElectionGuard-COMP413-clean | 6c4c7ce3b34097c29a772efeaa845ea8740ae1eb | [
"MIT"
] | null | null | null | src/electionguard/ballot/election-object-base.ts | DJunge-w/ElectionGuard-COMP413-clean | 6c4c7ce3b34097c29a772efeaa845ea8740ae1eb | [
"MIT"
] | null | null | null | export interface Eq<T> {
/* Compares the other object to this one. */
equals(other: T): boolean;
}
/**
* A base object to derive other election objects identifiable by object_id
*/
export interface ElectionObjectBase extends Eq<ElectionObjectBase> {
/** The object_id, should be a unique string. */
objectId: string;
}
/**
* A ordered base object to derive other election objects.
*/
export interface OrderedObjectBase extends ElectionObjectBase {
/**
* Used for ordering in a ballot to ensure various encryption primitives are deterministic.
* The sequence order must be unique and should be representative of how the items are represented
* on a template ballot in an external system. The sequence order is not required to be in the order
* in which they are displayed to a voter. Any acceptable range of integer values may be provided.
*/
sequenceOrder: number;
}
/** Sort an array of {@link OrderedObjectBase} in sequence order. Original is unchanged. */
export function sortedArrayOfOrderedElectionObjects<
T extends OrderedObjectBase
>(unsorted: T[]): T[] {
const inputCopy = Array.from(unsorted);
return inputCopy.sort((a, b) => a.sequenceOrder - b.sequenceOrder);
}
/** Sort an array of {@link ElectionObjectBase} in lexical objectId order. Original is unchanged. */
export function sortedArrayOfAnyElectionObjects<T extends ElectionObjectBase>(
unsorted: T[]
): T[] {
const inputCopy = Array.from(unsorted);
return inputCopy.sort((a, b) => a.objectId.localeCompare(b.objectId));
}
/**
* Given an array of {@link OrderedObjectBase} objects, first sorts them
* by their sequence order, then does pairwise comparison for equality.
* The inputs are not mutated.
*/
export function matchingArraysOfOrderedElectionObjects<
T extends OrderedObjectBase
>(a: T[], b: T[]): boolean {
const sortedA = sortedArrayOfOrderedElectionObjects(a);
const sortedB = sortedArrayOfOrderedElectionObjects(b);
if (sortedA.length !== sortedB.length) {
return false;
}
for (let i = 0; i < sortedA.length; i++) {
if (!sortedA[i].equals(sortedB[i])) {
return false;
}
}
return true;
}
/**
* Given an array of any {@link ElectionObjectBase} objects, first sorts them
* by their objectId strings, then does pairwise comparison for equality.
* The inputs are not mutated.
*/
export function matchingArraysOfAnyElectionObjects<
T extends ElectionObjectBase
>(a: T[], b: T[]): boolean {
const sortedA = sortedArrayOfAnyElectionObjects(a);
const sortedB = sortedArrayOfAnyElectionObjects(b);
if (sortedA.length !== sortedB.length) {
return false;
}
for (let i = 0; i < sortedA.length; i++) {
if (!sortedA[i].equals(sortedB[i])) {
return false;
}
}
return true;
}
/**
* Given two arrays of a type that supports equals(), ({@link Eq}),
* returns whether their contents are indeed equal. Arrays that might
* include undefined are also supported.
*/
export function matchingArraysWithEquals<T extends Eq<T>>(
a: (T | undefined)[] | undefined,
b: (T | undefined)[] | undefined
): boolean {
// having some fun here with union types!
if (a === undefined && b === undefined) {
return true;
}
if (a === undefined || b === undefined) {
return false;
}
if (a.length !== b.length) {
return false;
} else {
for (let i = 0; i < a.length; i++) {
if (!objEqualsOrUndefEquals(a[i], b[i])) {
return false;
}
}
return true;
}
}
/** Helper function: compares objects for equality, but also deals with `undefined` values. */
export function objEqualsOrUndefEquals<T extends Eq<T>>(
a: T | undefined,
b: T | undefined
): boolean {
const aUndef = a === undefined;
const bUndef = b === undefined;
if (aUndef && bUndef) {
return true;
}
if (aUndef || bUndef || !a.equals(b)) {
return false;
}
return true;
}
| 29.656489 | 103 | 0.686229 | 86 | 8 | 1 | 15 | 11 | 2 | 3 | 0 | 7 | 3 | 0 | 6.625 | 1,051 | 0.021884 | 0.010466 | 0.001903 | 0.002854 | 0 | 0 | 0.189189 | 0.260567 | export interface Eq<T> {
/* Compares the other object to this one. */
equals(other);
}
/**
* A base object to derive other election objects identifiable by object_id
*/
export interface ElectionObjectBase extends Eq<ElectionObjectBase> {
/** The object_id, should be a unique string. */
objectId;
}
/**
* A ordered base object to derive other election objects.
*/
export interface OrderedObjectBase extends ElectionObjectBase {
/**
* Used for ordering in a ballot to ensure various encryption primitives are deterministic.
* The sequence order must be unique and should be representative of how the items are represented
* on a template ballot in an external system. The sequence order is not required to be in the order
* in which they are displayed to a voter. Any acceptable range of integer values may be provided.
*/
sequenceOrder;
}
/** Sort an array of {@link OrderedObjectBase} in sequence order. Original is unchanged. */
export /* Example usages of 'sortedArrayOfOrderedElectionObjects' are shown below:
sortedArrayOfOrderedElectionObjects(a);
sortedArrayOfOrderedElectionObjects(b);
*/
function sortedArrayOfOrderedElectionObjects<
T extends OrderedObjectBase
>(unsorted) {
const inputCopy = Array.from(unsorted);
return inputCopy.sort((a, b) => a.sequenceOrder - b.sequenceOrder);
}
/** Sort an array of {@link ElectionObjectBase} in lexical objectId order. Original is unchanged. */
export /* Example usages of 'sortedArrayOfAnyElectionObjects' are shown below:
sortedArrayOfAnyElectionObjects(a);
sortedArrayOfAnyElectionObjects(b);
*/
function sortedArrayOfAnyElectionObjects<T extends ElectionObjectBase>(
unsorted
) {
const inputCopy = Array.from(unsorted);
return inputCopy.sort((a, b) => a.objectId.localeCompare(b.objectId));
}
/**
* Given an array of {@link OrderedObjectBase} objects, first sorts them
* by their sequence order, then does pairwise comparison for equality.
* The inputs are not mutated.
*/
export function matchingArraysOfOrderedElectionObjects<
T extends OrderedObjectBase
>(a, b) {
const sortedA = sortedArrayOfOrderedElectionObjects(a);
const sortedB = sortedArrayOfOrderedElectionObjects(b);
if (sortedA.length !== sortedB.length) {
return false;
}
for (let i = 0; i < sortedA.length; i++) {
if (!sortedA[i].equals(sortedB[i])) {
return false;
}
}
return true;
}
/**
* Given an array of any {@link ElectionObjectBase} objects, first sorts them
* by their objectId strings, then does pairwise comparison for equality.
* The inputs are not mutated.
*/
export function matchingArraysOfAnyElectionObjects<
T extends ElectionObjectBase
>(a, b) {
const sortedA = sortedArrayOfAnyElectionObjects(a);
const sortedB = sortedArrayOfAnyElectionObjects(b);
if (sortedA.length !== sortedB.length) {
return false;
}
for (let i = 0; i < sortedA.length; i++) {
if (!sortedA[i].equals(sortedB[i])) {
return false;
}
}
return true;
}
/**
* Given two arrays of a type that supports equals(), ({@link Eq}),
* returns whether their contents are indeed equal. Arrays that might
* include undefined are also supported.
*/
export function matchingArraysWithEquals<T extends Eq<T>>(
a,
b
) {
// having some fun here with union types!
if (a === undefined && b === undefined) {
return true;
}
if (a === undefined || b === undefined) {
return false;
}
if (a.length !== b.length) {
return false;
} else {
for (let i = 0; i < a.length; i++) {
if (!objEqualsOrUndefEquals(a[i], b[i])) {
return false;
}
}
return true;
}
}
/** Helper function: compares objects for equality, but also deals with `undefined` values. */
export /* Example usages of 'objEqualsOrUndefEquals' are shown below:
!objEqualsOrUndefEquals(a[i], b[i]);
*/
function objEqualsOrUndefEquals<T extends Eq<T>>(
a,
b
) {
const aUndef = a === undefined;
const bUndef = b === undefined;
if (aUndef && bUndef) {
return true;
}
if (aUndef || bUndef || !a.equals(b)) {
return false;
}
return true;
}
|
19bb848d35047dfc5869aa1160fd54a9b17f89cd | 1,506 | ts | TypeScript | src/simulator/gear/stats.ts | hintxiv/reassemble | b183f4ec85be527430664ce807551a031e9272b4 | [
"MIT"
] | null | null | null | src/simulator/gear/stats.ts | hintxiv/reassemble | b183f4ec85be527430664ce807551a031e9272b4 | [
"MIT"
] | 1 | 2022-02-05T21:22:46.000Z | 2022-02-05T21:22:46.000Z | src/simulator/gear/stats.ts | hintxiv/reassemble | b183f4ec85be527430664ce807551a031e9272b4 | [
"MIT"
] | null | null | null | export interface Stats
{
weaponDamage: number
vitality: number
strength: number
dexterity: number
intelligence: number
mind: number
critical: number
determination: number
direct: number
skillspeed: number
spellspeed: number
tenacity: number
}
export type StatGroup =
| 'weaponDamage'
| 'vitality'
| 'mainStat'
| 'subStat'
export const statMap: Record<keyof Stats, StatGroup> = {
weaponDamage: 'weaponDamage',
vitality: 'vitality',
strength: 'mainStat',
dexterity: 'mainStat',
intelligence: 'mainStat',
mind: 'mainStat',
critical: 'subStat',
determination: 'subStat',
direct: 'subStat',
skillspeed: 'subStat',
spellspeed: 'subStat',
tenacity: 'subStat',
}
/**
* Helper function to initialize a stats object with default values
* @param someStats optionally specify some stats fields
*/
export function makeStats(someStats?: Partial<Stats> | Array<Partial<Stats>>): Stats {
const stats: Stats = {
weaponDamage: 0,
vitality: 390,
strength: 448,
dexterity: 448,
intelligence: 448,
mind: 448,
critical: 400,
determination: 390,
direct: 400,
skillspeed: 400,
spellspeed: 400,
tenacity: 400,
}
if (Array.isArray(someStats)) {
return someStats.reduce<Stats>(
(total, s) => total = { ...total, ...s }, stats
)
}
return { ...stats, ...someStats }
}
| 21.826087 | 86 | 0.606906 | 56 | 2 | 0 | 3 | 2 | 12 | 0 | 0 | 12 | 2 | 0 | 10.5 | 430 | 0.011628 | 0.004651 | 0.027907 | 0.004651 | 0 | 0 | 0.631579 | 0.219138 | export interface Stats
{
weaponDamage
vitality
strength
dexterity
intelligence
mind
critical
determination
direct
skillspeed
spellspeed
tenacity
}
export type StatGroup =
| 'weaponDamage'
| 'vitality'
| 'mainStat'
| 'subStat'
export const statMap = {
weaponDamage: 'weaponDamage',
vitality: 'vitality',
strength: 'mainStat',
dexterity: 'mainStat',
intelligence: 'mainStat',
mind: 'mainStat',
critical: 'subStat',
determination: 'subStat',
direct: 'subStat',
skillspeed: 'subStat',
spellspeed: 'subStat',
tenacity: 'subStat',
}
/**
* Helper function to initialize a stats object with default values
* @param someStats optionally specify some stats fields
*/
export function makeStats(someStats?) {
const stats = {
weaponDamage: 0,
vitality: 390,
strength: 448,
dexterity: 448,
intelligence: 448,
mind: 448,
critical: 400,
determination: 390,
direct: 400,
skillspeed: 400,
spellspeed: 400,
tenacity: 400,
}
if (Array.isArray(someStats)) {
return someStats.reduce<Stats>(
(total, s) => total = { ...total, ...s }, stats
)
}
return { ...stats, ...someStats }
}
|
19d57bba34088220520f0540c5898a7714748a9a | 2,307 | tsx | TypeScript | contracts/deployedContracts.tsx | SunblockFinance/sunblock | c61bb1014e037121dde2b224c193edc9abab028d | [
"MIT"
] | 3 | 2022-03-04T11:34:31.000Z | 2022-03-04T13:06:43.000Z | contracts/deployedContracts.tsx | SunblockFinance/sunblock | c61bb1014e037121dde2b224c193edc9abab028d | [
"MIT"
] | 29 | 2022-02-17T12:46:13.000Z | 2022-03-30T09:49:47.000Z | contracts/deployedContracts.tsx | SunblockFinance/sunblock | c61bb1014e037121dde2b224c193edc9abab028d | [
"MIT"
] | null | null | null | // Copyright 2022 Kenth Fagerlund.
// SPDX-License-Identifier: MIT
export interface ContractDescriptor {
title: string
logo: string
description: string
url: string
}
export const DESCRIPTOR_STRONGBLOCK:ContractDescriptor = {
title:"Strongblock",
logo:"/svg/strong-logo.svg",
description:"StrongBlock is the first and only blockchain-agnostic protocol to reward nodes",
url:'https://strongblock.com/'
}
export const DESCRIPTOR_YIELDNODE:ContractDescriptor = {
title:"Yieldnodes",
logo:"/svg/yield-nodes-logo.svg",
description:"YieldNodes is a complex, multi-tiered Node rental program based on the new blockchain-based economy",
url:'https://yieldnodes.com/'
}
export const DESCRIPTOR_THOR:ContractDescriptor = {
title:"Thor",
logo:"/svg/thor.svg",
description:"Gain passive income by leveraging THOR's Financial multi-chain yield-farming protocol",
url:'https://www.thor.financial/'
}
export const DESCRIPTOR_POLAR:ContractDescriptor = {
title:"Polar",
logo:"/svg/polar.svg",
description:"Poloar nodes",
url:'https://www.polar.financial/'
}
export const DESCRIPTOR_ANCHOR:ContractDescriptor = {
title:"Anchor",
logo:"/svg/anchor.svg",
description:"Anchor",
url:'https://www.anchor.financial/'
}
export const DESCRIPTOR_ETHERSTONES:ContractDescriptor = {
title:"Etherstones",
logo:"/etherstones.webp",
description:"YieldNodes is a complex, multi-tiered Node rental program based on the new blockchain-based economy",
url:'https://etherstones.fi/'
}
export const DESCRIPTOR_PHOENIX:ContractDescriptor = {
title:"Phoenix",
logo:"/crypto-icons/fire.png",
description:"Fire nodes",
url:'https://thephoenix.finance/app/'
}
export function NameToDescriptor(contractName:string):ContractDescriptor {
switch (contractName) {
case 'Strongblock':
return DESCRIPTOR_STRONGBLOCK
case 'Yieldnodes':
return DESCRIPTOR_YIELDNODE
case 'Polar':
return DESCRIPTOR_POLAR
case 'Thor':
return DESCRIPTOR_THOR
case 'Etherstones':
return DESCRIPTOR_ETHERSTONES
case 'Phoenix':
return DESCRIPTOR_PHOENIX
default:
return DESCRIPTOR_STRONGBLOCK
}
}
| 29.576923 | 118 | 0.693108 | 66 | 1 | 0 | 1 | 7 | 4 | 0 | 0 | 5 | 1 | 0 | 16 | 602 | 0.003322 | 0.011628 | 0.006645 | 0.001661 | 0 | 0 | 0.384615 | 0.218012 | // Copyright 2022 Kenth Fagerlund.
// SPDX-License-Identifier: MIT
export interface ContractDescriptor {
title
logo
description
url
}
export const DESCRIPTOR_STRONGBLOCK = {
title:"Strongblock",
logo:"/svg/strong-logo.svg",
description:"StrongBlock is the first and only blockchain-agnostic protocol to reward nodes",
url:'https://strongblock.com/'
}
export const DESCRIPTOR_YIELDNODE = {
title:"Yieldnodes",
logo:"/svg/yield-nodes-logo.svg",
description:"YieldNodes is a complex, multi-tiered Node rental program based on the new blockchain-based economy",
url:'https://yieldnodes.com/'
}
export const DESCRIPTOR_THOR = {
title:"Thor",
logo:"/svg/thor.svg",
description:"Gain passive income by leveraging THOR's Financial multi-chain yield-farming protocol",
url:'https://www.thor.financial/'
}
export const DESCRIPTOR_POLAR = {
title:"Polar",
logo:"/svg/polar.svg",
description:"Poloar nodes",
url:'https://www.polar.financial/'
}
export const DESCRIPTOR_ANCHOR = {
title:"Anchor",
logo:"/svg/anchor.svg",
description:"Anchor",
url:'https://www.anchor.financial/'
}
export const DESCRIPTOR_ETHERSTONES = {
title:"Etherstones",
logo:"/etherstones.webp",
description:"YieldNodes is a complex, multi-tiered Node rental program based on the new blockchain-based economy",
url:'https://etherstones.fi/'
}
export const DESCRIPTOR_PHOENIX = {
title:"Phoenix",
logo:"/crypto-icons/fire.png",
description:"Fire nodes",
url:'https://thephoenix.finance/app/'
}
export function NameToDescriptor(contractName) {
switch (contractName) {
case 'Strongblock':
return DESCRIPTOR_STRONGBLOCK
case 'Yieldnodes':
return DESCRIPTOR_YIELDNODE
case 'Polar':
return DESCRIPTOR_POLAR
case 'Thor':
return DESCRIPTOR_THOR
case 'Etherstones':
return DESCRIPTOR_ETHERSTONES
case 'Phoenix':
return DESCRIPTOR_PHOENIX
default:
return DESCRIPTOR_STRONGBLOCK
}
}
|
ed2225712939ad4ccc4082d39228248ab91b41fa | 2,474 | ts | TypeScript | src/util/queue.ts | jkunimune15/dunia-hamar | 2838b8557ac89c2446e6b62158e27318e9cdd330 | [
"MIT"
] | 1 | 2022-01-31T04:50:43.000Z | 2022-01-31T04:50:43.000Z | src/util/queue.ts | jkunimune15/world-hammer | 2838b8557ac89c2446e6b62158e27318e9cdd330 | [
"MIT"
] | null | null | null | src/util/queue.ts | jkunimune15/world-hammer | 2838b8557ac89c2446e6b62158e27318e9cdd330 | [
"MIT"
] | null | null | null | /*
ISC License
Copyright (c) 2017, Vladimir Agafonkin
Permission to use, copy, modify, and/or distribute this software for any porpoise
with or without fee is hereby granted, provided that the above copyright notice
and this permission notice appear in all copies.
THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WUSLOPEBO
REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND
FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WUSLOPEBO RESULTING FROM LOSS
OF MSE, DATA OR PROFITS, WUSLOPEBO IN AN ACCION OF CONTRACT, NEGLIGENCE OR OTHER
TORTIOUS ACCION, ARISING OUT OF OR IN CONNECCION WUSLOPEBO THE MSE OR PERFORMANCE OF
THIS SOFTWARE.
*/
/**
* The smallest and simplest binary heap priority queue in JavaScript.
* @author Vladimir Agafonkin (@mourner)
*/
export default class Queue<E> {
private readonly data: E[];
private readonly compare: (a: E, b: E) => number;
private length: number;
constructor(data: E[] = [], compare: (a: E, b: E) => number) {
this.data = data;
this.length = this.data.length;
this.compare = compare;
if (this.length > 0)
for (let i = (this.length >> 1) - 1; i >= 0; i--)
this.down(i);
}
public empty(): boolean {
return this.length === 0;
}
public push(item: E): void {
this.data.push(item);
this.up(this.length++);
}
public pop(): E {
if (this.length === 0) return undefined;
const top = this.data[0];
const bottom = this.data.pop();
if (--this.length > 0) {
this.data[0] = bottom;
this.down(0);
}
return top;
}
public peek(): E {
return this.data[0];
}
private up(pos: number): void {
const {data, compare} = this;
const item = data[pos];
while (pos > 0) {
const parent = (pos - 1) >> 1;
const current = data[parent];
if (compare(item, current) >= 0) break;
data[pos] = current;
pos = parent;
}
data[pos] = item;
}
private down(pos: number): void {
const {data, compare} = this;
const halfLength = this.length >> 1;
const item = data[pos];
while (pos < halfLength) {
let bestChild = (pos << 1) + 1; // initially it is the left child
const right = bestChild + 1;
if (right < this.length && compare(data[right], data[bestChild]) < 0) {
bestChild = right;
}
if (compare(data[bestChild], item) >= 0) break;
data[pos] = data[bestChild];
pos = bestChild;
}
data[pos] = item;
}
}
| 24.254902 | 84 | 0.661277 | 61 | 7 | 0 | 5 | 12 | 3 | 4 | 0 | 9 | 1 | 0 | 6 | 825 | 0.014545 | 0.014545 | 0.003636 | 0.001212 | 0 | 0 | 0.333333 | 0.254137 | /*
ISC License
Copyright (c) 2017, Vladimir Agafonkin
Permission to use, copy, modify, and/or distribute this software for any porpoise
with or without fee is hereby granted, provided that the above copyright notice
and this permission notice appear in all copies.
THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WUSLOPEBO
REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND
FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WUSLOPEBO RESULTING FROM LOSS
OF MSE, DATA OR PROFITS, WUSLOPEBO IN AN ACCION OF CONTRACT, NEGLIGENCE OR OTHER
TORTIOUS ACCION, ARISING OUT OF OR IN CONNECCION WUSLOPEBO THE MSE OR PERFORMANCE OF
THIS SOFTWARE.
*/
/**
* The smallest and simplest binary heap priority queue in JavaScript.
* @author Vladimir Agafonkin (@mourner)
*/
export default class Queue<E> {
private readonly data;
private readonly compare;
private length;
constructor(data = [], compare) {
this.data = data;
this.length = this.data.length;
this.compare = compare;
if (this.length > 0)
for (let i = (this.length >> 1) - 1; i >= 0; i--)
this.down(i);
}
public empty() {
return this.length === 0;
}
public push(item) {
this.data.push(item);
this.up(this.length++);
}
public pop() {
if (this.length === 0) return undefined;
const top = this.data[0];
const bottom = this.data.pop();
if (--this.length > 0) {
this.data[0] = bottom;
this.down(0);
}
return top;
}
public peek() {
return this.data[0];
}
private up(pos) {
const {data, compare} = this;
const item = data[pos];
while (pos > 0) {
const parent = (pos - 1) >> 1;
const current = data[parent];
if (compare(item, current) >= 0) break;
data[pos] = current;
pos = parent;
}
data[pos] = item;
}
private down(pos) {
const {data, compare} = this;
const halfLength = this.length >> 1;
const item = data[pos];
while (pos < halfLength) {
let bestChild = (pos << 1) + 1; // initially it is the left child
const right = bestChild + 1;
if (right < this.length && compare(data[right], data[bestChild]) < 0) {
bestChild = right;
}
if (compare(data[bestChild], item) >= 0) break;
data[pos] = data[bestChild];
pos = bestChild;
}
data[pos] = item;
}
}
|
ed707857103d58beb481bd7cdef24308b16ff916 | 2,566 | ts | TypeScript | src/utils/Tree.ts | GaoNeng-wWw/gachi | 643c3bfc2b89e53fd73376d8ad44f7773948ef16 | [
"MIT"
] | 1 | 2022-02-17T12:11:11.000Z | 2022-02-17T12:11:11.000Z | src/utils/Tree.ts | GaoNeng-wWw/gachi | 643c3bfc2b89e53fd73376d8ad44f7773948ef16 | [
"MIT"
] | null | null | null | src/utils/Tree.ts | GaoNeng-wWw/gachi | 643c3bfc2b89e53fd73376d8ad44f7773948ef16 | [
"MIT"
] | null | null | null | type Node_Type = Node_;
export class Node_{
public data:any;
public children: Node_Type[];
public parent: Node_ | null;
constructor(data: any){
this.data = data;
this.children = [];
this.parent = null;
}
}
export default class tree {
public static head: Node_ = new Node_('head');
public static path:string[][] | string[] = [];
public static rootNode = '';
static append(parent:any=undefined, data:any){
const node = new Node_(data);
if (!parent){
this.head?.children.push(node);
return;
} else {
const stack = [...this.head?.children] as Node_[];
let prevIdx = null;
while (stack?.length){
const shiftItem = stack.shift();
prevIdx = shiftItem;
const children = shiftItem?.children;
if (shiftItem?.data?.data === parent.data){
node.parent = prevIdx as Node_;
shiftItem?.children.push(node);
return;
} else {
children?.forEach((node:Node_)=>{
stack.push(node);
});
}
}
}
}
static getTree(){
return this.head;
}
static async getPath(){
// let rootNode = ;
const rootNode = this.getRoot();
const stack = [...this.head.children];
let path_:string[] = [];
while (stack.length){
const shiftItem = stack.shift();
path_.push(shiftItem?.data.data);
const children = shiftItem?.children;
if (shiftItem?.data.type === 'item'){
(this.path as string[][]).push([...path_ as string[]]);
if (shiftItem.parent){
while (
path_[path_.length - 1] !== rootNode?.data.data
){
path_.pop();
}
} else {
path_ = [];
}
} else if (!shiftItem?.children.length){
(this.path as string[][]).push([...path_ as string[]]);
path_.pop();
if (shiftItem?.parent){
while (
path_[path_.length - 1] !== rootNode?.data.data
){
path_.pop();
}
} else {
path_ = [];
}
}
for (let i=children?.length as number-1; i>=0; i--){
stack.unshift(children?.[i] as Node_);
}
}
return this.path;
}
private static getRoot(){
const stack = [...tree.head.children];
while (stack.length){
const shiftItem = stack.shift();
if (shiftItem?.data.type === 'parent'){
return shiftItem;
} else {
const children = shiftItem?.children;
for (let i=children?.length as number-1; i>=0; i--){
stack.unshift(children?.[i] as Node_);
}
}
}
return undefined;
}
static clearTree(){
this.head = new Node_('head');
this.path = [];
this.rootNode = '';
return true;
}
}
/**
* a {
* b{
* d
* }
* c{
* }
* }
*
*
*
*
*/
| 21.563025 | 59 | 0.574435 | 102 | 7 | 0 | 4 | 15 | 6 | 1 | 4 | 9 | 3 | 10 | 11.428571 | 850 | 0.012941 | 0.017647 | 0.007059 | 0.003529 | 0.011765 | 0.125 | 0.28125 | 0.259821 | type Node_Type = Node_;
export class Node_{
public data;
public children;
public parent;
constructor(data){
this.data = data;
this.children = [];
this.parent = null;
}
}
export default class tree {
public static head = new Node_('head');
public static path = [];
public static rootNode = '';
static append(parent=undefined, data){
const node = new Node_(data);
if (!parent){
this.head?.children.push(node);
return;
} else {
const stack = [...this.head?.children] as Node_[];
let prevIdx = null;
while (stack?.length){
const shiftItem = stack.shift();
prevIdx = shiftItem;
const children = shiftItem?.children;
if (shiftItem?.data?.data === parent.data){
node.parent = prevIdx as Node_;
shiftItem?.children.push(node);
return;
} else {
children?.forEach((node)=>{
stack.push(node);
});
}
}
}
}
static getTree(){
return this.head;
}
static async getPath(){
// let rootNode = ;
const rootNode = this.getRoot();
const stack = [...this.head.children];
let path_ = [];
while (stack.length){
const shiftItem = stack.shift();
path_.push(shiftItem?.data.data);
const children = shiftItem?.children;
if (shiftItem?.data.type === 'item'){
(this.path as string[][]).push([...path_ as string[]]);
if (shiftItem.parent){
while (
path_[path_.length - 1] !== rootNode?.data.data
){
path_.pop();
}
} else {
path_ = [];
}
} else if (!shiftItem?.children.length){
(this.path as string[][]).push([...path_ as string[]]);
path_.pop();
if (shiftItem?.parent){
while (
path_[path_.length - 1] !== rootNode?.data.data
){
path_.pop();
}
} else {
path_ = [];
}
}
for (let i=children?.length as number-1; i>=0; i--){
stack.unshift(children?.[i] as Node_);
}
}
return this.path;
}
private static getRoot(){
const stack = [...tree.head.children];
while (stack.length){
const shiftItem = stack.shift();
if (shiftItem?.data.type === 'parent'){
return shiftItem;
} else {
const children = shiftItem?.children;
for (let i=children?.length as number-1; i>=0; i--){
stack.unshift(children?.[i] as Node_);
}
}
}
return undefined;
}
static clearTree(){
this.head = new Node_('head');
this.path = [];
this.rootNode = '';
return true;
}
}
/**
* a {
* b{
* d
* }
* c{
* }
* }
*
*
*
*
*/
|
31402e411e80253d3dc62503b11ea12d9ab998ef | 2,527 | ts | TypeScript | packages/shared/utils/date.ts | dvargas92495/clerkfe | 3fd42ed5fe435326163f86852af03f954ad3e7ba | [
"MIT"
] | 60 | 2022-01-20T10:06:23.000Z | 2022-03-29T13:07:15.000Z | packages/shared/utils/date.ts | dvargas92495/clerkfe | 3fd42ed5fe435326163f86852af03f954ad3e7ba | [
"MIT"
] | 25 | 2022-01-25T09:36:02.000Z | 2022-03-31T11:19:05.000Z | packages/shared/utils/date.ts | dvargas92495/clerkfe | 3fd42ed5fe435326163f86852af03f954ad3e7ba | [
"MIT"
] | 7 | 2022-02-16T17:11:41.000Z | 2022-03-24T13:03:01.000Z | const MILLISECONDS_IN_DAY = 86400000;
const DAYS_EN = ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday'];
export function dateTo12HourTime(date: Date): string {
if (!date) {
return '';
}
return date.toLocaleString('en-US', {
hour: '2-digit',
minute: 'numeric',
hour12: true,
});
}
export function differenceInCalendarDays(a: Date, b: Date, { absolute = true } = {}): number {
if (!a || !b) {
return 0;
}
const utcA = Date.UTC(a.getFullYear(), a.getMonth(), a.getDate());
const utcB = Date.UTC(b.getFullYear(), b.getMonth(), b.getDate());
const diff = Math.floor((utcB - utcA) / MILLISECONDS_IN_DAY);
return absolute ? Math.abs(diff) : diff;
}
function normalizeDate(d: Date | string | number): Date {
try {
return new Date(d || new Date());
} catch (e) {
return new Date();
}
}
/*
* Follows date-fns format, see here:
* https://date-fns.org/v2.21.1/docs/formatRelative
* TODO: support localisation
* | Distance to the base date | Result |
* |---------------------------|---------------------------|
* | Previous 6 days | last Sunday at 04:30 AM |
* | Last day | yesterday at 04:30 AM |
* | Same day | today at 04:30 AM |
* | Next day | tomorrow at 04:30 AM |
* | Next 6 days | Sunday at 04:30 AM |
* | Other | 12/31/2017 |
*/
export function formatRelative(date: Date, relativeTo: Date): string {
if (!date || !relativeTo) {
return '';
}
const a = normalizeDate(date);
const b = normalizeDate(relativeTo);
const differenceInDays = differenceInCalendarDays(b, a, { absolute: false });
const time12Hour = dateTo12HourTime(a);
const dayName = DAYS_EN[a.getDay()];
if (differenceInDays < -6) {
return a.toLocaleDateString();
}
if (differenceInDays < -1) {
return `last ${dayName} at ${time12Hour}`;
}
if (differenceInDays === -1) {
return `yesterday at ${time12Hour}`;
}
if (differenceInDays === 0) {
return `today at ${time12Hour}`;
}
if (differenceInDays === 1) {
return `tomorrow at ${time12Hour}`;
}
if (differenceInDays < 7) {
return `${dayName} at ${time12Hour}`;
}
return a.toLocaleDateString();
}
export function addYears(initialDate: Date | number | string, yearsToAdd: number): Date {
const date = normalizeDate(initialDate);
date.setFullYear(date.getFullYear() + yearsToAdd);
return date;
}
| 30.817073 | 95 | 0.585675 | 62 | 5 | 0 | 9 | 11 | 0 | 3 | 0 | 8 | 0 | 0 | 10 | 785 | 0.017834 | 0.014013 | 0 | 0 | 0 | 0 | 0.32 | 0.257919 | const MILLISECONDS_IN_DAY = 86400000;
const DAYS_EN = ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday'];
export /* Example usages of 'dateTo12HourTime' are shown below:
dateTo12HourTime(a);
*/
function dateTo12HourTime(date) {
if (!date) {
return '';
}
return date.toLocaleString('en-US', {
hour: '2-digit',
minute: 'numeric',
hour12: true,
});
}
export /* Example usages of 'differenceInCalendarDays' are shown below:
differenceInCalendarDays(b, a, { absolute: false });
*/
function differenceInCalendarDays(a, b, { absolute = true } = {}) {
if (!a || !b) {
return 0;
}
const utcA = Date.UTC(a.getFullYear(), a.getMonth(), a.getDate());
const utcB = Date.UTC(b.getFullYear(), b.getMonth(), b.getDate());
const diff = Math.floor((utcB - utcA) / MILLISECONDS_IN_DAY);
return absolute ? Math.abs(diff) : diff;
}
/* Example usages of 'normalizeDate' are shown below:
normalizeDate(date);
normalizeDate(relativeTo);
normalizeDate(initialDate);
*/
function normalizeDate(d) {
try {
return new Date(d || new Date());
} catch (e) {
return new Date();
}
}
/*
* Follows date-fns format, see here:
* https://date-fns.org/v2.21.1/docs/formatRelative
* TODO: support localisation
* | Distance to the base date | Result |
* |---------------------------|---------------------------|
* | Previous 6 days | last Sunday at 04:30 AM |
* | Last day | yesterday at 04:30 AM |
* | Same day | today at 04:30 AM |
* | Next day | tomorrow at 04:30 AM |
* | Next 6 days | Sunday at 04:30 AM |
* | Other | 12/31/2017 |
*/
export function formatRelative(date, relativeTo) {
if (!date || !relativeTo) {
return '';
}
const a = normalizeDate(date);
const b = normalizeDate(relativeTo);
const differenceInDays = differenceInCalendarDays(b, a, { absolute: false });
const time12Hour = dateTo12HourTime(a);
const dayName = DAYS_EN[a.getDay()];
if (differenceInDays < -6) {
return a.toLocaleDateString();
}
if (differenceInDays < -1) {
return `last ${dayName} at ${time12Hour}`;
}
if (differenceInDays === -1) {
return `yesterday at ${time12Hour}`;
}
if (differenceInDays === 0) {
return `today at ${time12Hour}`;
}
if (differenceInDays === 1) {
return `tomorrow at ${time12Hour}`;
}
if (differenceInDays < 7) {
return `${dayName} at ${time12Hour}`;
}
return a.toLocaleDateString();
}
export function addYears(initialDate, yearsToAdd) {
const date = normalizeDate(initialDate);
date.setFullYear(date.getFullYear() + yearsToAdd);
return date;
}
|
3181b173facb368c8fed7594ab8a782f337f300c | 3,536 | ts | TypeScript | uaa-ui/src/utils/tree.ts | brave9uy/dsn-uaa | 40ad83482a15f279d3f2559b21ed5ac890d7de5f | [
"MIT"
] | 3 | 2022-03-24T10:06:03.000Z | 2022-03-28T03:00:43.000Z | uaa-ui/src/utils/tree.ts | brave9uy/dsn-uaa | 40ad83482a15f279d3f2559b21ed5ac890d7de5f | [
"MIT"
] | null | null | null | uaa-ui/src/utils/tree.ts | brave9uy/dsn-uaa | 40ad83482a15f279d3f2559b21ed5ac890d7de5f | [
"MIT"
] | 1 | 2022-03-24T10:06:05.000Z | 2022-03-24T10:06:05.000Z | /**
* / 将数组递归成树
* @param arr 数组
* @param key 关键字段的字段名
* @param parentKey 父节点关键字段的值
* @param parent 父节点关键字段值的字段名
* @param children 子节点字段字段名
* @return {*}
*/
export const arrToTree = (arr: any[],
parentKey = 0,
key = 'id',
parent = 'parent',
children = 'children'): any => {
let node: any = { [key]: parentKey }
// 1. 根据传入id,从数组remove节点,避免遍历时重新计算
if (parentKey !== 0) {
for (let i = 0; i < arr.length; i++) {
if (arr[i][key] === parentKey) {
node = arr.splice(i, 1)[0]
break
}
}
}
// 2. 遍历剩余的节点,如果有节点的pid跟这个节点的id相等,即为这个节点的子节点
for (let j = 0; j < arr.length; j++) {
if (arr[j][key] === undefined) {
throw new Error(`属性${key}在node中不存在`)
}
if (arr[j] === undefined && arr.length > 0) {
j = 0
}
if (arr[j][parent] === node[key]) {
const n = arrToTree(arr, arr[j][key], key, parent, children)
if (node[children] === undefined) {
node[children] = []
}
node[children].push(n)
// 下标变成-1,是因为remove元素后希望重新计算有无子元素
j = -1
}
}
return node
}
/**
* 广度优先算法 - 查找
* 凭借条件找出对应的节点。查找到第一个吻合的节点立即返回。建议用id作为条件
* @param condition { name: '超级管理员' }
* @param sourceNode 传入被查找的节点,第一层可以是root.也可以是nodes
* @return {*}
*/
export const breadthFirstSearch = (condition: Record<string, unknown>, sourceNode: Record<string, unknown> | any[]): Record<string, any> | null => {
let key = ''
let value: null | any = null
let returnNode: null | Record<string, unknown> = null
for (const k in condition) {
key = k
value = condition[k]
}
if (key !== null && value !== null) {
let queue: any[] = []
if (Object.prototype.toString.call(sourceNode) === '[object Array]') {
queue = JSON.parse(JSON.stringify(sourceNode))
} else {
queue = [JSON.parse(JSON.stringify(sourceNode))]
}
while (queue.length > 0) {
[...queue].forEach(child => {
queue.shift()
if (child[key] !== undefined && child[key] === value) {
returnNode = child
return false
}
child.children && (queue.push(...child.children))
})
}
}
return returnNode
}
/**
* 向父方向遍历树,执行方法. Promise保证执行顺序
* @param sourceNode 整个节点树
* @param keyProp 关键字段
* @param parentKey 父节点关键字段值
* @param func 执行方法
* @param parent 父节点关键字段值的字段名
* @param children 子节点字段名
*/
export const breadthFirstExecuteUpwards = (
sourceNode: Record<string, unknown> | any[],
keyProp: string,
parentKey: number | string,
func: (node: Record<string, any>, resolve: (value: unknown) => void) => void,
parent = 'parent',
children = 'children'): void => {
// 1. 找到父节点
const node = breadthFirstSearch({ [keyProp]: parentKey }, sourceNode)
// 2. 父节点执行方法
let promise: Promise<unknown> | null = null
if (node && node[children] && Array.isArray(node[children])) {
if (func !== undefined) {
promise = new Promise((resolve: (value: unknown) => void) => {
func(node, resolve)
})
}
}
// 3. 继续向上遍历
if (node && node[parent] !== undefined && promise !== null) {
promise.then(() => {
breadthFirstExecuteUpwards(sourceNode, keyProp, node[parent], func, parent, children)
})
}
}
/**
* 深度优先算法 - 执行
*/
export const depthFirstExecute = (tree: any[] | any, func: (node: any) => void, children = 'children'): void => {
if (!Array.isArray(tree)) {
tree = [tree]
}
tree.forEach((node: any) => {
node[children] && depthFirstExecute(node[children], func, children) // 遍历子树
func && func(node)
})
}
| 27.410853 | 148 | 0.584276 | 91 | 8 | 0 | 19 | 14 | 0 | 4 | 13 | 22 | 0 | 0 | 10.375 | 1,198 | 0.022538 | 0.011686 | 0 | 0 | 0 | 0.317073 | 0.536585 | 0.256263 | /**
* / 将数组递归成树
* @param arr 数组
* @param key 关键字段的字段名
* @param parentKey 父节点关键字段的值
* @param parent 父节点关键字段值的字段名
* @param children 子节点字段字段名
* @return {*}
*/
export /* Example usages of 'arrToTree' are shown below:
arrToTree(arr, arr[j][key], key, parent, children);
*/
const arrToTree = (arr,
parentKey = 0,
key = 'id',
parent = 'parent',
children = 'children') => {
let node = { [key]: parentKey }
// 1. 根据传入id,从数组remove节点,避免遍历时重新计算
if (parentKey !== 0) {
for (let i = 0; i < arr.length; i++) {
if (arr[i][key] === parentKey) {
node = arr.splice(i, 1)[0]
break
}
}
}
// 2. 遍历剩余的节点,如果有节点的pid跟这个节点的id相等,即为这个节点的子节点
for (let j = 0; j < arr.length; j++) {
if (arr[j][key] === undefined) {
throw new Error(`属性${key}在node中不存在`)
}
if (arr[j] === undefined && arr.length > 0) {
j = 0
}
if (arr[j][parent] === node[key]) {
const n = arrToTree(arr, arr[j][key], key, parent, children)
if (node[children] === undefined) {
node[children] = []
}
node[children].push(n)
// 下标变成-1,是因为remove元素后希望重新计算有无子元素
j = -1
}
}
return node
}
/**
* 广度优先算法 - 查找
* 凭借条件找出对应的节点。查找到第一个吻合的节点立即返回。建议用id作为条件
* @param condition { name: '超级管理员' }
* @param sourceNode 传入被查找的节点,第一层可以是root.也可以是nodes
* @return {*}
*/
export /* Example usages of 'breadthFirstSearch' are shown below:
breadthFirstSearch({ [keyProp]: parentKey }, sourceNode);
*/
const breadthFirstSearch = (condition, sourceNode) => {
let key = ''
let value = null
let returnNode = null
for (const k in condition) {
key = k
value = condition[k]
}
if (key !== null && value !== null) {
let queue = []
if (Object.prototype.toString.call(sourceNode) === '[object Array]') {
queue = JSON.parse(JSON.stringify(sourceNode))
} else {
queue = [JSON.parse(JSON.stringify(sourceNode))]
}
while (queue.length > 0) {
[...queue].forEach(child => {
queue.shift()
if (child[key] !== undefined && child[key] === value) {
returnNode = child
return false
}
child.children && (queue.push(...child.children))
})
}
}
return returnNode
}
/**
* 向父方向遍历树,执行方法. Promise保证执行顺序
* @param sourceNode 整个节点树
* @param keyProp 关键字段
* @param parentKey 父节点关键字段值
* @param func 执行方法
* @param parent 父节点关键字段值的字段名
* @param children 子节点字段名
*/
export /* Example usages of 'breadthFirstExecuteUpwards' are shown below:
breadthFirstExecuteUpwards(sourceNode, keyProp, node[parent], func, parent, children);
*/
const breadthFirstExecuteUpwards = (
sourceNode,
keyProp,
parentKey,
func,
parent = 'parent',
children = 'children') => {
// 1. 找到父节点
const node = breadthFirstSearch({ [keyProp]: parentKey }, sourceNode)
// 2. 父节点执行方法
let promise = null
if (node && node[children] && Array.isArray(node[children])) {
if (func !== undefined) {
promise = new Promise((resolve) => {
func(node, resolve)
})
}
}
// 3. 继续向上遍历
if (node && node[parent] !== undefined && promise !== null) {
promise.then(() => {
breadthFirstExecuteUpwards(sourceNode, keyProp, node[parent], func, parent, children)
})
}
}
/**
* 深度优先算法 - 执行
*/
export /* Example usages of 'depthFirstExecute' are shown below:
node[children] && depthFirstExecute(node[children], func, children) // 遍历子树
;
*/
const depthFirstExecute = (tree, func, children = 'children') => {
if (!Array.isArray(tree)) {
tree = [tree]
}
tree.forEach((node) => {
node[children] && depthFirstExecute(node[children], func, children) // 遍历子树
func && func(node)
})
}
|
31a28792b3d0181850107c86d45571774a6ca9d7 | 1,597 | ts | TypeScript | src/components/vector1d.ts | allen-garvey/embla-carousel | 8a9615965e1256c08816e104dd60d01dde171237 | [
"MIT"
] | 1 | 2022-02-17T08:23:35.000Z | 2022-02-17T08:23:35.000Z | src/components/vector1d.ts | chernrus/embla-carousel | c6c535e75fac833979b147ec2f5aa1bcc18bb189 | [
"MIT"
] | null | null | null | src/components/vector1d.ts | chernrus/embla-carousel | c6c535e75fac833979b147ec2f5aa1bcc18bb189 | [
"MIT"
] | null | null | null | export type Vector1D = {
get: () => number
set: (v: Vector1D) => Vector1D
add: (v: Vector1D) => Vector1D
subtract: (v: Vector1D) => Vector1D
multiply: (n: number) => Vector1D
setNumber: (n: number) => Vector1D
addNumber: (n: number) => Vector1D
subtractNumber: (n: number) => Vector1D
divide: (n: number) => Vector1D
magnitude: () => number
normalize: () => Vector1D
}
export function Vector1D(value: number): Vector1D {
const state = { value }
function get(): number {
return state.value
}
function set(v: Vector1D): Vector1D {
state.value = v.get()
return self
}
function add(v: Vector1D): Vector1D {
state.value += v.get()
return self
}
function subtract(v: Vector1D): Vector1D {
state.value -= v.get()
return self
}
function multiply(n: number): Vector1D {
state.value *= n
return self
}
function divide(n: number): Vector1D {
state.value /= n
return self
}
function setNumber(n: number): Vector1D {
state.value = n
return self
}
function addNumber(n: number): Vector1D {
state.value += n
return self
}
function subtractNumber(n: number): Vector1D {
state.value -= n
return self
}
function magnitude(): number {
return get()
}
function normalize(): Vector1D {
const m = magnitude()
if (m !== 0) divide(m)
return self
}
const self: Vector1D = {
add,
addNumber,
divide,
get,
magnitude,
multiply,
normalize,
set,
setNumber,
subtract,
subtractNumber,
}
return Object.freeze(self)
}
| 18.356322 | 51 | 0.609894 | 73 | 12 | 0 | 9 | 3 | 11 | 3 | 0 | 15 | 1 | 0 | 6.583333 | 473 | 0.044397 | 0.006342 | 0.023256 | 0.002114 | 0 | 0 | 0.428571 | 0.298292 | export type Vector1D = {
get
set
add
subtract
multiply
setNumber
addNumber
subtractNumber
divide
magnitude
normalize
}
export /* Example usages of 'Vector1D' are shown below:
;
*/
function Vector1D(value) {
const state = { value }
/* Example usages of 'get' are shown below:
;
state.value = v.get();
state.value += v.get();
state.value -= v.get();
get();
*/
function get() {
return state.value
}
/* Example usages of 'set' are shown below:
;
*/
function set(v) {
state.value = v.get()
return self
}
/* Example usages of 'add' are shown below:
;
*/
function add(v) {
state.value += v.get()
return self
}
/* Example usages of 'subtract' are shown below:
;
*/
function subtract(v) {
state.value -= v.get()
return self
}
/* Example usages of 'multiply' are shown below:
;
*/
function multiply(n) {
state.value *= n
return self
}
/* Example usages of 'divide' are shown below:
;
divide(m);
*/
function divide(n) {
state.value /= n
return self
}
/* Example usages of 'setNumber' are shown below:
;
*/
function setNumber(n) {
state.value = n
return self
}
/* Example usages of 'addNumber' are shown below:
;
*/
function addNumber(n) {
state.value += n
return self
}
/* Example usages of 'subtractNumber' are shown below:
;
*/
function subtractNumber(n) {
state.value -= n
return self
}
/* Example usages of 'magnitude' are shown below:
;
magnitude();
*/
function magnitude() {
return get()
}
/* Example usages of 'normalize' are shown below:
;
*/
function normalize() {
const m = magnitude()
if (m !== 0) divide(m)
return self
}
const self = {
add,
addNumber,
divide,
get,
magnitude,
multiply,
normalize,
set,
setNumber,
subtract,
subtractNumber,
}
return Object.freeze(self)
}
|
90205cd08f75381d042c1f9f76be74b4df3a172a | 7,825 | ts | TypeScript | packages/core/src/util/pathToRegexp.ts | 4xii/midway | 290179ce47c287f2b39599e609a349c14907cccc | [
"MIT"
] | 1 | 2022-03-21T16:08:11.000Z | 2022-03-21T16:08:11.000Z | packages/core/src/util/pathToRegexp.ts | 4xii/midway | 290179ce47c287f2b39599e609a349c14907cccc | [
"MIT"
] | null | null | null | packages/core/src/util/pathToRegexp.ts | 4xii/midway | 290179ce47c287f2b39599e609a349c14907cccc | [
"MIT"
] | null | null | null | /**
* this file fork from path-to-regexp package v1.8.0
*/
/**
* The main path matching regexp utility.
*
* @type {RegExp}
*/
const PATH_REGEXP = new RegExp(
[
// Match escaped characters that would otherwise appear in future matches.
// This allows the user to escape special characters that won't transform.
'(\\\\.)',
// Match Express-style parameters and un-named parameters with a prefix
// and optional suffixes. Matches appear as:
//
// "/:test(\\d+)?" => ["/", "test", "\d+", undefined, "?", undefined]
// "/route(\\d+)" => [undefined, undefined, undefined, "\d+", undefined, undefined]
// "/*" => ["/", undefined, undefined, undefined, undefined, "*"]
'([\\/.])?(?:(?:\\:(\\w+)(?:\\(((?:\\\\.|[^\\\\()])+)\\))?|\\(((?:\\\\.|[^\\\\()])+)\\))([+*?])?|(\\*))',
].join('|'),
'g'
);
/**
* Parse a string for the raw tokens.
*
* @param {string} str
* @param {Object=} options
* @return {!Array}
*/
function parse(str, options) {
const tokens = [];
let key = 0;
let index = 0;
let path = '';
const defaultDelimiter = (options && options.delimiter) || '/';
let res;
while ((res = PATH_REGEXP.exec(str)) != null) {
const m = res[0];
const escaped = res[1];
const offset = res.index;
path += str.slice(index, offset);
index = offset + m.length;
// Ignore already escaped sequences.
if (escaped) {
path += escaped[1];
continue;
}
const next = str[index];
const prefix = res[2];
const name = res[3];
const capture = res[4];
const group = res[5];
const modifier = res[6];
const asterisk = res[7];
// Push the current path onto the tokens.
if (path) {
tokens.push(path);
path = '';
}
const partial = prefix != null && next != null && next !== prefix;
const repeat = modifier === '+' || modifier === '*';
const optional = modifier === '?' || modifier === '*';
const delimiter = res[2] || defaultDelimiter;
const pattern = capture || group;
tokens.push({
name: name || key++,
prefix: prefix || '',
delimiter: delimiter,
optional: optional,
repeat: repeat,
partial: partial,
asterisk: !!asterisk,
pattern: pattern
? escapeGroup(pattern)
: asterisk
? '.*'
: '[^' + escapeString(delimiter) + ']+?',
});
}
// Match any characters still remaining.
if (index < str.length) {
path += str.slice(index);
}
// If the path exists, push it onto the end.
if (path) {
tokens.push(path);
}
return tokens;
}
/**
* Escape a regular expression string.
*
* @param {string} str
* @return {string}
*/
function escapeString(str) {
return str.replace(/([.+*?=^!:${}()[\]|/\\])/g, '\\$1');
}
/**
* Escape the capturing group by escaping special characters and meaning.
*
* @param {string} group
* @return {string}
*/
function escapeGroup(group) {
return group.replace(/([=!:$/()])/g, '\\$1');
}
/**
* Attach the keys as a property of the regexp.
*
* @param {!RegExp} re
* @param {Array} keys
* @return {!RegExp}
*/
function attachKeys(re, keys) {
re.keys = keys;
return re;
}
/**
* Get the flags for a regexp from the options.
*
* @param {Object} options
* @return {string}
*/
function flags(options) {
return options && options.sensitive ? '' : 'i';
}
/**
* Pull out keys from a regexp.
*
* @param {!RegExp} path
* @param {!Array} keys
* @return {!RegExp}
*/
function regexpToRegexp(path, keys) {
// Use a negative lookahead to match only capturing groups.
const groups = path.source.match(/\((?!\?)/g);
if (groups) {
for (let i = 0; i < groups.length; i++) {
keys.push({
name: i,
prefix: null,
delimiter: null,
optional: false,
repeat: false,
partial: false,
asterisk: false,
pattern: null,
});
}
}
return attachKeys(path, keys);
}
/**
* Transform an array into a regexp.
*
* @param {!Array} path
* @param {Array} keys
* @param {!Object} options
* @return {!RegExp}
*/
function arrayToRegexp(path, keys, options) {
const parts = [];
for (let i = 0; i < path.length; i++) {
parts.push(pathToRegexp(path[i], keys, options).source);
}
const regexp = new RegExp('(?:' + parts.join('|') + ')', flags(options));
return attachKeys(regexp, keys);
}
/**
* Create a path regexp from string input.
*
* @param {string} path
* @param {!Array} keys
* @param {!Object} options
* @return {!RegExp}
*/
function stringToRegexp(path, keys, options) {
return tokensToRegExp(parse(path, options), keys, options);
}
/**
* Expose a function for taking tokens and returning a RegExp.
*
* @param {!Array} tokens
* @param {(Array|Object)=} keys
* @param {Object=} options
* @return {!RegExp}
*/
function tokensToRegExp(tokens, keys, options) {
if (!Array.isArray(keys)) {
options = /** @type {!Object} */ keys || options;
keys = [];
}
options = options || {};
const strict = options.strict;
const end = options.end !== false;
let route = '';
// Iterate over the tokens and create our regexp string.
for (let i = 0; i < tokens.length; i++) {
const token = tokens[i];
if (typeof token === 'string') {
route += escapeString(token);
} else {
const prefix = escapeString(token.prefix);
let capture = '(?:' + token.pattern + ')';
keys.push(token);
if (token.repeat) {
capture += '(?:' + prefix + capture + ')*';
}
if (token.optional) {
if (!token.partial) {
capture = '(?:' + prefix + '(' + capture + '))?';
} else {
capture = prefix + '(' + capture + ')?';
}
} else {
capture = prefix + '(' + capture + ')';
}
route += capture;
}
}
const delimiter = escapeString(options.delimiter || '/');
const endsWithDelimiter = route.slice(-delimiter.length) === delimiter;
// In non-strict mode we allow a slash at the end of match. If the path to
// match already ends with a slash, we remove it for consistency. The slash
// is valid at the end of a path match, not in the middle. This is important
// in non-ending mode, where "/test/" shouldn't match "/test//route".
if (!strict) {
route =
(endsWithDelimiter ? route.slice(0, -delimiter.length) : route) +
'(?:' +
delimiter +
'(?=$))?';
}
if (end) {
route += '$';
} else {
// In non-ending mode, we need the capturing groups to match as much as
// possible by using a positive lookahead to the end or next path segment.
route += strict && endsWithDelimiter ? '' : '(?=' + delimiter + '|$)';
}
return attachKeys(new RegExp('^' + route, flags(options)), keys);
}
/**
* Normalize the given path string, returning a regular expression.
*
* An empty array can be passed in for the keys, which will hold the
* placeholder key descriptions. For example, using `/user/:id`, `keys` will
* contain `[{ name: 'id', delimiter: '/', optional: false, repeat: false }]`.
*
* @param {(string|RegExp|Array)} path
* @param {(Array|Object)=} keys
* @param {Object=} options
* @return {!RegExp}
*/
export function pathToRegexp(path, keys, options) {
if (!Array.isArray(keys)) {
options = /** @type {!Object} */ keys || options;
keys = [];
}
options = options || {};
if (path instanceof RegExp) {
return regexpToRegexp(path, /** @type {!Array} */ keys);
}
if (Array.isArray(path)) {
return arrayToRegexp(
/** @type {!Array} */ path,
/** @type {!Array} */ keys,
options
);
}
return stringToRegexp(
/** @type {string} */ path,
/** @type {!Array} */ keys,
options
);
}
| 24.453125 | 109 | 0.561406 | 175 | 10 | 0 | 21 | 36 | 0 | 10 | 0 | 0 | 0 | 2 | 14.8 | 2,209 | 0.014033 | 0.016297 | 0 | 0 | 0.000905 | 0 | 0 | 0.258573 | /**
* this file fork from path-to-regexp package v1.8.0
*/
/**
* The main path matching regexp utility.
*
* @type {RegExp}
*/
const PATH_REGEXP = new RegExp(
[
// Match escaped characters that would otherwise appear in future matches.
// This allows the user to escape special characters that won't transform.
'(\\\\.)',
// Match Express-style parameters and un-named parameters with a prefix
// and optional suffixes. Matches appear as:
//
// "/:test(\\d+)?" => ["/", "test", "\d+", undefined, "?", undefined]
// "/route(\\d+)" => [undefined, undefined, undefined, "\d+", undefined, undefined]
// "/*" => ["/", undefined, undefined, undefined, undefined, "*"]
'([\\/.])?(?:(?:\\:(\\w+)(?:\\(((?:\\\\.|[^\\\\()])+)\\))?|\\(((?:\\\\.|[^\\\\()])+)\\))([+*?])?|(\\*))',
].join('|'),
'g'
);
/**
* Parse a string for the raw tokens.
*
* @param {string} str
* @param {Object=} options
* @return {!Array}
*/
/* Example usages of 'parse' are shown below:
tokensToRegExp(parse(path, options), keys, options);
*/
function parse(str, options) {
const tokens = [];
let key = 0;
let index = 0;
let path = '';
const defaultDelimiter = (options && options.delimiter) || '/';
let res;
while ((res = PATH_REGEXP.exec(str)) != null) {
const m = res[0];
const escaped = res[1];
const offset = res.index;
path += str.slice(index, offset);
index = offset + m.length;
// Ignore already escaped sequences.
if (escaped) {
path += escaped[1];
continue;
}
const next = str[index];
const prefix = res[2];
const name = res[3];
const capture = res[4];
const group = res[5];
const modifier = res[6];
const asterisk = res[7];
// Push the current path onto the tokens.
if (path) {
tokens.push(path);
path = '';
}
const partial = prefix != null && next != null && next !== prefix;
const repeat = modifier === '+' || modifier === '*';
const optional = modifier === '?' || modifier === '*';
const delimiter = res[2] || defaultDelimiter;
const pattern = capture || group;
tokens.push({
name: name || key++,
prefix: prefix || '',
delimiter: delimiter,
optional: optional,
repeat: repeat,
partial: partial,
asterisk: !!asterisk,
pattern: pattern
? escapeGroup(pattern)
: asterisk
? '.*'
: '[^' + escapeString(delimiter) + ']+?',
});
}
// Match any characters still remaining.
if (index < str.length) {
path += str.slice(index);
}
// If the path exists, push it onto the end.
if (path) {
tokens.push(path);
}
return tokens;
}
/**
* Escape a regular expression string.
*
* @param {string} str
* @return {string}
*/
/* Example usages of 'escapeString' are shown below:
pattern
? escapeGroup(pattern)
: asterisk
? '.*'
: '[^' + escapeString(delimiter) + ']+?';
route += escapeString(token);
escapeString(token.prefix);
escapeString(options.delimiter || '/');
*/
function escapeString(str) {
return str.replace(/([.+*?=^!:${}()[\]|/\\])/g, '\\$1');
}
/**
* Escape the capturing group by escaping special characters and meaning.
*
* @param {string} group
* @return {string}
*/
/* Example usages of 'escapeGroup' are shown below:
pattern
? escapeGroup(pattern)
: asterisk
? '.*'
: '[^' + escapeString(delimiter) + ']+?';
*/
function escapeGroup(group) {
return group.replace(/([=!:$/()])/g, '\\$1');
}
/**
* Attach the keys as a property of the regexp.
*
* @param {!RegExp} re
* @param {Array} keys
* @return {!RegExp}
*/
/* Example usages of 'attachKeys' are shown below:
attachKeys(path, keys);
attachKeys(regexp, keys);
attachKeys(new RegExp('^' + route, flags(options)), keys);
*/
function attachKeys(re, keys) {
re.keys = keys;
return re;
}
/**
* Get the flags for a regexp from the options.
*
* @param {Object} options
* @return {string}
*/
/* Example usages of 'flags' are shown below:
new RegExp('(?:' + parts.join('|') + ')', flags(options));
attachKeys(new RegExp('^' + route, flags(options)), keys);
*/
function flags(options) {
return options && options.sensitive ? '' : 'i';
}
/**
* Pull out keys from a regexp.
*
* @param {!RegExp} path
* @param {!Array} keys
* @return {!RegExp}
*/
/* Example usages of 'regexpToRegexp' are shown below:
regexpToRegexp(path, * @type {!Array} keys);
*/
function regexpToRegexp(path, keys) {
// Use a negative lookahead to match only capturing groups.
const groups = path.source.match(/\((?!\?)/g);
if (groups) {
for (let i = 0; i < groups.length; i++) {
keys.push({
name: i,
prefix: null,
delimiter: null,
optional: false,
repeat: false,
partial: false,
asterisk: false,
pattern: null,
});
}
}
return attachKeys(path, keys);
}
/**
* Transform an array into a regexp.
*
* @param {!Array} path
* @param {Array} keys
* @param {!Object} options
* @return {!RegExp}
*/
/* Example usages of 'arrayToRegexp' are shown below:
arrayToRegexp(
* @type {!Array} path,
* @type {!Array} keys, options);
*/
function arrayToRegexp(path, keys, options) {
const parts = [];
for (let i = 0; i < path.length; i++) {
parts.push(pathToRegexp(path[i], keys, options).source);
}
const regexp = new RegExp('(?:' + parts.join('|') + ')', flags(options));
return attachKeys(regexp, keys);
}
/**
* Create a path regexp from string input.
*
* @param {string} path
* @param {!Array} keys
* @param {!Object} options
* @return {!RegExp}
*/
/* Example usages of 'stringToRegexp' are shown below:
stringToRegexp(
* @type {string} path,
* @type {!Array} keys, options);
*/
function stringToRegexp(path, keys, options) {
return tokensToRegExp(parse(path, options), keys, options);
}
/**
* Expose a function for taking tokens and returning a RegExp.
*
* @param {!Array} tokens
* @param {(Array|Object)=} keys
* @param {Object=} options
* @return {!RegExp}
*/
/* Example usages of 'tokensToRegExp' are shown below:
tokensToRegExp(parse(path, options), keys, options);
*/
function tokensToRegExp(tokens, keys, options) {
if (!Array.isArray(keys)) {
options = /** @type {!Object} */ keys || options;
keys = [];
}
options = options || {};
const strict = options.strict;
const end = options.end !== false;
let route = '';
// Iterate over the tokens and create our regexp string.
for (let i = 0; i < tokens.length; i++) {
const token = tokens[i];
if (typeof token === 'string') {
route += escapeString(token);
} else {
const prefix = escapeString(token.prefix);
let capture = '(?:' + token.pattern + ')';
keys.push(token);
if (token.repeat) {
capture += '(?:' + prefix + capture + ')*';
}
if (token.optional) {
if (!token.partial) {
capture = '(?:' + prefix + '(' + capture + '))?';
} else {
capture = prefix + '(' + capture + ')?';
}
} else {
capture = prefix + '(' + capture + ')';
}
route += capture;
}
}
const delimiter = escapeString(options.delimiter || '/');
const endsWithDelimiter = route.slice(-delimiter.length) === delimiter;
// In non-strict mode we allow a slash at the end of match. If the path to
// match already ends with a slash, we remove it for consistency. The slash
// is valid at the end of a path match, not in the middle. This is important
// in non-ending mode, where "/test/" shouldn't match "/test//route".
if (!strict) {
route =
(endsWithDelimiter ? route.slice(0, -delimiter.length) : route) +
'(?:' +
delimiter +
'(?=$))?';
}
if (end) {
route += '$';
} else {
// In non-ending mode, we need the capturing groups to match as much as
// possible by using a positive lookahead to the end or next path segment.
route += strict && endsWithDelimiter ? '' : '(?=' + delimiter + '|$)';
}
return attachKeys(new RegExp('^' + route, flags(options)), keys);
}
/**
* Normalize the given path string, returning a regular expression.
*
* An empty array can be passed in for the keys, which will hold the
* placeholder key descriptions. For example, using `/user/:id`, `keys` will
* contain `[{ name: 'id', delimiter: '/', optional: false, repeat: false }]`.
*
* @param {(string|RegExp|Array)} path
* @param {(Array|Object)=} keys
* @param {Object=} options
* @return {!RegExp}
*/
export /* Example usages of 'pathToRegexp' are shown below:
parts.push(pathToRegexp(path[i], keys, options).source);
*/
function pathToRegexp(path, keys, options) {
if (!Array.isArray(keys)) {
options = /** @type {!Object} */ keys || options;
keys = [];
}
options = options || {};
if (path instanceof RegExp) {
return regexpToRegexp(path, /** @type {!Array} */ keys);
}
if (Array.isArray(path)) {
return arrayToRegexp(
/** @type {!Array} */ path,
/** @type {!Array} */ keys,
options
);
}
return stringToRegexp(
/** @type {string} */ path,
/** @type {!Array} */ keys,
options
);
}
|
90adfc80b4d9856dcba679938b524dee8cf37433 | 2,679 | ts | TypeScript | problemset/integer-to-english-words/index.ts | OUDUIDUI/leet-code | 50e61ce16d1c419ccefc075ae9ead721cdd1cdbb | [
"MIT"
] | 6 | 2022-01-17T03:19:56.000Z | 2022-01-17T05:45:39.000Z | problemset/integer-to-english-words/index.ts | OUDUIDUI/leet-code | 50e61ce16d1c419ccefc075ae9ead721cdd1cdbb | [
"MIT"
] | null | null | null | problemset/integer-to-english-words/index.ts | OUDUIDUI/leet-code | 50e61ce16d1c419ccefc075ae9ead721cdd1cdbb | [
"MIT"
] | null | null | null | /**
* 递归
* @desc 时间复杂度 O(1) 空间复杂度 O(1)
* @param num
* @returns
*/
export function numberToWords(num: number): string {
if (num === 0) return 'Zero'
const SINGLES = ['', 'One', 'Two', 'Three', 'Four', 'Five', 'Six', 'Seven', 'Eight', 'Nine']
const TEENS = ['Ten', 'Eleven', 'Twelve', 'Thirteen', 'Fourteen', 'Fifteen', 'Sixteen', 'Seventeen', 'Eighteen', 'Nineteen']
const TENS = ['', 'Ten', 'Twenty', 'Thirty', 'Forty', 'Fifty', 'Sixty', 'Seventy', 'Eighty', 'Ninety']
const THOUSANDS = ['', 'Thousand', 'Million', 'Billion']
const result: string[] = []
for (
let i = 3, unit = 1000000000;
i >= 0;
i--, unit = (unit / 1000) >> 0
) {
const curNum = (num / unit) >> 0
if (curNum !== 0) {
num -= curNum * unit
const cur: string[] = []
dfs(cur, curNum)
cur.push(`${THOUSANDS[i]} `)
result.push(cur.join(''))
}
}
return result.join('').trim()
function dfs(cur: string[], num: number): void {
if (num === 0) return
if (num < 10) {
cur.push(`${SINGLES[num]} `)
}
else if (num < 20) {
cur.push(`${TEENS[num - 10]} `)
}
else if (num < 100) {
cur.push(`${TENS[Math.floor(num / 10)]} `)
dfs(cur, num % 10)
}
else {
cur.push(`${SINGLES[Math.floor(num / 100)]} Hundred `)
dfs(cur, num % 100)
}
}
}
/**
* 迭代
* @desc 时间复杂度 O(1) 空间复杂度 O(1)
* @param num
* @returns
*/
export function numberToWords2(num: number): string {
if (num === 0)
return 'Zero'
const SINGLES = ['', 'One', 'Two', 'Three', 'Four', 'Five', 'Six', 'Seven', 'Eight', 'Nine']
const TEENS = ['Ten', 'Eleven', 'Twelve', 'Thirteen', 'Fourteen', 'Fifteen', 'Sixteen', 'Seventeen', 'Eighteen', 'Nineteen']
const TENS = ['', 'Ten', 'Twenty', 'Thirty', 'Forty', 'Fifty', 'Sixty', 'Seventy', 'Eighty', 'Ninety']
const THOUSANDS = ['', 'Thousand', 'Million', 'Billion']
const result: string[] = []
for (
let i = 3, unit = 1000000000;
i >= 0;
i--, unit = (unit / 1000) >> 0
) {
const curNum = (num / unit) >> 0
if (curNum !== 0) {
num -= curNum * unit
result.push(`${toEnglish(curNum) + THOUSANDS[i]} `)
}
}
return result.join('').trim()
function toEnglish(num: number): string {
const curr = []
const hundred = Math.floor(num / 100)
num %= 100
if (hundred !== 0)
curr.push(`${SINGLES[hundred]} Hundred `)
const ten = Math.floor(num / 10)
if (ten >= 2) {
curr.push(`${TENS[ten]} `)
num %= 10
}
if (num > 0 && num < 10)
curr.push(`${SINGLES[num]} `)
else if (num >= 10)
curr.push(`${TEENS[num - 10]} `)
return curr.join('')
}
}
| 25.273585 | 126 | 0.518104 | 78 | 4 | 0 | 5 | 20 | 0 | 2 | 0 | 12 | 0 | 0 | 26 | 1,025 | 0.00878 | 0.019512 | 0 | 0 | 0 | 0 | 0.413793 | 0.254396 | /**
* 递归
* @desc 时间复杂度 O(1) 空间复杂度 O(1)
* @param num
* @returns
*/
export function numberToWords(num) {
if (num === 0) return 'Zero'
const SINGLES = ['', 'One', 'Two', 'Three', 'Four', 'Five', 'Six', 'Seven', 'Eight', 'Nine']
const TEENS = ['Ten', 'Eleven', 'Twelve', 'Thirteen', 'Fourteen', 'Fifteen', 'Sixteen', 'Seventeen', 'Eighteen', 'Nineteen']
const TENS = ['', 'Ten', 'Twenty', 'Thirty', 'Forty', 'Fifty', 'Sixty', 'Seventy', 'Eighty', 'Ninety']
const THOUSANDS = ['', 'Thousand', 'Million', 'Billion']
const result = []
for (
let i = 3, unit = 1000000000;
i >= 0;
i--, unit = (unit / 1000) >> 0
) {
const curNum = (num / unit) >> 0
if (curNum !== 0) {
num -= curNum * unit
const cur = []
dfs(cur, curNum)
cur.push(`${THOUSANDS[i]} `)
result.push(cur.join(''))
}
}
return result.join('').trim()
/* Example usages of 'dfs' are shown below:
dfs(cur, curNum);
dfs(cur, num % 10);
dfs(cur, num % 100);
*/
function dfs(cur, num) {
if (num === 0) return
if (num < 10) {
cur.push(`${SINGLES[num]} `)
}
else if (num < 20) {
cur.push(`${TEENS[num - 10]} `)
}
else if (num < 100) {
cur.push(`${TENS[Math.floor(num / 10)]} `)
dfs(cur, num % 10)
}
else {
cur.push(`${SINGLES[Math.floor(num / 100)]} Hundred `)
dfs(cur, num % 100)
}
}
}
/**
* 迭代
* @desc 时间复杂度 O(1) 空间复杂度 O(1)
* @param num
* @returns
*/
export function numberToWords2(num) {
if (num === 0)
return 'Zero'
const SINGLES = ['', 'One', 'Two', 'Three', 'Four', 'Five', 'Six', 'Seven', 'Eight', 'Nine']
const TEENS = ['Ten', 'Eleven', 'Twelve', 'Thirteen', 'Fourteen', 'Fifteen', 'Sixteen', 'Seventeen', 'Eighteen', 'Nineteen']
const TENS = ['', 'Ten', 'Twenty', 'Thirty', 'Forty', 'Fifty', 'Sixty', 'Seventy', 'Eighty', 'Ninety']
const THOUSANDS = ['', 'Thousand', 'Million', 'Billion']
const result = []
for (
let i = 3, unit = 1000000000;
i >= 0;
i--, unit = (unit / 1000) >> 0
) {
const curNum = (num / unit) >> 0
if (curNum !== 0) {
num -= curNum * unit
result.push(`${toEnglish(curNum) + THOUSANDS[i]} `)
}
}
return result.join('').trim()
/* Example usages of 'toEnglish' are shown below:
toEnglish(curNum) + THOUSANDS[i];
*/
function toEnglish(num) {
const curr = []
const hundred = Math.floor(num / 100)
num %= 100
if (hundred !== 0)
curr.push(`${SINGLES[hundred]} Hundred `)
const ten = Math.floor(num / 10)
if (ten >= 2) {
curr.push(`${TENS[ten]} `)
num %= 10
}
if (num > 0 && num < 10)
curr.push(`${SINGLES[num]} `)
else if (num >= 10)
curr.push(`${TEENS[num - 10]} `)
return curr.join('')
}
}
|
334799763d7d1337e3c485d09fc1b22e9544bfe9 | 2,905 | ts | TypeScript | src/useContext.ts | Robicue/useContext | 5379d414ef98f85c8bcfb8cbb91011e67cb7a90f | [
"MIT"
] | 1 | 2022-01-29T20:34:18.000Z | 2022-01-29T20:34:18.000Z | src/useContext.ts | Robicue/use-context | 5379d414ef98f85c8bcfb8cbb91011e67cb7a90f | [
"MIT"
] | null | null | null | src/useContext.ts | Robicue/use-context | 5379d414ef98f85c8bcfb8cbb91011e67cb7a90f | [
"MIT"
] | null | null | null | const MAGIC_DATA_TOKEN = "__context_container__";
const VERSION = "1.0.0";
/**
* All the data of our context is stored inside a property with a
* long name that starts and ends with two underscores.
* This is to indicate that the context data should never be accessed directly.
*/
export type Context = { [MAGIC_DATA_TOKEN]: unknown };
/**
* We deliberately did not make the key of type 'string', to encourage the
* use of the createKey. The createKey function ensures a better naming
* convention by splitting the key into 3 parts: namespace, hook name, and
* a name for the state.
*/
export type Key = unknown;
/**
* Holds the created keys to warn about duplications
*/
const usedKeys = new Set<Key>();
/**
* Use this function to create a distinguishable
* key for a contextual state.
*/
export const createKey = (
namespace: string,
hook: string,
name: string
): Key => {
const key = `${namespace}/${hook}/${name}`;
if (usedKeys.has(key)) {
throw new Error(
`The context key '${key}' is already created somewhere else`
);
}
usedKeys.add(key);
return key;
};
/**
* Checks if the provided value is a valid context object.
*/
export const isContext = (value: unknown) => {
return !!(value as Context)[MAGIC_DATA_TOKEN];
};
/**
* Major hook that can be used to:
* - create a new context
* - create a fork of a context
* - get or initialize a contextual state
*/
export const useContext = (context?: Context) => {
let map: Map<Key, unknown>;
if (context) {
map = context[MAGIC_DATA_TOKEN] as Map<Key, unknown>;
if (!map) {
throw "An invalid context object has been provided";
}
} else {
map = new Map();
context = {
[MAGIC_DATA_TOKEN]: map,
__context_version__: VERSION,
} as Context;
}
return {
/**
* The current context object.
*/
context,
/**
* Returns TRUE if the specified key is not used in the context yet.
*/
isAvailable(key: Key) {
return map.has(key);
},
/**
* Accesses the contextual state related to the specified key.
* If the state does not exist yet, the result of the initializer
* will be set and returned.
*/
use<T>(key: Key, initializer?: () => T) {
if (map.has(key)) {
return map.get(key) as T;
}
if (!initializer) {
throw `No context data available for '${key}'`;
}
const value = initializer();
map.set(key, value);
return value;
},
/**
* Makes a fork of the current context.
* The forked context allows you to keep access to the states
* of the current context, but newly initialized states, created
* in the forked context, are not seen by hooks using the current context.
*/
fork() {
return {
...context,
[MAGIC_DATA_TOKEN]: new Map(map),
} as Context;
},
};
};
| 24.618644 | 79 | 0.624441 | 60 | 6 | 0 | 8 | 9 | 1 | 0 | 0 | 8 | 2 | 5 | 9.833333 | 760 | 0.018421 | 0.011842 | 0.001316 | 0.002632 | 0.006579 | 0 | 0.333333 | 0.254669 | const MAGIC_DATA_TOKEN = "__context_container__";
const VERSION = "1.0.0";
/**
* All the data of our context is stored inside a property with a
* long name that starts and ends with two underscores.
* This is to indicate that the context data should never be accessed directly.
*/
export type Context = { [MAGIC_DATA_TOKEN] };
/**
* We deliberately did not make the key of type 'string', to encourage the
* use of the createKey. The createKey function ensures a better naming
* convention by splitting the key into 3 parts: namespace, hook name, and
* a name for the state.
*/
export type Key = unknown;
/**
* Holds the created keys to warn about duplications
*/
const usedKeys = new Set<Key>();
/**
* Use this function to create a distinguishable
* key for a contextual state.
*/
export const createKey = (
namespace,
hook,
name
) => {
const key = `${namespace}/${hook}/${name}`;
if (usedKeys.has(key)) {
throw new Error(
`The context key '${key}' is already created somewhere else`
);
}
usedKeys.add(key);
return key;
};
/**
* Checks if the provided value is a valid context object.
*/
export const isContext = (value) => {
return !!(value as Context)[MAGIC_DATA_TOKEN];
};
/**
* Major hook that can be used to:
* - create a new context
* - create a fork of a context
* - get or initialize a contextual state
*/
export const useContext = (context?) => {
let map;
if (context) {
map = context[MAGIC_DATA_TOKEN] as Map<Key, unknown>;
if (!map) {
throw "An invalid context object has been provided";
}
} else {
map = new Map();
context = {
[MAGIC_DATA_TOKEN]: map,
__context_version__: VERSION,
} as Context;
}
return {
/**
* The current context object.
*/
context,
/**
* Returns TRUE if the specified key is not used in the context yet.
*/
isAvailable(key) {
return map.has(key);
},
/**
* Accesses the contextual state related to the specified key.
* If the state does not exist yet, the result of the initializer
* will be set and returned.
*/
use<T>(key, initializer?) {
if (map.has(key)) {
return map.get(key) as T;
}
if (!initializer) {
throw `No context data available for '${key}'`;
}
const value = initializer();
map.set(key, value);
return value;
},
/**
* Makes a fork of the current context.
* The forked context allows you to keep access to the states
* of the current context, but newly initialized states, created
* in the forked context, are not seen by hooks using the current context.
*/
fork() {
return {
...context,
[MAGIC_DATA_TOKEN]: new Map(map),
} as Context;
},
};
};
|
336571afe07949a5a3bc46e079e37369d88ab971 | 2,314 | ts | TypeScript | src/CitizenIdentificationNumber.ts | HerbertHe/chinese-unique-identification-code | 3c55772af427c7f79b5626034b04e01a665ee70b | [
"MIT"
] | 1 | 2022-02-15T02:36:42.000Z | 2022-02-15T02:36:42.000Z | src/CitizenIdentificationNumber.ts | HerbertHe/chinese-unique-identification-code | 3c55772af427c7f79b5626034b04e01a665ee70b | [
"MIT"
] | null | null | null | src/CitizenIdentificationNumber.ts | HerbertHe/chinese-unique-identification-code | 3c55772af427c7f79b5626034b04e01a665ee70b | [
"MIT"
] | null | null | null | /**
* 公民身份号码校验器返回值类型
* Citizen Identification Number Checker Type
*/
export type CitizenIdentificationNumberCheckerType = [boolean, string]
/**
* 校验码计算器
* @param {string} code 前17位代码
* @returns
*/
const CheckCodeCalculator = (code: string): string => {
const Wi = [7, 9, 10, 5, 8, 4, 2, 1, 6, 3, 7, 9, 10, 5, 8, 4, 2, 1]
const a1s = ["1", "0", "X", "9", "8", "7", "6", "5", "4", "3", "2"]
const a1 =
a1s[
code
.split("")
.map((item) => parseInt(item))
.reduce((pre, curr, idx) => {
return pre + curr * Wi[idx]
}, 0) % 11
]
return a1
}
const IDRegExp = /([0-9]{6})([0-9]{8})([0-9]{3})([0-9|X]{1})/
/**
* 公民身份号码校验器
* Citizen Identification Number Checker
*
* @param {string} id 公民身份号码
* @returns
*
* @description 标准号: GB 11643-1999
* @link http://openstd.samr.gov.cn/bzgk/gb/newGbInfo?hcno=080D6FBF2BB468F9007657F26D60013E
*/
export const CitizenIdentificationNumberChecker = (
id: string
): CitizenIdentificationNumberCheckerType => {
id = id.toUpperCase()
// check if length of id !== 18
if (id.length !== 18) {
return [false, id]
}
if (!IDRegExp.test(id)) {
return [false, id]
}
if (CheckCodeCalculator(id.substring(0, 17)) === id.substring(17)) {
return [true, id]
} else {
return [false, id]
}
}
export type CitizenIdentificationNumberInformationExtractorDetailsType = [
string,
string,
string,
string
]
export type CitizenIdentificationNumberInformationExtractorType = [
boolean,
CitizenIdentificationNumberInformationExtractorDetailsType
]
/**
* 公民身份号码信息提取器
* Citizen Identification Number Checker
*
* @param {string} id 公民身份号码
* @returns
*
* @description 标准号: GB 11643-1999
* @link http://openstd.samr.gov.cn/bzgk/gb/newGbInfo?hcno=080D6FBF2BB468F9007657F26D60013E
*/
export const CitizenIdentificationNumberInformationExtractor = (
id: string
): CitizenIdentificationNumberInformationExtractorType => {
if (!CitizenIdentificationNumberChecker(id)[0]) {
return [false, null]
}
const [raw, addr, db, or] = IDRegExp.exec(id)
const gender = parseInt(or) % 2 === 0 ? "女" : "男"
return [true, [addr, db, gender, raw]]
}
| 24.104167 | 91 | 0.608038 | 52 | 5 | 0 | 7 | 9 | 0 | 2 | 0 | 11 | 3 | 0 | 6.4 | 851 | 0.014101 | 0.010576 | 0 | 0.003525 | 0 | 0 | 0.52381 | 0.243103 | /**
* 公民身份号码校验器返回值类型
* Citizen Identification Number Checker Type
*/
export type CitizenIdentificationNumberCheckerType = [boolean, string]
/**
* 校验码计算器
* @param {string} code 前17位代码
* @returns
*/
/* Example usages of 'CheckCodeCalculator' are shown below:
CheckCodeCalculator(id.substring(0, 17)) === id.substring(17);
*/
const CheckCodeCalculator = (code) => {
const Wi = [7, 9, 10, 5, 8, 4, 2, 1, 6, 3, 7, 9, 10, 5, 8, 4, 2, 1]
const a1s = ["1", "0", "X", "9", "8", "7", "6", "5", "4", "3", "2"]
const a1 =
a1s[
code
.split("")
.map((item) => parseInt(item))
.reduce((pre, curr, idx) => {
return pre + curr * Wi[idx]
}, 0) % 11
]
return a1
}
const IDRegExp = /([0-9]{6})([0-9]{8})([0-9]{3})([0-9|X]{1})/
/**
* 公民身份号码校验器
* Citizen Identification Number Checker
*
* @param {string} id 公民身份号码
* @returns
*
* @description 标准号: GB 11643-1999
* @link http://openstd.samr.gov.cn/bzgk/gb/newGbInfo?hcno=080D6FBF2BB468F9007657F26D60013E
*/
export /* Example usages of 'CitizenIdentificationNumberChecker' are shown below:
!CitizenIdentificationNumberChecker(id)[0];
*/
const CitizenIdentificationNumberChecker = (
id
) => {
id = id.toUpperCase()
// check if length of id !== 18
if (id.length !== 18) {
return [false, id]
}
if (!IDRegExp.test(id)) {
return [false, id]
}
if (CheckCodeCalculator(id.substring(0, 17)) === id.substring(17)) {
return [true, id]
} else {
return [false, id]
}
}
export type CitizenIdentificationNumberInformationExtractorDetailsType = [
string,
string,
string,
string
]
export type CitizenIdentificationNumberInformationExtractorType = [
boolean,
CitizenIdentificationNumberInformationExtractorDetailsType
]
/**
* 公民身份号码信息提取器
* Citizen Identification Number Checker
*
* @param {string} id 公民身份号码
* @returns
*
* @description 标准号: GB 11643-1999
* @link http://openstd.samr.gov.cn/bzgk/gb/newGbInfo?hcno=080D6FBF2BB468F9007657F26D60013E
*/
export const CitizenIdentificationNumberInformationExtractor = (
id
) => {
if (!CitizenIdentificationNumberChecker(id)[0]) {
return [false, null]
}
const [raw, addr, db, or] = IDRegExp.exec(id)
const gender = parseInt(or) % 2 === 0 ? "女" : "男"
return [true, [addr, db, gender, raw]]
}
|
33b7ca5e8483474f1e5fef02a305e0919a37eae4 | 2,508 | ts | TypeScript | src/utils/SubscriberCountSort.ts | TaiwanVtuberData/TaiwanVtuberData-Preact | 69377d533a0aaff50e74cbf7bcad0de5524c18dc | [
"BSD-3-Clause"
] | null | null | null | src/utils/SubscriberCountSort.ts | TaiwanVtuberData/TaiwanVtuberData-Preact | 69377d533a0aaff50e74cbf7bcad0de5524c18dc | [
"BSD-3-Clause"
] | 7 | 2022-03-24T11:44:01.000Z | 2022-03-24T12:03:29.000Z | src/utils/SubscriberCountSort.ts | TaiwanVtuberData/TaiwanVtuberData-Preact | 69377d533a0aaff50e74cbf7bcad0de5524c18dc | [
"BSD-3-Clause"
] | null | null | null | export type SortMethod = 'YouTube+Twitch' | 'YouTube' | 'Twitch';
const YouTubeSubscriberCountDescendingSort = <
T extends { hasYouTube: boolean; YouTubeSubscriberCount?: number }
>(
rowA: T,
rowB: T
): number => {
const aExist = rowA.hasYouTube;
const bExist = rowB.hasYouTube;
if (!aExist && !bExist) return 0;
if (!bExist) return -1;
if (!aExist) return 1;
const aCount = rowA.YouTubeSubscriberCount;
const bCount = rowB.YouTubeSubscriberCount;
if (aCount === undefined && bCount === undefined) return 0;
if (bCount === undefined) return -1;
if (aCount === undefined) return 1;
if (aCount > bCount) return -1;
if (bCount > aCount) return 1;
return 0;
};
const TwitchFollowerCountDescendingSort = <
T extends { hasTwitch: boolean; TwitchFollowerCount: number }
>(
rowA: T,
rowB: T
): number => {
const aExist = rowA.hasTwitch;
const bExist = rowB.hasTwitch;
if (!aExist && !bExist) return 0;
if (!bExist) return -1;
if (!aExist) return 1;
const aCount = rowA.TwitchFollowerCount;
const bCount = rowB.TwitchFollowerCount;
if (aCount > bCount) return -1;
if (bCount > aCount) return 1;
return 0;
};
// TODO: Merge the logic of descending and ascending functions
export const YouTubeSubscriberCountPlusTwitchFollowerCountDescendingSort = <
T extends { YouTubeSubscriberCount?: number; TwitchFollowerCount?: number }
>(
rowA: T,
rowB: T
): number => {
const aCount =
(rowA.YouTubeSubscriberCount ?? 0) + (rowA.TwitchFollowerCount ?? 0);
const bCount =
(rowB.YouTubeSubscriberCount ?? 0) + (rowB.TwitchFollowerCount ?? 0);
if (aCount > bCount) return -1;
if (bCount > aCount) return 1;
return 0;
};
export const YouTubeSubscriberCountPlusTwitchFollowerCountAscendingSort = <
T extends { YouTubeSubscriberCount?: number; TwitchFollowerCount?: number }
>(
rowA: T,
rowB: T
): number => {
const aCount =
(rowA.YouTubeSubscriberCount ?? 0) + (rowA.TwitchFollowerCount ?? 0);
const bCount =
(rowB.YouTubeSubscriberCount ?? 0) + (rowB.TwitchFollowerCount ?? 0);
if (aCount > bCount) return 1;
if (bCount > aCount) return -1;
return 0;
};
export const SubscriberCountDescendingSort = (sortMethod: SortMethod) => {
switch (sortMethod) {
case 'YouTube+Twitch':
return YouTubeSubscriberCountPlusTwitchFollowerCountDescendingSort;
case 'YouTube':
return YouTubeSubscriberCountDescendingSort;
case 'Twitch':
return TwitchFollowerCountDescendingSort;
}
};
| 23.660377 | 77 | 0.691786 | 76 | 5 | 0 | 9 | 17 | 0 | 0 | 0 | 12 | 1 | 0 | 9 | 766 | 0.018277 | 0.022193 | 0 | 0.001305 | 0 | 0 | 0.387097 | 0.286938 | export type SortMethod = 'YouTube+Twitch' | 'YouTube' | 'Twitch';
/* Example usages of 'YouTubeSubscriberCountDescendingSort' are shown below:
return YouTubeSubscriberCountDescendingSort;
*/
const YouTubeSubscriberCountDescendingSort = <
T extends { hasYouTube; YouTubeSubscriberCount? }
>(
rowA,
rowB
) => {
const aExist = rowA.hasYouTube;
const bExist = rowB.hasYouTube;
if (!aExist && !bExist) return 0;
if (!bExist) return -1;
if (!aExist) return 1;
const aCount = rowA.YouTubeSubscriberCount;
const bCount = rowB.YouTubeSubscriberCount;
if (aCount === undefined && bCount === undefined) return 0;
if (bCount === undefined) return -1;
if (aCount === undefined) return 1;
if (aCount > bCount) return -1;
if (bCount > aCount) return 1;
return 0;
};
/* Example usages of 'TwitchFollowerCountDescendingSort' are shown below:
return TwitchFollowerCountDescendingSort;
*/
const TwitchFollowerCountDescendingSort = <
T extends { hasTwitch; TwitchFollowerCount }
>(
rowA,
rowB
) => {
const aExist = rowA.hasTwitch;
const bExist = rowB.hasTwitch;
if (!aExist && !bExist) return 0;
if (!bExist) return -1;
if (!aExist) return 1;
const aCount = rowA.TwitchFollowerCount;
const bCount = rowB.TwitchFollowerCount;
if (aCount > bCount) return -1;
if (bCount > aCount) return 1;
return 0;
};
// TODO: Merge the logic of descending and ascending functions
export /* Example usages of 'YouTubeSubscriberCountPlusTwitchFollowerCountDescendingSort' are shown below:
return YouTubeSubscriberCountPlusTwitchFollowerCountDescendingSort;
*/
const YouTubeSubscriberCountPlusTwitchFollowerCountDescendingSort = <
T extends { YouTubeSubscriberCount?; TwitchFollowerCount? }
>(
rowA,
rowB
) => {
const aCount =
(rowA.YouTubeSubscriberCount ?? 0) + (rowA.TwitchFollowerCount ?? 0);
const bCount =
(rowB.YouTubeSubscriberCount ?? 0) + (rowB.TwitchFollowerCount ?? 0);
if (aCount > bCount) return -1;
if (bCount > aCount) return 1;
return 0;
};
export const YouTubeSubscriberCountPlusTwitchFollowerCountAscendingSort = <
T extends { YouTubeSubscriberCount?; TwitchFollowerCount? }
>(
rowA,
rowB
) => {
const aCount =
(rowA.YouTubeSubscriberCount ?? 0) + (rowA.TwitchFollowerCount ?? 0);
const bCount =
(rowB.YouTubeSubscriberCount ?? 0) + (rowB.TwitchFollowerCount ?? 0);
if (aCount > bCount) return 1;
if (bCount > aCount) return -1;
return 0;
};
export const SubscriberCountDescendingSort = (sortMethod) => {
switch (sortMethod) {
case 'YouTube+Twitch':
return YouTubeSubscriberCountPlusTwitchFollowerCountDescendingSort;
case 'YouTube':
return YouTubeSubscriberCountDescendingSort;
case 'Twitch':
return TwitchFollowerCountDescendingSort;
}
};
|
33dc4b394041366ec0b4848922d93d6a79e678f8 | 1,977 | ts | TypeScript | packages/parser/src/utils.ts | dopey2/math-x-js | 31350349370b5333f24d3f5e9255f045becd3604 | [
"MIT"
] | null | null | null | packages/parser/src/utils.ts | dopey2/math-x-js | 31350349370b5333f24d3f5e9255f045becd3604 | [
"MIT"
] | 1 | 2022-03-21T18:15:13.000Z | 2022-03-27T12:48:37.000Z | packages/parser/src/utils.ts | dopey2/math-x-js | 31350349370b5333f24d3f5e9255f045becd3604 | [
"MIT"
] | null | null | null | export const isNumber = (n: string) => !isNaN(Number(n));
export const isOperator = (c: string) => {
return ["+", "-", "*", ":", "/", "^"].indexOf(c) !== -1;
};
export const isInParenthesis = (symbols: string[]) => {
const first = symbols[0];
const last = symbols[symbols.length - 1];
const HAS_PARENTHESIS = first === "(" && last === ")";
let numberOfParenthesis = 0;
let depth = 0;
for(let i = 0; i < symbols.length && HAS_PARENTHESIS; i++) {
let char = symbols[i];
if(char === "(") {
if(depth === 0) {
numberOfParenthesis++;
}
depth++;
}
if(char === ")") {
depth--;
}
}
return numberOfParenthesis === 1;
};
export const isInBracket = (symbols: string[]) => {
const first = symbols[0];
const last = symbols[symbols.length - 1];
const HAS_BRACKET = first === "{" && last === "}";
let numberOfBracket = 0;
let depth = 0;
for(let i = 0; i < symbols.length && HAS_BRACKET; i++) {
let char = symbols[i];
if(char === "{") {
if(depth === 0) {
numberOfBracket++;
}
depth++;
}
if(char === "}") {
depth--;
}
}
return numberOfBracket === 1;
};
export const getParenthesisContent = (symbols: string[]) => {
return symbols.slice(1, symbols.length - 1);
};
export const splitStringExpressionToSymbols = (expression: string) => {
expression = expression.split("").filter((c)=>c !== " ").join("");
let symbols: string[] = [];
for(let i = 0; i < expression.length; i++) {
const symbolN1 = symbols[symbols.length - 1];
const char = expression[i];
if(symbolN1 && isNumber(symbolN1) && isNumber(char)) {
symbols[symbols.length - 1] = symbolN1 + char;
} else {
symbols.push(expression[i]);
}
}
return symbols;
};
| 24.407407 | 71 | 0.499241 | 61 | 7 | 0 | 7 | 24 | 0 | 1 | 0 | 7 | 0 | 0 | 7.428571 | 523 | 0.026769 | 0.045889 | 0 | 0 | 0 | 0 | 0.184211 | 0.382658 | export /* Example usages of 'isNumber' are shown below:
symbolN1 && isNumber(symbolN1) && isNumber(char);
*/
const isNumber = (n) => !isNaN(Number(n));
export const isOperator = (c) => {
return ["+", "-", "*", ":", "/", "^"].indexOf(c) !== -1;
};
export const isInParenthesis = (symbols) => {
const first = symbols[0];
const last = symbols[symbols.length - 1];
const HAS_PARENTHESIS = first === "(" && last === ")";
let numberOfParenthesis = 0;
let depth = 0;
for(let i = 0; i < symbols.length && HAS_PARENTHESIS; i++) {
let char = symbols[i];
if(char === "(") {
if(depth === 0) {
numberOfParenthesis++;
}
depth++;
}
if(char === ")") {
depth--;
}
}
return numberOfParenthesis === 1;
};
export const isInBracket = (symbols) => {
const first = symbols[0];
const last = symbols[symbols.length - 1];
const HAS_BRACKET = first === "{" && last === "}";
let numberOfBracket = 0;
let depth = 0;
for(let i = 0; i < symbols.length && HAS_BRACKET; i++) {
let char = symbols[i];
if(char === "{") {
if(depth === 0) {
numberOfBracket++;
}
depth++;
}
if(char === "}") {
depth--;
}
}
return numberOfBracket === 1;
};
export const getParenthesisContent = (symbols) => {
return symbols.slice(1, symbols.length - 1);
};
export const splitStringExpressionToSymbols = (expression) => {
expression = expression.split("").filter((c)=>c !== " ").join("");
let symbols = [];
for(let i = 0; i < expression.length; i++) {
const symbolN1 = symbols[symbols.length - 1];
const char = expression[i];
if(symbolN1 && isNumber(symbolN1) && isNumber(char)) {
symbols[symbols.length - 1] = symbolN1 + char;
} else {
symbols.push(expression[i]);
}
}
return symbols;
};
|
181ec44034d7ff44d9293788b657b1a2036d874b | 3,086 | ts | TypeScript | packages/core/src/Validator.ts | Bewond/cloudshape | 7c1715b8e292e31c443fca0101031850c1f9497b | [
"Apache-2.0"
] | 1 | 2022-03-22T23:43:59.000Z | 2022-03-22T23:43:59.000Z | packages/core/src/Validator.ts | Bewond/cloudshape | 7c1715b8e292e31c443fca0101031850c1f9497b | [
"Apache-2.0"
] | null | null | null | packages/core/src/Validator.ts | Bewond/cloudshape | 7c1715b8e292e31c443fca0101031850c1f9497b | [
"Apache-2.0"
] | null | null | null | type InstanceType = "object" | "array" | "boolean" | "number" | "string";
export interface ValidationError {
/**
* Schema keyword.
*/
keyword: string;
/**
* Schema location.
*/
location: string;
/**
* Error message.
*/
message: string;
}
export interface ValidationResult {
/**
* Validation test result.
*/
valid: boolean;
/**
* Any validation test errors.
*/
errors: ValidationError[];
}
/**
* @summary Subset of JSON Type Definition.
*
* @see https://ajv.js.org/json-type-definition.html
*/
export interface Schema {
type?: InstanceType;
properties?: Record<string, Schema>;
}
/**
* @summary Schema-based data validator.
*/
export class Validator {
constructor(private readonly schema: Schema) {}
/**
* Performs the instance validation test based on the provided schema.
* @param instance the instance to validate.
* @returns result of validation test.
*/
// eslint-disable-next-line @typescript-eslint/no-explicit-any
public test(instance: any): ValidationResult {
return this.validate(instance, this.schema, "#");
}
// eslint-disable-next-line @typescript-eslint/no-explicit-any
private validate(instance: any, schema: Schema, location: string): ValidationResult {
const instanceType = this.processInstance(instance);
const { type: $type, properties: $properties } = schema;
const errors: ValidationError[] = [];
// type
if ($type && $type !== instanceType) {
errors.push({
keyword: "type",
location: `${location}/type`,
message: `Instance type "${instanceType}" is invalid. Expected "${$type}".`,
});
}
// properties
if ($properties) {
for (const key in $properties) {
if (key in instance) {
const result = this.validate(
instance[key],
$properties[key] ?? {},
`${location}/properties`
);
if (!result.valid) {
errors.push(
{
keyword: "properties",
location: `${location}/properties`,
message: `Property "${key}" does not match schema.`,
},
...result.errors
);
}
} else {
errors.push({
keyword: "properties",
location: `${location}/properties`,
message: `Instance does not have required property "${key}".`,
});
}
}
}
return {
valid: errors.length === 0,
errors: errors,
};
}
// eslint-disable-next-line @typescript-eslint/no-explicit-any
private processInstance(instance: any): InstanceType {
const rawType = typeof instance;
switch (rawType) {
case "boolean":
case "number":
case "string":
return rawType;
case "object":
if (Array.isArray(instance)) return "array";
else return "object";
default:
// undefined, bigint, function, symbol
throw new Error(`Instances of "${rawType}" type are not supported.`);
}
}
}
| 24.492063 | 87 | 0.575502 | 77 | 4 | 0 | 6 | 5 | 7 | 2 | 3 | 6 | 5 | 1 | 13.5 | 715 | 0.013986 | 0.006993 | 0.00979 | 0.006993 | 0.001399 | 0.136364 | 0.272727 | 0.234698 | type InstanceType = "object" | "array" | "boolean" | "number" | "string";
export interface ValidationError {
/**
* Schema keyword.
*/
keyword;
/**
* Schema location.
*/
location;
/**
* Error message.
*/
message;
}
export interface ValidationResult {
/**
* Validation test result.
*/
valid;
/**
* Any validation test errors.
*/
errors;
}
/**
* @summary Subset of JSON Type Definition.
*
* @see https://ajv.js.org/json-type-definition.html
*/
export interface Schema {
type?;
properties?;
}
/**
* @summary Schema-based data validator.
*/
export class Validator {
constructor(private readonly schema) {}
/**
* Performs the instance validation test based on the provided schema.
* @param instance the instance to validate.
* @returns result of validation test.
*/
// eslint-disable-next-line @typescript-eslint/no-explicit-any
public test(instance) {
return this.validate(instance, this.schema, "#");
}
// eslint-disable-next-line @typescript-eslint/no-explicit-any
private validate(instance, schema, location) {
const instanceType = this.processInstance(instance);
const { type: $type, properties: $properties } = schema;
const errors = [];
// type
if ($type && $type !== instanceType) {
errors.push({
keyword: "type",
location: `${location}/type`,
message: `Instance type "${instanceType}" is invalid. Expected "${$type}".`,
});
}
// properties
if ($properties) {
for (const key in $properties) {
if (key in instance) {
const result = this.validate(
instance[key],
$properties[key] ?? {},
`${location}/properties`
);
if (!result.valid) {
errors.push(
{
keyword: "properties",
location: `${location}/properties`,
message: `Property "${key}" does not match schema.`,
},
...result.errors
);
}
} else {
errors.push({
keyword: "properties",
location: `${location}/properties`,
message: `Instance does not have required property "${key}".`,
});
}
}
}
return {
valid: errors.length === 0,
errors: errors,
};
}
// eslint-disable-next-line @typescript-eslint/no-explicit-any
private processInstance(instance) {
const rawType = typeof instance;
switch (rawType) {
case "boolean":
case "number":
case "string":
return rawType;
case "object":
if (Array.isArray(instance)) return "array";
else return "object";
default:
// undefined, bigint, function, symbol
throw new Error(`Instances of "${rawType}" type are not supported.`);
}
}
}
|
1829e369e402ab188fbc3b27d2b646a8fd372f10 | 2,519 | ts | TypeScript | libs/amyr-ts-lib/src/lib/libs/tsmt/math/prime-factorization.ts | theAlgorithmist/AMYR | db4141d7e545b94a5c98fc5430a065e2ba229e75 | [
"Apache-2.0"
] | 3 | 2022-01-17T21:31:47.000Z | 2022-03-04T20:16:21.000Z | libs/amyr-ts-lib/src/lib/libs/tsmt/math/prime-factorization.ts | theAlgorithmist/AMYR | db4141d7e545b94a5c98fc5430a065e2ba229e75 | [
"Apache-2.0"
] | null | null | null | libs/amyr-ts-lib/src/lib/libs/tsmt/math/prime-factorization.ts | theAlgorithmist/AMYR | db4141d7e545b94a5c98fc5430a065e2ba229e75 | [
"Apache-2.0"
] | null | null | null | /**
* Copyright 2016 Jim Armstrong (www.algorithmist.net)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/**
* AMYR Library: A simple, prime factorization, suitable for modest-size, positive integers.
*
* @author Jim Armstrong (https://www.linkedin.com/in/jimarmstrong/)
*
* @version 1.0
*/
export class TSMT$PrimeFactorization
{
protected _isFinished: boolean; // true if procedure finished
constructor()
{
this._isFinished = false;
}
/**
* Return an array of prime factors of a positive integer or empty array for invalid input; {n} is rounded and the
* abs. value is used as the number to factorize
*
* @param {number} n Integer whose prime factorization is desired (this method is not recommended for very large integers)
*/
public factorize(n: number): Array<number>
{
if (isNaN(n) && !isFinite(n)) return [];
n = Math.abs(Math.round(n));
// some simple cases ... always make your life easy :)
const arg: number = Math.floor(n);
if (arg === 0) return [0];
if (arg === 1) return [1];
if (arg === 2) return [2];
const primes: Array<number> = new Array<number>();
this._isFinished = false;
this.__factors(arg, 2, primes);
return primes.length == 0 ? [arg] : primes;
}
protected __factors(n: number, start: number, primes: Array<number>): void
{
let c: number;
for (c=start; c <=n+1; ++c)
{
if (this._isFinished) return;
if (n%c == 0 && this.__isPrime(c))
{
primes.push(c);
const next: number = n/c;
if (next > 1)
{
this.__factors(next, c, primes);
}
else
{
this._isFinished = true;
return;
}
}
}
}
protected __isPrime(n: number): boolean
{
if (n === 2) return true;
const upper: number = Math.floor( Math.sqrt(n)+1 );
let i: number;
for (i = 2; i <= upper; ++i) {
if (n%i == 0) return false;
}
return true;
}
}
| 25.19 | 124 | 0.614133 | 53 | 4 | 0 | 5 | 6 | 1 | 2 | 0 | 16 | 1 | 0 | 9.25 | 712 | 0.01264 | 0.008427 | 0.001404 | 0.001404 | 0 | 0 | 1 | 0.228641 | /**
* Copyright 2016 Jim Armstrong (www.algorithmist.net)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/**
* AMYR Library: A simple, prime factorization, suitable for modest-size, positive integers.
*
* @author Jim Armstrong (https://www.linkedin.com/in/jimarmstrong/)
*
* @version 1.0
*/
export class TSMT$PrimeFactorization
{
protected _isFinished; // true if procedure finished
constructor()
{
this._isFinished = false;
}
/**
* Return an array of prime factors of a positive integer or empty array for invalid input; {n} is rounded and the
* abs. value is used as the number to factorize
*
* @param {number} n Integer whose prime factorization is desired (this method is not recommended for very large integers)
*/
public factorize(n)
{
if (isNaN(n) && !isFinite(n)) return [];
n = Math.abs(Math.round(n));
// some simple cases ... always make your life easy :)
const arg = Math.floor(n);
if (arg === 0) return [0];
if (arg === 1) return [1];
if (arg === 2) return [2];
const primes = new Array<number>();
this._isFinished = false;
this.__factors(arg, 2, primes);
return primes.length == 0 ? [arg] : primes;
}
protected __factors(n, start, primes)
{
let c;
for (c=start; c <=n+1; ++c)
{
if (this._isFinished) return;
if (n%c == 0 && this.__isPrime(c))
{
primes.push(c);
const next = n/c;
if (next > 1)
{
this.__factors(next, c, primes);
}
else
{
this._isFinished = true;
return;
}
}
}
}
protected __isPrime(n)
{
if (n === 2) return true;
const upper = Math.floor( Math.sqrt(n)+1 );
let i;
for (i = 2; i <= upper; ++i) {
if (n%i == 0) return false;
}
return true;
}
}
|
0d6ff85b4c9ecced4d023be295e4e39e2a04cbec | 1,834 | ts | TypeScript | src/index.ts | lucamattiazzi/off-centered-pie | e0e2a156a4580aad6f1ad72370e295fa8f8aba6d | [
"MIT"
] | null | null | null | src/index.ts | lucamattiazzi/off-centered-pie | e0e2a156a4580aad6f1ad72370e295fa8f8aba6d | [
"MIT"
] | 4 | 2022-02-22T09:09:02.000Z | 2022-02-22T09:13:06.000Z | src/index.ts | lucamattiazzi/off-centered-pie | e0e2a156a4580aad6f1ad72370e295fa8f8aba6d | [
"MIT"
] | null | null | null | export interface Slice {
center: number[]
alpha: number
beta: number
}
function sum(values: number[]): number {
return values.reduce((a, v) => a + v, 0)
}
function computeArea (slice: Slice, radius: number): number {
const angle = Math.abs(slice.beta - slice.alpha)
const ax = slice.center[0]
const ay = slice.center[1]
const bx = radius * Math.cos(slice.alpha)
const by = radius * Math.sin(slice.alpha)
const cx = radius * Math.cos(slice.beta)
const cy = radius * Math.sin(slice.beta)
const sectorArea = angle * (radius ** 2) / 2
const arcArea = sectorArea - (Math.sin(angle) * radius ** 2) / 2
const triangleArea = (ax * (by - cy) + bx * (cy - ay) + cx * (ay - by)) / 2
return arcArea + triangleArea
}
function getAngle (center: number[], radius: number, alpha: number, part: number): number {
const expectedArea = part * Math.PI * radius ** 2
let angle = part * Math.PI * 2
let area = 0
let iterations = 0
let error = Infinity
while (true) {
const slice = {
center,
alpha,
beta: alpha + angle
}
area = computeArea(slice, radius)
error = Math.abs(expectedArea - area) / expectedArea
if (error < 0.01 || iterations > 100) break
const delta = area < expectedArea ? error / Math.PI : -error / Math.PI
angle += delta
iterations++
}
return angle
}
export function buildSlices (center: number[], radius: number, values: number[]): Slice[] {
const normalized = values.map(v => v / sum(values))
const slices = normalized.reduce<Slice[]>((acc, n, idx) => {
const alpha = acc[idx - 1]?.beta ?? 0
const angle = getAngle(center, radius, alpha, n)
const beta = alpha + (idx === normalized.length - 1 ? 2 * Math.PI - alpha : angle)
const slice = { alpha, beta, center }
return [...acc, slice]
}, [])
return slices
}
| 30.566667 | 91 | 0.627045 | 53 | 7 | 0 | 16 | 23 | 3 | 3 | 0 | 15 | 1 | 0 | 6.714286 | 555 | 0.041441 | 0.041441 | 0.005405 | 0.001802 | 0 | 0 | 0.306122 | 0.405732 | export interface Slice {
center
alpha
beta
}
/* Example usages of 'sum' are shown below:
v / sum(values);
*/
function sum(values) {
return values.reduce((a, v) => a + v, 0)
}
/* Example usages of 'computeArea' are shown below:
area = computeArea(slice, radius);
*/
function computeArea (slice, radius) {
const angle = Math.abs(slice.beta - slice.alpha)
const ax = slice.center[0]
const ay = slice.center[1]
const bx = radius * Math.cos(slice.alpha)
const by = radius * Math.sin(slice.alpha)
const cx = radius * Math.cos(slice.beta)
const cy = radius * Math.sin(slice.beta)
const sectorArea = angle * (radius ** 2) / 2
const arcArea = sectorArea - (Math.sin(angle) * radius ** 2) / 2
const triangleArea = (ax * (by - cy) + bx * (cy - ay) + cx * (ay - by)) / 2
return arcArea + triangleArea
}
/* Example usages of 'getAngle' are shown below:
getAngle(center, radius, alpha, n);
*/
function getAngle (center, radius, alpha, part) {
const expectedArea = part * Math.PI * radius ** 2
let angle = part * Math.PI * 2
let area = 0
let iterations = 0
let error = Infinity
while (true) {
const slice = {
center,
alpha,
beta: alpha + angle
}
area = computeArea(slice, radius)
error = Math.abs(expectedArea - area) / expectedArea
if (error < 0.01 || iterations > 100) break
const delta = area < expectedArea ? error / Math.PI : -error / Math.PI
angle += delta
iterations++
}
return angle
}
export function buildSlices (center, radius, values) {
const normalized = values.map(v => v / sum(values))
const slices = normalized.reduce<Slice[]>((acc, n, idx) => {
const alpha = acc[idx - 1]?.beta ?? 0
const angle = getAngle(center, radius, alpha, n)
const beta = alpha + (idx === normalized.length - 1 ? 2 * Math.PI - alpha : angle)
const slice = { alpha, beta, center }
return [...acc, slice]
}, [])
return slices
}
|
0db5fc4d6c0acc5ca993426ff909b7fa849baeca | 1,755 | ts | TypeScript | packages/shared-utils/src/backend.ts | CyberFlameGO/devtools | 328b52e10d36f929d7dfd47a67210b8f73d44578 | [
"MIT"
] | 1 | 2022-03-14T03:23:27.000Z | 2022-03-14T03:23:27.000Z | packages/shared-utils/src/backend.ts | CyberFlameGO/devtools | 328b52e10d36f929d7dfd47a67210b8f73d44578 | [
"MIT"
] | null | null | null | packages/shared-utils/src/backend.ts | CyberFlameGO/devtools | 328b52e10d36f929d7dfd47a67210b8f73d44578 | [
"MIT"
] | null | null | null | export const backendInjections = {
instanceMap: new Map(),
isVueInstance: (() => false) as ((value: any) => boolean),
getCustomInstanceDetails: (() => ({})) as ((instance: any) => any),
getCustomObjectDetails: (() => undefined) as (value: any, proto: string) => any,
}
export function getInstanceMap () {
return backendInjections.instanceMap
}
export function getCustomInstanceDetails (instance) {
return backendInjections.getCustomInstanceDetails(instance)
}
export function getCustomObjectDetails (value, proto: string) {
return backendInjections.getCustomObjectDetails(value, proto)
}
export function isVueInstance (value) {
return backendInjections.isVueInstance(value)
}
// @TODO refactor
export function getCustomRouterDetails (router) {
return {
_custom: {
type: 'router',
display: 'VueRouter',
value: {
options: router.options,
currentRoute: router.currentRoute,
},
fields: {
abstract: true,
},
},
}
}
// @TODO refactor
export function getCustomStoreDetails (store) {
return {
_custom: {
type: 'store',
display: 'Store',
value: {
state: store.state,
getters: getCatchedGetters(store),
},
fields: {
abstract: true,
},
},
}
}
// @TODO refactor
export function getCatchedGetters (store) {
const getters = {}
const origGetters = store.getters || {}
const keys = Object.keys(origGetters)
for (let i = 0; i < keys.length; i++) {
const key = keys[i]
Object.defineProperty(getters, key, {
enumerable: true,
get: () => {
try {
return origGetters[key]
} catch (e) {
return e
}
},
})
}
return getters
}
| 21.9375 | 82 | 0.617664 | 67 | 11 | 0 | 7 | 6 | 0 | 4 | 5 | 3 | 0 | 3 | 5 | 447 | 0.040268 | 0.013423 | 0 | 0 | 0.006711 | 0.208333 | 0.125 | 0.304666 | export const backendInjections = {
instanceMap: new Map(),
isVueInstance: (() => false) as ((value) => boolean),
getCustomInstanceDetails: (() => ({})) as ((instance) => any),
getCustomObjectDetails: (() => undefined) as (value, proto) => any,
}
export function getInstanceMap () {
return backendInjections.instanceMap
}
export /* Example usages of 'getCustomInstanceDetails' are shown below:
;
backendInjections.getCustomInstanceDetails(instance);
*/
function getCustomInstanceDetails (instance) {
return backendInjections.getCustomInstanceDetails(instance)
}
export /* Example usages of 'getCustomObjectDetails' are shown below:
;
backendInjections.getCustomObjectDetails(value, proto);
*/
function getCustomObjectDetails (value, proto) {
return backendInjections.getCustomObjectDetails(value, proto)
}
export /* Example usages of 'isVueInstance' are shown below:
;
backendInjections.isVueInstance(value);
*/
function isVueInstance (value) {
return backendInjections.isVueInstance(value)
}
// @TODO refactor
export function getCustomRouterDetails (router) {
return {
_custom: {
type: 'router',
display: 'VueRouter',
value: {
options: router.options,
currentRoute: router.currentRoute,
},
fields: {
abstract: true,
},
},
}
}
// @TODO refactor
export function getCustomStoreDetails (store) {
return {
_custom: {
type: 'store',
display: 'Store',
value: {
state: store.state,
getters: getCatchedGetters(store),
},
fields: {
abstract: true,
},
},
}
}
// @TODO refactor
export /* Example usages of 'getCatchedGetters' are shown below:
getCatchedGetters(store);
*/
function getCatchedGetters (store) {
const getters = {}
const origGetters = store.getters || {}
const keys = Object.keys(origGetters)
for (let i = 0; i < keys.length; i++) {
const key = keys[i]
Object.defineProperty(getters, key, {
enumerable: true,
get: () => {
try {
return origGetters[key]
} catch (e) {
return e
}
},
})
}
return getters
}
|
0dd7afdb6cc8378f50eb41c2a3abf6742a3c9514 | 2,061 | tsx | TypeScript | frontend/src/Reducer/SettingsReducer.tsx | TheMrPhantom/beachify | cb5111ff459b26efed3327a595391e034c7af970 | [
"MIT"
] | 1 | 2022-03-28T12:16:03.000Z | 2022-03-28T12:16:03.000Z | frontend/src/Reducer/SettingsReducer.tsx | TheMrPhantom/beachify | cb5111ff459b26efed3327a595391e034c7af970 | [
"MIT"
] | null | null | null | frontend/src/Reducer/SettingsReducer.tsx | TheMrPhantom/beachify | cb5111ff459b26efed3327a595391e034c7af970 | [
"MIT"
] | null | null | null | const initialState: SettingsType = {
listMode: "",
trustMode: "",
defaultPlaylist: "",
whitelistPlaylist: "",
guestToken: "",
waitingTime: "",
defaultBanTime: "",
queueState: "",
queueSubmittable: "",
retentionTime: "",
is_playing: false
}
export type SettingsType = {
listMode: string,
trustMode: string,
defaultPlaylist: string,
whitelistPlaylist: string,
guestToken: string,
waitingTime: string,
defaultBanTime: string,
queueState: string,
queueSubmittable: string,
retentionTime: string,
is_playing: boolean
}
const reducer = (state = initialState, { type, payload }: { type: string, payload: any }) => {
var newState = { ...state }
switch (type) {
case "SET_ALL":
newState = payload
return newState
case "SET_LISTMODE":
newState.listMode = payload
return newState
case "SET_TRUSTMODE":
newState.trustMode = payload
return newState
case "SET_DF_PLAYLIST":
newState.defaultPlaylist = payload
return newState
case "SET_WL_PLAYLIST":
newState.whitelistPlaylist = payload
return newState
case "SET_GUEST_TOKEN":
newState.guestToken = payload
return newState
case "SET_WAITING_TIME":
newState.waitingTime = payload
return newState
case "SET_DEFAULT_BANTIME":
newState.defaultBanTime = payload
return newState
case "SET_QUEUE_STATE":
newState.queueState = payload
return newState
case "SET_QUEUESUBMITTABLE":
newState.queueSubmittable = payload
return newState
case "SET_RETENTIONTIME":
newState.retentionTime = payload
return newState
case "SET_IS_PLAYING":
newState.is_playing = payload
return newState
default:
return state
}
}
export default reducer
| 27.118421 | 94 | 0.591946 | 70 | 1 | 0 | 2 | 3 | 11 | 0 | 1 | 12 | 1 | 0 | 41 | 434 | 0.006912 | 0.006912 | 0.025346 | 0.002304 | 0 | 0.058824 | 0.705882 | 0.210814 | const initialState = {
listMode: "",
trustMode: "",
defaultPlaylist: "",
whitelistPlaylist: "",
guestToken: "",
waitingTime: "",
defaultBanTime: "",
queueState: "",
queueSubmittable: "",
retentionTime: "",
is_playing: false
}
export type SettingsType = {
listMode,
trustMode,
defaultPlaylist,
whitelistPlaylist,
guestToken,
waitingTime,
defaultBanTime,
queueState,
queueSubmittable,
retentionTime,
is_playing
}
/* Example usages of 'reducer' are shown below:
;
*/
const reducer = (state = initialState, { type, payload }) => {
var newState = { ...state }
switch (type) {
case "SET_ALL":
newState = payload
return newState
case "SET_LISTMODE":
newState.listMode = payload
return newState
case "SET_TRUSTMODE":
newState.trustMode = payload
return newState
case "SET_DF_PLAYLIST":
newState.defaultPlaylist = payload
return newState
case "SET_WL_PLAYLIST":
newState.whitelistPlaylist = payload
return newState
case "SET_GUEST_TOKEN":
newState.guestToken = payload
return newState
case "SET_WAITING_TIME":
newState.waitingTime = payload
return newState
case "SET_DEFAULT_BANTIME":
newState.defaultBanTime = payload
return newState
case "SET_QUEUE_STATE":
newState.queueState = payload
return newState
case "SET_QUEUESUBMITTABLE":
newState.queueSubmittable = payload
return newState
case "SET_RETENTIONTIME":
newState.retentionTime = payload
return newState
case "SET_IS_PLAYING":
newState.is_playing = payload
return newState
default:
return state
}
}
export default reducer
|
fa04e67509eb55595bfa8378ba1bb4565e400c76 | 2,045 | ts | TypeScript | packages/common/src/augments/array.ts | electrovir/modivir | daa39d9e8abfa5ea632276e1aa8e048cb99cb2e3 | [
"MIT"
] | null | null | null | packages/common/src/augments/array.ts | electrovir/modivir | daa39d9e8abfa5ea632276e1aa8e048cb99cb2e3 | [
"MIT"
] | 1 | 2022-03-18T20:47:26.000Z | 2022-03-18T20:47:26.000Z | packages/common/src/augments/array.ts | electrovir/modivir | daa39d9e8abfa5ea632276e1aa8e048cb99cb2e3 | [
"MIT"
] | null | null | null | /** Same as array.prototype.filter but works with async filter callbacks. */
export async function asyncFilter<ArrayContents>(
arrayToFilter: Readonly<ArrayContents[]>,
callback: (
arrayEntry: ArrayContents,
index: number,
array: Readonly<ArrayContents[]>,
) => boolean | Promise<boolean>,
): Promise<ArrayContents[]> {
const mappedOutput = await Promise.all(arrayToFilter.map(callback));
return arrayToFilter.filter((entry, index) => {
const mappedEntry = mappedOutput[index];
return !!mappedEntry;
});
}
/** Maps the given array with the given callback and then filters out null and undefined mapped values. */
export function filterMap<ArrayContents, MappedValue>(
arrayToFilterMap: Readonly<ArrayContents[]>,
callback: (
arrayEntry: ArrayContents,
index: number,
array: Readonly<ArrayContents[]>,
) => MappedValue | undefined | null,
): NonNullable<MappedValue>[] {
return arrayToFilterMap.reduce(
(accum: NonNullable<MappedValue>[], currentValue, index, array) => {
const mappedValue: MappedValue | null | undefined = callback(
currentValue,
index,
array,
);
if (mappedValue != undefined) {
accum.push(mappedValue as NonNullable<MappedValue>);
}
return accum;
},
[],
);
}
export async function asyncInOrderMap<InArrayElementType, OutArrayElementType>(
inputArray: Readonly<InArrayElementType[]>,
callback: (
element: InArrayElementType,
index: number,
array: Readonly<InArrayElementType[]>,
) => Promise<OutArrayElementType> | OutArrayElementType,
): Promise<OutArrayElementType[]> {
return await inputArray.reduce(async (lastPromise, currentElement, index, array) => {
const accum = await lastPromise;
return accum.concat(await callback(currentElement, index, array));
}, Promise.resolve([] as OutArrayElementType[]));
}
| 37.181818 | 106 | 0.647433 | 50 | 6 | 0 | 16 | 4 | 0 | 0 | 0 | 5 | 0 | 2 | 6 | 449 | 0.048998 | 0.008909 | 0 | 0 | 0.004454 | 0 | 0.192308 | 0.312897 | /** Same as array.prototype.filter but works with async filter callbacks. */
export async function asyncFilter<ArrayContents>(
arrayToFilter,
callback,
) {
const mappedOutput = await Promise.all(arrayToFilter.map(callback));
return arrayToFilter.filter((entry, index) => {
const mappedEntry = mappedOutput[index];
return !!mappedEntry;
});
}
/** Maps the given array with the given callback and then filters out null and undefined mapped values. */
export function filterMap<ArrayContents, MappedValue>(
arrayToFilterMap,
callback,
) {
return arrayToFilterMap.reduce(
(accum, currentValue, index, array) => {
const mappedValue = callback(
currentValue,
index,
array,
);
if (mappedValue != undefined) {
accum.push(mappedValue as NonNullable<MappedValue>);
}
return accum;
},
[],
);
}
export async function asyncInOrderMap<InArrayElementType, OutArrayElementType>(
inputArray,
callback,
) {
return await inputArray.reduce(async (lastPromise, currentElement, index, array) => {
const accum = await lastPromise;
return accum.concat(await callback(currentElement, index, array));
}, Promise.resolve([] as OutArrayElementType[]));
}
|
fa55ae7de944b1052a12a0d21af39eb93b89f6a6 | 2,095 | ts | TypeScript | packages/validators/src/validators/bankAccountNumber/utils.ts | IQ-tech/firebolt | 5ae7519505129ca268f97ec72623860312163c0f | [
"Apache-2.0"
] | 5 | 2022-03-08T21:18:17.000Z | 2022-03-09T13:13:59.000Z | packages/validators/src/validators/bankAccountNumber/utils.ts | IQ-tech/firebolt | 5ae7519505129ca268f97ec72623860312163c0f | [
"Apache-2.0"
] | 11 | 2022-03-08T14:42:46.000Z | 2022-03-14T13:03:58.000Z | packages/validators/src/validators/bankAccountNumber/utils.ts | IQ-tech/firebolt | 5ae7519505129ca268f97ec72623860312163c0f | [
"Apache-2.0"
] | 1 | 2022-03-14T17:40:23.000Z | 2022-03-14T17:40:23.000Z | export function leftPad(value = '', padValue: number | string, len: number) {
if (value.length >= len) {
return value;
}
const padLength = len - value.length;
const padStr = String(padValue).repeat(padLength) + value;
return padStr;
}
export function getBranchAndDigit(bankBranch: string, dvLen: string | number) {
const numberDvLen = Number(dvLen);
const branch = bankBranch.slice(0, bankBranch.length - numberDvLen);
const branchDigit = bankBranch.slice(bankBranch.length - numberDvLen);
return { branch, branchDigit };
}
export function getAccountAndDigit(bankAccount: string) {
const account = bankAccount.slice(0, bankAccount.length - 1);
const accountDigit = bankAccount.slice(bankAccount.length - 1);
return { account, accountDigit };
}
export function getSumOfDigits(num: number | string) {
const numString = num.toString();
if (numString.length === 1) {
return num;
}
const numDigits = numString.split('');
const sum = numDigits.reduce((acc, digit) => acc + parseInt(digit), 0);
return sum;
}
export function getUnitDigit(num: number | string){
const numString = num.toString();
if (numString.length === 1) {
return num;
}
const unitDigit = parseInt(numString.slice(-1));
return unitDigit;
};
export const getMultipliersAndAccountProduct = (
weights: string[],
accountData: string,
prodModifier?: (...args: any) => string | number
): number => {
const result = weights.reduce((acc, currentValue, idx) => {
const multiplier = parseInt(currentValue);
const accDigit = parseInt(accountData[idx]);
const product = multiplier * accDigit;
if (prodModifier) {
const processedProduct = Number(prodModifier(product))
return acc + processedProduct
}
return acc + product;
}, 0);
return result;
};
export function cleanAccountAndBranchStrings(
bankAccount: string,
bankBranch: string,
) {
const formattedBranch = bankBranch.replace(/[.-]+/gi, '');
const formattedAccount = bankAccount.replace(/[.-]+/gi, '');
return {
formattedAccount,
formattedBranch,
};
}
| 26.1875 | 79 | 0.690692 | 64 | 9 | 0 | 18 | 20 | 0 | 0 | 1 | 18 | 0 | 0 | 5.777778 | 565 | 0.047788 | 0.035398 | 0 | 0 | 0 | 0.021277 | 0.382979 | 0.396721 | export function leftPad(value = '', padValue, len) {
if (value.length >= len) {
return value;
}
const padLength = len - value.length;
const padStr = String(padValue).repeat(padLength) + value;
return padStr;
}
export function getBranchAndDigit(bankBranch, dvLen) {
const numberDvLen = Number(dvLen);
const branch = bankBranch.slice(0, bankBranch.length - numberDvLen);
const branchDigit = bankBranch.slice(bankBranch.length - numberDvLen);
return { branch, branchDigit };
}
export function getAccountAndDigit(bankAccount) {
const account = bankAccount.slice(0, bankAccount.length - 1);
const accountDigit = bankAccount.slice(bankAccount.length - 1);
return { account, accountDigit };
}
export function getSumOfDigits(num) {
const numString = num.toString();
if (numString.length === 1) {
return num;
}
const numDigits = numString.split('');
const sum = numDigits.reduce((acc, digit) => acc + parseInt(digit), 0);
return sum;
}
export function getUnitDigit(num){
const numString = num.toString();
if (numString.length === 1) {
return num;
}
const unitDigit = parseInt(numString.slice(-1));
return unitDigit;
};
export const getMultipliersAndAccountProduct = (
weights,
accountData,
prodModifier?
) => {
const result = weights.reduce((acc, currentValue, idx) => {
const multiplier = parseInt(currentValue);
const accDigit = parseInt(accountData[idx]);
const product = multiplier * accDigit;
if (prodModifier) {
const processedProduct = Number(prodModifier(product))
return acc + processedProduct
}
return acc + product;
}, 0);
return result;
};
export function cleanAccountAndBranchStrings(
bankAccount,
bankBranch,
) {
const formattedBranch = bankBranch.replace(/[.-]+/gi, '');
const formattedAccount = bankAccount.replace(/[.-]+/gi, '');
return {
formattedAccount,
formattedBranch,
};
}
|
eb983290d28a75966aca98eb4a05bd4860401fd6 | 1,265 | ts | TypeScript | src/domain/BookStatus.ts | Lennoard/PI-II | 87558831bb399fcf09dac44d6d579aa083e0825b | [
"MIT"
] | 1 | 2022-03-31T21:33:41.000Z | 2022-03-31T21:33:41.000Z | src/domain/BookStatus.ts | Lennoard/PI-II | 87558831bb399fcf09dac44d6d579aa083e0825b | [
"MIT"
] | 2 | 2022-02-19T11:52:21.000Z | 2022-03-31T10:58:22.000Z | src/domain/BookStatus.ts | Lennoard/PI-II | 87558831bb399fcf09dac44d6d579aa083e0825b | [
"MIT"
] | 1 | 2022-03-18T17:45:06.000Z | 2022-03-18T17:45:06.000Z | export enum BookStatus {
NotAdded = -1,
Dropped = 0,
Reading = 1,
OnHold = 2,
Finished = 3,
PlanToRead = 4,
}
export default function parseBookStatus(status: BookStatus) {
switch (status) {
case BookStatus.Dropped:
return "Desistido";
case BookStatus.NotAdded:
return "Não adicionado";
case BookStatus.Reading:
return "Lendo";
case BookStatus.OnHold:
return "Em espera";
case BookStatus.Finished:
return "Lido";
case BookStatus.PlanToRead:
return "Planejo ler";
default:
return "Status desconhecido";
}
}
export function parseBookStatusInt(status: BookStatus){
switch (status) {
case BookStatus.NotAdded:
return -1;
case BookStatus.Dropped:
return 0;
case BookStatus.Reading:
return 1;
case BookStatus.OnHold:
return 2;
case BookStatus.Finished:
return 3;
case BookStatus.PlanToRead:
return 4;
}
}
export function parseBookStatusIntToTitle(status: number){
switch (status) {
case -1:
return "Não adicionado";
case 0:
return "Desistido";
case 1:
return "Lendo";
case 2:
return "Em espera";
case 3:
return "Acabado";
case 4:
return "Planejo ler";
}
} | 20.737705 | 61 | 0.628458 | 58 | 3 | 0 | 3 | 0 | 0 | 0 | 0 | 1 | 0 | 0 | 14.666667 | 371 | 0.016173 | 0 | 0 | 0 | 0 | 0 | 0.166667 | 0.207685 | export enum BookStatus {
NotAdded = -1,
Dropped = 0,
Reading = 1,
OnHold = 2,
Finished = 3,
PlanToRead = 4,
}
export default function parseBookStatus(status) {
switch (status) {
case BookStatus.Dropped:
return "Desistido";
case BookStatus.NotAdded:
return "Não adicionado";
case BookStatus.Reading:
return "Lendo";
case BookStatus.OnHold:
return "Em espera";
case BookStatus.Finished:
return "Lido";
case BookStatus.PlanToRead:
return "Planejo ler";
default:
return "Status desconhecido";
}
}
export function parseBookStatusInt(status){
switch (status) {
case BookStatus.NotAdded:
return -1;
case BookStatus.Dropped:
return 0;
case BookStatus.Reading:
return 1;
case BookStatus.OnHold:
return 2;
case BookStatus.Finished:
return 3;
case BookStatus.PlanToRead:
return 4;
}
}
export function parseBookStatusIntToTitle(status){
switch (status) {
case -1:
return "Não adicionado";
case 0:
return "Desistido";
case 1:
return "Lendo";
case 2:
return "Em espera";
case 3:
return "Acabado";
case 4:
return "Planejo ler";
}
} |
ebc37e1b73e92c4750a5fc480f46e34a74c09e71 | 2,025 | ts | TypeScript | lib/process-services-cloud/src/lib/process-cloud/models/process-filter-cloud.model.ts | stevetweeddale/alfresco-ng2-components | 5fc03cf26b919e770745a3fb78eb05709b23f835 | [
"ECL-2.0",
"Apache-2.0"
] | null | null | null | lib/process-services-cloud/src/lib/process-cloud/models/process-filter-cloud.model.ts | stevetweeddale/alfresco-ng2-components | 5fc03cf26b919e770745a3fb78eb05709b23f835 | [
"ECL-2.0",
"Apache-2.0"
] | 3 | 2022-02-27T23:58:39.000Z | 2022-03-02T12:50:14.000Z | lib/process-services-cloud/src/lib/process-cloud/models/process-filter-cloud.model.ts | stevetweeddale/alfresco-ng2-components | 5fc03cf26b919e770745a3fb78eb05709b23f835 | [
"ECL-2.0",
"Apache-2.0"
] | null | null | null | /*!
* @license
* Copyright 2016 Alfresco Software, Ltd.
*
* 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.
*/
export class ProcessQueryModel {
processDefinitionId: string;
appName: string;
state: string;
sort: string;
assignment: string;
order: string;
constructor(obj?: any) {
if (obj) {
this.appName = obj.appName || null;
this.processDefinitionId = obj.processDefinitionId || null;
this.state = obj.state || null;
this.sort = obj.sort || null;
this.assignment = obj.assignment || null;
this.order = obj.order || null;
}
}
}
export class ProcessFilterRepresentationModel {
id: string;
name: string;
key: string;
icon: string;
query: ProcessQueryModel;
constructor(obj?: any) {
if (obj) {
this.id = obj.id || Math.random().toString(36).substring(2, 9);
this.name = obj.name || null;
this.key = obj.key || null;
this.icon = obj.icon || null;
this.query = new ProcessQueryModel(obj.query);
}
}
hasFilter() {
return !!this.query;
}
}
export class ProcessFilterParamModel {
id: string;
name: string;
key: string;
index: number;
constructor(obj?: any) {
if (obj) {
this.id = obj.id || null;
this.name = obj.name || null;
this.key = obj.key || null;
this.index = obj.index || null;
}
}
}
| 28.125 | 75 | 0.595062 | 51 | 4 | 0 | 3 | 0 | 15 | 0 | 3 | 14 | 3 | 0 | 5.5 | 515 | 0.013592 | 0 | 0.029126 | 0.005825 | 0 | 0.136364 | 0.636364 | 0.208233 | /*!
* @license
* Copyright 2016 Alfresco Software, Ltd.
*
* 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.
*/
export class ProcessQueryModel {
processDefinitionId;
appName;
state;
sort;
assignment;
order;
constructor(obj?) {
if (obj) {
this.appName = obj.appName || null;
this.processDefinitionId = obj.processDefinitionId || null;
this.state = obj.state || null;
this.sort = obj.sort || null;
this.assignment = obj.assignment || null;
this.order = obj.order || null;
}
}
}
export class ProcessFilterRepresentationModel {
id;
name;
key;
icon;
query;
constructor(obj?) {
if (obj) {
this.id = obj.id || Math.random().toString(36).substring(2, 9);
this.name = obj.name || null;
this.key = obj.key || null;
this.icon = obj.icon || null;
this.query = new ProcessQueryModel(obj.query);
}
}
hasFilter() {
return !!this.query;
}
}
export class ProcessFilterParamModel {
id;
name;
key;
index;
constructor(obj?) {
if (obj) {
this.id = obj.id || null;
this.name = obj.name || null;
this.key = obj.key || null;
this.index = obj.index || null;
}
}
}
|
ebdb0168a7a62ecf639187ddc572903ca255d6ad | 2,721 | ts | TypeScript | buildScripts/prettyBytes.ts | samhuk/tree-starter | 07c9d0a075b754e17ca3c9abeb9b9f9320b28534 | [
"MIT"
] | 8 | 2022-01-09T00:32:10.000Z | 2022-03-19T09:48:50.000Z | buildScripts/prettyBytes.ts | samhuk/tree-starter | 07c9d0a075b754e17ca3c9abeb9b9f9320b28534 | [
"MIT"
] | null | null | null | buildScripts/prettyBytes.ts | samhuk/tree-starter | 07c9d0a075b754e17ca3c9abeb9b9f9320b28534 | [
"MIT"
] | null | null | null | const BYTE_UNITS = [
'B',
'kB',
'MB',
'GB',
'TB',
'PB',
'EB',
'ZB',
'YB',
]
const BIBYTE_UNITS = [
'B',
'kiB',
'MiB',
'GiB',
'TiB',
'PiB',
'EiB',
'ZiB',
'YiB',
]
const BIT_UNITS = [
'b',
'kbit',
'Mbit',
'Gbit',
'Tbit',
'Pbit',
'Ebit',
'Zbit',
'Ybit',
]
const BIBIT_UNITS = [
'b',
'kibit',
'Mibit',
'Gibit',
'Tibit',
'Pibit',
'Eibit',
'Zibit',
'Yibit',
]
/*
Formats the given number using `Number#toLocaleString`.
- If locale is a string, the value is expected to be a locale-key (for example: `de`).
- If locale is true, the system default locale is used for translation.
- If no value for locale is specified, the number is returned unmodified.
*/
const toLocaleString = (number: any, locale: any, options: any) => {
let result = number
if (typeof locale === 'string' || Array.isArray(locale))
result = number.toLocaleString(locale, options)
else if (locale === true || options !== undefined)
result = number.toLocaleString(undefined, options)
return result
}
const prettyBytes = (number: any, options?: any) => {
if (!Number.isFinite(number))
throw new TypeError(`Expected a finite number, got ${typeof number}: ${number}`)
// eslint-disable-next-line no-param-reassign
options = {
bits: false,
binary: false,
...options,
}
const UNITS = options.bits
? (options.binary ? BIBIT_UNITS : BIT_UNITS)
: (options.binary ? BIBYTE_UNITS : BYTE_UNITS)
if (options.signed && number === 0)
return ` 0 ${UNITS[0]}`
const isNegative = number < 0
const prefix = isNegative ? '-' : (options.signed ? '+' : '')
if (isNegative)
// eslint-disable-next-line no-param-reassign
number = -number
let localeOptions
if (options.minimumFractionDigits !== undefined)
localeOptions = { minimumFractionDigits: options.minimumFractionDigits }
if (options.maximumFractionDigits !== undefined)
localeOptions = { maximumFractionDigits: options.maximumFractionDigits, ...localeOptions }
if (number < 1) {
const numberString = toLocaleString(number, options.locale, localeOptions)
return `${prefix + numberString} ${UNITS[0]}`
}
const exponent = Math.min(Math.floor(options.binary ? Math.log(number) / Math.log(1024) : Math.log10(number) / 3), UNITS.length - 1)
// eslint-disable-next-line no-param-reassign
number /= (options.binary ? 1024 : 1000) ** exponent
if (!localeOptions)
// eslint-disable-next-line no-param-reassign
number = number.toPrecision(3)
const numberString = toLocaleString(Number(number), options.locale, localeOptions)
const unit = UNITS[exponent]
return `${prefix + numberString} ${unit}`
}
export default prettyBytes
| 22.675 | 134 | 0.649026 | 87 | 2 | 0 | 5 | 15 | 0 | 1 | 5 | 0 | 0 | 2 | 19 | 843 | 0.008304 | 0.017794 | 0 | 0 | 0.002372 | 0.227273 | 0 | 0.243933 | const BYTE_UNITS = [
'B',
'kB',
'MB',
'GB',
'TB',
'PB',
'EB',
'ZB',
'YB',
]
const BIBYTE_UNITS = [
'B',
'kiB',
'MiB',
'GiB',
'TiB',
'PiB',
'EiB',
'ZiB',
'YiB',
]
const BIT_UNITS = [
'b',
'kbit',
'Mbit',
'Gbit',
'Tbit',
'Pbit',
'Ebit',
'Zbit',
'Ybit',
]
const BIBIT_UNITS = [
'b',
'kibit',
'Mibit',
'Gibit',
'Tibit',
'Pibit',
'Eibit',
'Zibit',
'Yibit',
]
/*
Formats the given number using `Number#toLocaleString`.
- If locale is a string, the value is expected to be a locale-key (for example: `de`).
- If locale is true, the system default locale is used for translation.
- If no value for locale is specified, the number is returned unmodified.
*/
/* Example usages of 'toLocaleString' are shown below:
result = number.toLocaleString(locale, options);
result = number.toLocaleString(undefined, options);
toLocaleString(number, options.locale, localeOptions);
toLocaleString(Number(number), options.locale, localeOptions);
*/
const toLocaleString = (number, locale, options) => {
let result = number
if (typeof locale === 'string' || Array.isArray(locale))
result = number.toLocaleString(locale, options)
else if (locale === true || options !== undefined)
result = number.toLocaleString(undefined, options)
return result
}
/* Example usages of 'prettyBytes' are shown below:
;
*/
const prettyBytes = (number, options?) => {
if (!Number.isFinite(number))
throw new TypeError(`Expected a finite number, got ${typeof number}: ${number}`)
// eslint-disable-next-line no-param-reassign
options = {
bits: false,
binary: false,
...options,
}
const UNITS = options.bits
? (options.binary ? BIBIT_UNITS : BIT_UNITS)
: (options.binary ? BIBYTE_UNITS : BYTE_UNITS)
if (options.signed && number === 0)
return ` 0 ${UNITS[0]}`
const isNegative = number < 0
const prefix = isNegative ? '-' : (options.signed ? '+' : '')
if (isNegative)
// eslint-disable-next-line no-param-reassign
number = -number
let localeOptions
if (options.minimumFractionDigits !== undefined)
localeOptions = { minimumFractionDigits: options.minimumFractionDigits }
if (options.maximumFractionDigits !== undefined)
localeOptions = { maximumFractionDigits: options.maximumFractionDigits, ...localeOptions }
if (number < 1) {
const numberString = toLocaleString(number, options.locale, localeOptions)
return `${prefix + numberString} ${UNITS[0]}`
}
const exponent = Math.min(Math.floor(options.binary ? Math.log(number) / Math.log(1024) : Math.log10(number) / 3), UNITS.length - 1)
// eslint-disable-next-line no-param-reassign
number /= (options.binary ? 1024 : 1000) ** exponent
if (!localeOptions)
// eslint-disable-next-line no-param-reassign
number = number.toPrecision(3)
const numberString = toLocaleString(Number(number), options.locale, localeOptions)
const unit = UNITS[exponent]
return `${prefix + numberString} ${unit}`
}
export default prettyBytes
|
ebf0aebabc3c31d9a0c4ac7e2f2949be4b8afef5 | 3,336 | ts | TypeScript | divide-two-integers/index.ts | masx200/leetcode-test | bec83c7bc30fe3387a19bf8ae0c8685ed0aba2f4 | [
"MulanPSL-1.0"
] | 1 | 2022-03-30T11:10:14.000Z | 2022-03-30T11:10:14.000Z | divide-two-integers/index.ts | masx200/leetcode-test | bec83c7bc30fe3387a19bf8ae0c8685ed0aba2f4 | [
"MulanPSL-1.0"
] | null | null | null | divide-two-integers/index.ts | masx200/leetcode-test | bec83c7bc30fe3387a19bf8ae0c8685ed0aba2f4 | [
"MulanPSL-1.0"
] | null | null | null | function divide(dividend: number, divisor: number): number {
if (dividend === 2147483647 && divisor == 3) return 715827882;
// console.log({ dividend, divisor });
if (-2147483648 === dividend && divisor === 1) {
return -2147483648;
}
if (-2147483648 === dividend && divisor === -3) {
return 715827882;
}
if (-2147483648 === dividend && divisor === 2) {
return -1073741824;
}
if (divisor < 0 && dividend < 0) return divide(-dividend, -divisor);
if (dividend < 0) return -divide(-dividend, divisor);
if (divisor < 0) return -divide(dividend, -divisor);
const maxInt = Math.pow(2, 31) - 1;
const minInt = -Math.pow(2, 31);
if (dividend === divisor) return 1;
if (dividend === 0) return 0;
if (divisor === 0) return dividend > 0 ? maxInt : -minInt;
if (divisor === 1) {
return Math.min(maxInt, Math.max(minInt, dividend));
}
if (dividend < divisor) {
return 0;
}
const binaryexp = Math.floor(Math.log2(divisor));
if (divisor === Math.pow(2, binaryexp)) {
return Math.abs(dividend >> binaryexp);
}
let left = 1;
let right = Math.abs(dividend >> 1);
// left = left << 1;
// right = right << 1;
// console.log({ left, right });
// }
while (-left + right > 1) {
const middle = (left + right) >> 1;
if (multiplyIntegerGreater(divisor, middle, dividend) >= dividend) {
right = middle;
} else {
left = middle;
}
// console.log({ left, right });
//if (left === right) break;
}
const result = left;
return Math.min(maxInt, Math.max(minInt, result));
}
function multiplyIntegerGreater(x: number, y: number, z: number): number {
if (!Number.isInteger(y) || !Number.isInteger(x)) {
throw Error("not integer");
}
if (
Number.isNaN(x) ||
Number.isNaN(y) ||
!Number.isFinite(x) ||
!Number.isFinite(y)
) {
throw Error("Invalid number");
}
if (x > 0 && y > 0 && (x > z || y > z)) return z + 1;
return x < 0
? -multiplyIntegerGreater(-x, y, z)
: y < 0
? -multiplyIntegerGreater(x, -y, z)
: x === 0
? 0
: y === 0
? 0
: x === 1
? y
: y === 1
? x
: x < y
? multiplyIntegerGreater(y, x, z)
: y & 1
? x + multiplyIntegerGreater(x, y - 1, z)
: multiplyIntegerGreater(x + x, Math.abs(y >> 1), z);
}
// function multiplyInteger(x: number, y: number): number {
// if (!Number.isInteger(y) || !Number.isInteger(x)) {
// throw Error("not integer");
// }
// if (
// Number.isNaN(x) || Number.isNaN(y) || !Number.isFinite(x) ||
// !Number.isFinite(y)
// ) {
// throw Error("Invalid number");
// }
// return x < 0
// ? -multiplyInteger(-x, y)
// : y < 0
// ? -multiplyInteger(x, -y)
// : x === 0
// ? 0
// : y === 0
// ? 0
// : x === 1
// ? y
// : y === 1
// ? x
// : x < y
// ? multiplyInteger(y, x)
// : y & 1
// ? x + multiplyInteger(x, y - 1)
// : multiplyInteger(x + x, Math.abs(y >> 1));
// }
export default divide;
| 27.8 | 76 | 0.484712 | 74 | 2 | 0 | 5 | 7 | 0 | 2 | 0 | 7 | 0 | 0 | 34.5 | 1,103 | 0.006346 | 0.006346 | 0 | 0 | 0 | 0 | 0.5 | 0.2056 | /* Example usages of 'divide' are shown below:
divide(-dividend, -divisor);
-divide(-dividend, divisor);
-divide(dividend, -divisor);
// function multiplyInteger(x: number, y: number): number {
// if (!Number.isInteger(y) || !Number.isInteger(x)) {
// throw Error("not integer");
// }
// if (
// Number.isNaN(x) || Number.isNaN(y) || !Number.isFinite(x) ||
// !Number.isFinite(y)
// ) {
// throw Error("Invalid number");
// }
// return x < 0
// ? -multiplyInteger(-x, y)
// : y < 0
// ? -multiplyInteger(x, -y)
// : x === 0
// ? 0
// : y === 0
// ? 0
// : x === 1
// ? y
// : y === 1
// ? x
// : x < y
// ? multiplyInteger(y, x)
// : y & 1
// ? x + multiplyInteger(x, y - 1)
// : multiplyInteger(x + x, Math.abs(y >> 1));
// }
;
*/
function divide(dividend, divisor) {
if (dividend === 2147483647 && divisor == 3) return 715827882;
// console.log({ dividend, divisor });
if (-2147483648 === dividend && divisor === 1) {
return -2147483648;
}
if (-2147483648 === dividend && divisor === -3) {
return 715827882;
}
if (-2147483648 === dividend && divisor === 2) {
return -1073741824;
}
if (divisor < 0 && dividend < 0) return divide(-dividend, -divisor);
if (dividend < 0) return -divide(-dividend, divisor);
if (divisor < 0) return -divide(dividend, -divisor);
const maxInt = Math.pow(2, 31) - 1;
const minInt = -Math.pow(2, 31);
if (dividend === divisor) return 1;
if (dividend === 0) return 0;
if (divisor === 0) return dividend > 0 ? maxInt : -minInt;
if (divisor === 1) {
return Math.min(maxInt, Math.max(minInt, dividend));
}
if (dividend < divisor) {
return 0;
}
const binaryexp = Math.floor(Math.log2(divisor));
if (divisor === Math.pow(2, binaryexp)) {
return Math.abs(dividend >> binaryexp);
}
let left = 1;
let right = Math.abs(dividend >> 1);
// left = left << 1;
// right = right << 1;
// console.log({ left, right });
// }
while (-left + right > 1) {
const middle = (left + right) >> 1;
if (multiplyIntegerGreater(divisor, middle, dividend) >= dividend) {
right = middle;
} else {
left = middle;
}
// console.log({ left, right });
//if (left === right) break;
}
const result = left;
return Math.min(maxInt, Math.max(minInt, result));
}
/* Example usages of 'multiplyIntegerGreater' are shown below:
multiplyIntegerGreater(divisor, middle, dividend) >= dividend;
x < 0
? -multiplyIntegerGreater(-x, y, z)
: y < 0
? -multiplyIntegerGreater(x, -y, z)
: x === 0
? 0
: y === 0
? 0
: x === 1
? y
: y === 1
? x
: x < y
? multiplyIntegerGreater(y, x, z)
: y & 1
? x + multiplyIntegerGreater(x, y - 1, z)
: multiplyIntegerGreater(x + x, Math.abs(y >> 1), z);
*/
function multiplyIntegerGreater(x, y, z) {
if (!Number.isInteger(y) || !Number.isInteger(x)) {
throw Error("not integer");
}
if (
Number.isNaN(x) ||
Number.isNaN(y) ||
!Number.isFinite(x) ||
!Number.isFinite(y)
) {
throw Error("Invalid number");
}
if (x > 0 && y > 0 && (x > z || y > z)) return z + 1;
return x < 0
? -multiplyIntegerGreater(-x, y, z)
: y < 0
? -multiplyIntegerGreater(x, -y, z)
: x === 0
? 0
: y === 0
? 0
: x === 1
? y
: y === 1
? x
: x < y
? multiplyIntegerGreater(y, x, z)
: y & 1
? x + multiplyIntegerGreater(x, y - 1, z)
: multiplyIntegerGreater(x + x, Math.abs(y >> 1), z);
}
// function multiplyInteger(x: number, y: number): number {
// if (!Number.isInteger(y) || !Number.isInteger(x)) {
// throw Error("not integer");
// }
// if (
// Number.isNaN(x) || Number.isNaN(y) || !Number.isFinite(x) ||
// !Number.isFinite(y)
// ) {
// throw Error("Invalid number");
// }
// return x < 0
// ? -multiplyInteger(-x, y)
// : y < 0
// ? -multiplyInteger(x, -y)
// : x === 0
// ? 0
// : y === 0
// ? 0
// : x === 1
// ? y
// : y === 1
// ? x
// : x < y
// ? multiplyInteger(y, x)
// : y & 1
// ? x + multiplyInteger(x, y - 1)
// : multiplyInteger(x + x, Math.abs(y >> 1));
// }
export default divide;
|
3f56768763456223c2ba0b091b90831e3aa1b8b3 | 2,693 | ts | TypeScript | src/shared/common/bounds.ts | scarqin/eoapi | 6b78189e389691f1da1c8d8f98fadbbfd05f3e57 | [
"Apache-2.0"
] | 6 | 2022-03-05T15:50:44.000Z | 2022-03-25T14:13:19.000Z | src/shared/common/bounds.ts | scarqin/eoapi | 6b78189e389691f1da1c8d8f98fadbbfd05f3e57 | [
"Apache-2.0"
] | 8 | 2022-03-14T06:13:41.000Z | 2022-03-25T03:18:23.000Z | src/shared/common/bounds.ts | scarqin/eoapi | 6b78189e389691f1da1c8d8f98fadbbfd05f3e57 | [
"Apache-2.0"
] | 6 | 2022-02-15T02:50:35.000Z | 2022-03-30T02:34:48.000Z | /**
* 边栏放置位置
*/
export enum SidePosition {
left = 'left',
right = 'right',
top = 'top',
bottom = 'bottom'
};
/**
* 视图区域
*/
export enum ViewZone {
top = 'top',
bottom = 'bottom',
side = 'side',
main = 'main'
}
/**
* 视图尺寸、位置
*/
export interface ViewBounds {
x: number;
y: number;
width: number;
height: number;
}
/**
* 获取某个显示区域的bounds
* @param zone
* @param width
* @param height
* @param sidePosition
*/
export const getViewBounds = (zone: ViewZone, width: number, height: number, sidePosition?: SidePosition, sideWidth?: number): ViewBounds => {
return calculateViewBounds(width, height, sidePosition, sideWidth).get(zone);
};
/**
* 根据容器的尺寸计算所有显示区域的尺寸与位置
* TODO:需要加上隐藏边栏的属性参数判断
* @param width
* @param height
* @param sidePosition
*/
export const calculateViewBounds = (width: number, height: number, sidePosition?: SidePosition, sideWidth?: number): Map<ViewZone, ViewBounds> => {
const position: SidePosition = sidePosition || SidePosition.left;
const _topHeight: number = 50;
const _bottomHeight: number = 0;
const _sideWidth: number = sideWidth || 50;
const _mainHeight: number = height - _topHeight - _bottomHeight;
let topBounds: ViewBounds = {x: 0, y: 0, width: width, height: _topHeight};
let bottomBounds: ViewBounds = {x: 0, y: (height - _bottomHeight), width: width, height: _bottomHeight};
let sideBounds: ViewBounds = {x: 0, y: 0, width: _sideWidth, height: _mainHeight };
let mainBounds: ViewBounds = {x: 0, y: 0, width: width, height: _mainHeight};
switch (position) {
case SidePosition.left:
sideBounds.y = topBounds.height;
mainBounds.x = sideBounds.width;
mainBounds.y = topBounds.height;
mainBounds.width -= mainBounds.x;
break;
case SidePosition.right:
sideBounds.y = topBounds.height;
sideBounds.x = width - sideBounds.width;
mainBounds.y = topBounds.height;
mainBounds.width = sideBounds.x;
break;
case SidePosition.top:
sideBounds.height = sideBounds.width;
sideBounds.width = width;
sideBounds.y = topBounds.height;
mainBounds.height = height - topBounds.height - sideBounds.height - bottomBounds.height;
mainBounds.y = topBounds.height + sideBounds.height;
break;
case SidePosition.bottom:
sideBounds.height = sideBounds.width;
sideBounds.width = width;
mainBounds.y = topBounds.height;
mainBounds.height -= sideBounds.height;
sideBounds.y = topBounds.height + mainBounds.height;
break;
}
return new Map([
[ViewZone.top, topBounds],
[ViewZone.bottom, bottomBounds],
[ViewZone.side, sideBounds],
[ViewZone.main, mainBounds]
]);
};
| 28.648936 | 147 | 0.672113 | 66 | 2 | 0 | 9 | 11 | 4 | 1 | 0 | 14 | 1 | 0 | 22 | 821 | 0.013398 | 0.013398 | 0.004872 | 0.001218 | 0 | 0 | 0.538462 | 0.246757 | /**
* 边栏放置位置
*/
export enum SidePosition {
left = 'left',
right = 'right',
top = 'top',
bottom = 'bottom'
};
/**
* 视图区域
*/
export enum ViewZone {
top = 'top',
bottom = 'bottom',
side = 'side',
main = 'main'
}
/**
* 视图尺寸、位置
*/
export interface ViewBounds {
x;
y;
width;
height;
}
/**
* 获取某个显示区域的bounds
* @param zone
* @param width
* @param height
* @param sidePosition
*/
export const getViewBounds = (zone, width, height, sidePosition?, sideWidth?) => {
return calculateViewBounds(width, height, sidePosition, sideWidth).get(zone);
};
/**
* 根据容器的尺寸计算所有显示区域的尺寸与位置
* TODO:需要加上隐藏边栏的属性参数判断
* @param width
* @param height
* @param sidePosition
*/
export /* Example usages of 'calculateViewBounds' are shown below:
calculateViewBounds(width, height, sidePosition, sideWidth).get(zone);
*/
const calculateViewBounds = (width, height, sidePosition?, sideWidth?) => {
const position = sidePosition || SidePosition.left;
const _topHeight = 50;
const _bottomHeight = 0;
const _sideWidth = sideWidth || 50;
const _mainHeight = height - _topHeight - _bottomHeight;
let topBounds = {x: 0, y: 0, width: width, height: _topHeight};
let bottomBounds = {x: 0, y: (height - _bottomHeight), width: width, height: _bottomHeight};
let sideBounds = {x: 0, y: 0, width: _sideWidth, height: _mainHeight };
let mainBounds = {x: 0, y: 0, width: width, height: _mainHeight};
switch (position) {
case SidePosition.left:
sideBounds.y = topBounds.height;
mainBounds.x = sideBounds.width;
mainBounds.y = topBounds.height;
mainBounds.width -= mainBounds.x;
break;
case SidePosition.right:
sideBounds.y = topBounds.height;
sideBounds.x = width - sideBounds.width;
mainBounds.y = topBounds.height;
mainBounds.width = sideBounds.x;
break;
case SidePosition.top:
sideBounds.height = sideBounds.width;
sideBounds.width = width;
sideBounds.y = topBounds.height;
mainBounds.height = height - topBounds.height - sideBounds.height - bottomBounds.height;
mainBounds.y = topBounds.height + sideBounds.height;
break;
case SidePosition.bottom:
sideBounds.height = sideBounds.width;
sideBounds.width = width;
mainBounds.y = topBounds.height;
mainBounds.height -= sideBounds.height;
sideBounds.y = topBounds.height + mainBounds.height;
break;
}
return new Map([
[ViewZone.top, topBounds],
[ViewZone.bottom, bottomBounds],
[ViewZone.side, sideBounds],
[ViewZone.main, mainBounds]
]);
};
|
3fad943666fdca533288129be3bfb8b3ed5365f7 | 2,252 | ts | TypeScript | packages/unigraph-dev-explorer/src/examples/notes/noteQuery.ts | asampal/unigraph-dev | 59be34cfc01f695fd0b38cc4c747b55e77fa02ec | [
"MIT"
] | 1 | 2022-01-10T19:41:16.000Z | 2022-01-10T19:41:16.000Z | packages/unigraph-dev-explorer/src/examples/notes/noteQuery.ts | asampal/unigraph-dev | 59be34cfc01f695fd0b38cc4c747b55e77fa02ec | [
"MIT"
] | null | null | null | packages/unigraph-dev-explorer/src/examples/notes/noteQuery.ts | asampal/unigraph-dev | 59be34cfc01f695fd0b38cc4c747b55e77fa02ec | [
"MIT"
] | 1 | 2022-01-09T03:27:24.000Z | 2022-01-09T03:27:24.000Z | const MAX_DEPTH = 8;
const getQuery: (depth: number) => string = (depth: number) => {
if (depth >= MAX_DEPTH) return '{ uid _hide type {<unigraph.id>} }';
return `{
_updatedAt
uid
_hide
<~_value> {
type { <unigraph.id> }
<unigraph.origin> @filter(NOT eq(_hide, true)) {
type { <unigraph.id> }
uid
}
}
<unigraph.origin> @filter(NOT eq(_hide, true)) {
type { <unigraph.id> }
uid
}
type {
<unigraph.id>
}
_value {
uid
text {
uid
_value {
_value {
<dgraph.type>
uid type { <unigraph.id> }
<_value.%>
}
uid type { <unigraph.id> }
}
}
content {
uid
_value {
uid
type { <unigraph.id> }
}
}
children {
uid
<_displayAs>
<_value[> {
uid
<_index> { uid <_value.#i> }
<_key>
<_value> {
_hide
_value ${getQuery(depth + 1)}
uid
type { <unigraph.id> }
}
}
}
}
}`;
};
export const noteQueryDetailed = (uid: string, depth = 0) => `(func: uid(${uid})) ${getQuery(depth + 1)}`;
export const journalQueryDetailed = (uid: string, depth = 0) => `(func: uid(${uid})) {
_updatedAt
uid
_hide
type {
<unigraph.id>
}
_value {
note {
_value ${getQuery(depth + 1)}
}
}
}`;
export const noteQuery = (uid: string) => `(func: uid(${uid})) ${getQuery(MAX_DEPTH - 1)}`;
export const journalQuery = (uid: string) => `(func: uid(${uid})) {
_updatedAt
uid
_hide
type {
<unigraph.id>
}
_value {
note {
_value ${getQuery(MAX_DEPTH - 1)}
}
}
}`;
| 25.022222 | 106 | 0.363677 | 87 | 5 | 0 | 7 | 6 | 0 | 1 | 0 | 7 | 0 | 0 | 16.8 | 529 | 0.022684 | 0.011342 | 0 | 0 | 0 | 0 | 0.388889 | 0.259977 | const MAX_DEPTH = 8;
/* Example usages of 'getQuery' are shown below:
getQuery(depth + 1);
getQuery(MAX_DEPTH - 1);
*/
const getQuery = (depth) => {
if (depth >= MAX_DEPTH) return '{ uid _hide type {<unigraph.id>} }';
return `{
_updatedAt
uid
_hide
<~_value> {
type { <unigraph.id> }
<unigraph.origin> @filter(NOT eq(_hide, true)) {
type { <unigraph.id> }
uid
}
}
<unigraph.origin> @filter(NOT eq(_hide, true)) {
type { <unigraph.id> }
uid
}
type {
<unigraph.id>
}
_value {
uid
text {
uid
_value {
_value {
<dgraph.type>
uid type { <unigraph.id> }
<_value.%>
}
uid type { <unigraph.id> }
}
}
content {
uid
_value {
uid
type { <unigraph.id> }
}
}
children {
uid
<_displayAs>
<_value[> {
uid
<_index> { uid <_value.#i> }
<_key>
<_value> {
_hide
_value ${getQuery(depth + 1)}
uid
type { <unigraph.id> }
}
}
}
}
}`;
};
export const noteQueryDetailed = (uid, depth = 0) => `(func: uid(${uid})) ${getQuery(depth + 1)}`;
export const journalQueryDetailed = (uid, depth = 0) => `(func: uid(${uid})) {
_updatedAt
uid
_hide
type {
<unigraph.id>
}
_value {
note {
_value ${getQuery(depth + 1)}
}
}
}`;
export const noteQuery = (uid) => `(func: uid(${uid})) ${getQuery(MAX_DEPTH - 1)}`;
export const journalQuery = (uid) => `(func: uid(${uid})) {
_updatedAt
uid
_hide
type {
<unigraph.id>
}
_value {
note {
_value ${getQuery(MAX_DEPTH - 1)}
}
}
}`;
|
3fdc3bf965144082c065c98c12cd2efdf35d3cb7 | 2,624 | ts | TypeScript | libs/amyr-ts-lib/src/lib/libs/tsmt/math/neville.ts | theAlgorithmist/AMYR | db4141d7e545b94a5c98fc5430a065e2ba229e75 | [
"Apache-2.0"
] | 3 | 2022-01-17T21:31:47.000Z | 2022-03-04T20:16:21.000Z | libs/amyr-ts-lib/src/lib/libs/tsmt/math/neville.ts | theAlgorithmist/AMYR | db4141d7e545b94a5c98fc5430a065e2ba229e75 | [
"Apache-2.0"
] | null | null | null | libs/amyr-ts-lib/src/lib/libs/tsmt/math/neville.ts | theAlgorithmist/AMYR | db4141d7e545b94a5c98fc5430a065e2ba229e75 | [
"Apache-2.0"
] | null | null | null | /**
* Copyright 2016 Jim Armstrong (www.algorithmist.net)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/**
* AMYR Library: An implementation of Neville's method for polynomial interpolation of a SMALL
* (ideally less than 10) number of data points. In very well-behaved cases, 10 or 20 might work, but
* 100 or 200 will not.
*
* Credit: Derived from NRC polint.c
*
* @author Jim Armstrong (https://www.linkedin.com/in/jimarmstrong/)
*
* @version 1.0
*/
/**
* Interpolate a single data point or return {NaN} in the case of failure due to bad inputs.
*
* @param {Array<number>} xa x-coordinates of interpolation points
*
* @param {Array<number>} ya y-coordinates of interpolation points (length must equal that of {xa})
*
* @param {number} x x-coordinate of point to be interpolated
*
* @returns {number} y-coordinate of interpolated point or NaN in the case of sufficiently bad inputs to make
* the method fail.
*/
export const nevilleInterpolate = (xa: Array<number>, ya: Array<number>, x: number): number =>
{
const c: Array<number> = new Array<number>();
const d: Array<number> = new Array<number>();
const n: number = xa.length;
let den: number, dif: number, dift: number;
let ho: number, hp: number, w: number;
let i: number, m: number, ns: number;
let dy = 0;
let y: number;
ns = 0;
dif = Math.abs(x - xa[0]);
for (i = 0; i < n; ++i)
{
dift = Math.abs( x-xa[i] );
if (dift < dif)
{
ns = i;
dif = dift;
}
c[i] = ya[i];
d[i] = ya[i];
}
y = ya[ns];
ns = ns-1;
for (m = 0; m < n-1; ++m)
{
for (i = 0; i < n-m-1; ++i)
{
ho = xa[i] - x;
hp = xa[i+m+1] - x;
w = c[i+1] - d[i];
den = ho - hp;
if (Math.abs(den) < 0.00000001)
{
// bad news
return NaN;
}
den = w/den;
d[i] = hp*den;
c[i] = ho*den;
}
if (2*(ns+1) < n-m-1)
{
dy = c[ns + 1];
}
else
{
dy = d[ns];
ns = ns-1;
}
y = y + dy;
}
return y;
}
| 24.073394 | 109 | 0.580793 | 54 | 1 | 0 | 3 | 15 | 0 | 0 | 0 | 19 | 0 | 0 | 51 | 859 | 0.004657 | 0.017462 | 0 | 0 | 0 | 0 | 1 | 0.236897 | /**
* Copyright 2016 Jim Armstrong (www.algorithmist.net)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/**
* AMYR Library: An implementation of Neville's method for polynomial interpolation of a SMALL
* (ideally less than 10) number of data points. In very well-behaved cases, 10 or 20 might work, but
* 100 or 200 will not.
*
* Credit: Derived from NRC polint.c
*
* @author Jim Armstrong (https://www.linkedin.com/in/jimarmstrong/)
*
* @version 1.0
*/
/**
* Interpolate a single data point or return {NaN} in the case of failure due to bad inputs.
*
* @param {Array<number>} xa x-coordinates of interpolation points
*
* @param {Array<number>} ya y-coordinates of interpolation points (length must equal that of {xa})
*
* @param {number} x x-coordinate of point to be interpolated
*
* @returns {number} y-coordinate of interpolated point or NaN in the case of sufficiently bad inputs to make
* the method fail.
*/
export const nevilleInterpolate = (xa, ya, x) =>
{
const c = new Array<number>();
const d = new Array<number>();
const n = xa.length;
let den, dif, dift;
let ho, hp, w;
let i, m, ns;
let dy = 0;
let y;
ns = 0;
dif = Math.abs(x - xa[0]);
for (i = 0; i < n; ++i)
{
dift = Math.abs( x-xa[i] );
if (dift < dif)
{
ns = i;
dif = dift;
}
c[i] = ya[i];
d[i] = ya[i];
}
y = ya[ns];
ns = ns-1;
for (m = 0; m < n-1; ++m)
{
for (i = 0; i < n-m-1; ++i)
{
ho = xa[i] - x;
hp = xa[i+m+1] - x;
w = c[i+1] - d[i];
den = ho - hp;
if (Math.abs(den) < 0.00000001)
{
// bad news
return NaN;
}
den = w/den;
d[i] = hp*den;
c[i] = ho*den;
}
if (2*(ns+1) < n-m-1)
{
dy = c[ns + 1];
}
else
{
dy = d[ns];
ns = ns-1;
}
y = y + dy;
}
return y;
}
|
3fe8267a4b8aed719bfa5cfc4d16f245a2d85629 | 4,809 | ts | TypeScript | packages/typechain-target-fuels/src/parser/parseSvmTypes.ts | FuelLabs/fuels-ts | 425b68c57e61cb0e17aa71f35a9b0a9171c82dfa | [
"Apache-2.0"
] | 7 | 2022-01-04T05:44:35.000Z | 2022-03-09T16:42:28.000Z | packages/typechain-target-fuels/src/parser/parseSvmTypes.ts | FuelLabs/fuels-ts | 425b68c57e61cb0e17aa71f35a9b0a9171c82dfa | [
"Apache-2.0"
] | 60 | 2022-01-11T02:44:02.000Z | 2022-03-27T18:49:49.000Z | packages/typechain-target-fuels/src/parser/parseSvmTypes.ts | FuelLabs/fuels-ts | 425b68c57e61cb0e17aa71f35a9b0a9171c82dfa | [
"Apache-2.0"
] | 5 | 2022-01-17T14:13:25.000Z | 2022-03-13T07:31:35.000Z | export declare type SvmType =
| BoolType
| U8intType
| U16intType
| U32intType
| U64intType
| ByteType
| B256Type
| AddressType
| StringType
| ArrayType
| TupleType
| UnknownType;
/**
* Like SvmType but with void
*/
export declare type SvmOutputType = SvmType | VoidType;
export declare type BoolType = {
type: 'bool';
originalType: string;
};
export declare type U8intType = {
type: 'u8';
bits: 8;
originalType: string;
};
export declare type U16intType = {
type: 'u16';
bits: 16;
originalType: string;
};
export declare type U32intType = {
type: 'u32';
bits: 32;
originalType: string;
};
export declare type U64intType = {
type: 'u64';
bits: 64;
originalType: string;
};
export declare type ByteType = {
type: 'byte';
size: 1;
originalType: string;
};
export declare type B256Type = {
type: 'b256';
originalType: string;
};
export declare type AddressType = {
type: 'address';
originalType: string;
};
export declare type StringType = {
type: 'string';
size: number;
originalType: string;
};
export declare type ArrayType = {
type: 'array';
itemType: SvmType;
size?: number;
originalType: string;
};
export declare type TupleType = {
type: 'tuple';
structName: string;
components: SvmSymbol[];
originalType: string;
};
export declare type UnknownType = {
type: 'unknown';
originalType: string;
};
export declare type VoidType = {
type: 'void';
};
export declare type SvmSymbol = {
type: SvmType;
name: string;
};
const stringRegEx = /str\[([0-9]+)\]/;
const arrayRegEx = /\[(\w+);\s*([0-9]+)\]/;
/**
* Used to check if type is a custom struct
*/
const structRegEx = /^(struct|enum)/;
/**
* Converts valid file names to valid javascript symbols and does best effort to make them readable.
* Example: ds-token.test becomes DsTokenTest
*/
export function normalizeName(rawName: string): string {
const transformations: ((s: string) => string)[] = [
(s) => s.replace(/\s+/g, '-'), // spaces to - so later we can automatically convert them
(s) => s.replace(/\./g, '-'), // replace "."
(s) => s.replace(/_/g, '-'), // replace "_"
(s) => s.replace(/-[a-z]/g, (match) => match.substr(-1).toUpperCase()), // delete '-' and capitalize the letter after them
(s) => s.replace(/-/g, ''), // delete any '-' left
(s) => s.replace(/^\d+/, ''), // removes leading digits
(s) => s.charAt(0).toUpperCase() + s.slice(1),
];
const finalName = transformations.reduce((s, t) => t(s), rawName);
if (finalName === '') {
throw new Error(`Can't guess class name, please rename file: ${rawName}`);
}
return finalName;
}
/**
* Parses the SvmType from the JSON ABI; recusively on non-primatives
*/
export function parseSvmType(rawType: string, components?: SvmSymbol[], name?: string): SvmType {
const stringMatch = rawType.match(stringRegEx);
if (stringMatch !== null) {
const length = stringMatch[1];
return {
type: 'string',
size: parseInt(length, 10),
originalType: rawType,
};
}
const arrayMatch = rawType.match(arrayRegEx);
if (arrayMatch !== null) {
const type = arrayMatch[1];
const length = arrayMatch[2];
return {
type: 'array',
itemType: parseSvmType(type, components),
size: parseInt(length, 10),
originalType: rawType,
};
}
// If type starts with struct/enum we can treat it as tuple.
// In this way, the parser can process all components from the struct.
if (structRegEx.test(rawType)) {
if (!components) throw new Error(`${rawType} specified without components!`);
return {
type: 'tuple',
components,
originalType: rawType,
// Remove struct prefix enabling the code parser
// To create a Class with the structName
structName: rawType.replace(structRegEx, '').trim(),
};
}
switch (rawType) {
case 'u8':
return { type: 'u8', bits: 8, originalType: rawType };
case 'u16':
return { type: 'u16', bits: 16, originalType: rawType };
case 'u32':
return { type: 'u32', bits: 32, originalType: rawType };
case 'u64':
return { type: 'u64', bits: 64, originalType: rawType };
case 'bool':
return { type: 'bool', originalType: rawType };
case 'address':
return { type: 'address', originalType: rawType };
case 'b256':
return { type: 'b256', originalType: rawType };
case 'byte':
return { type: 'byte', size: 1, originalType: rawType };
case 'tuple':
if (!components) throw new Error('Tuple specified without components!');
return {
type: 'tuple',
components,
originalType: rawType,
structName: normalizeName(name || ''),
};
default:
}
return { type: 'unknown', originalType: rawType };
}
| 25.444444 | 126 | 0.625702 | 157 | 11 | 0 | 14 | 10 | 37 | 2 | 0 | 22 | 16 | 0 | 7.272727 | 1,427 | 0.017519 | 0.007008 | 0.025929 | 0.011212 | 0 | 0 | 0.305556 | 0.252135 | export declare type SvmType =
| BoolType
| U8intType
| U16intType
| U32intType
| U64intType
| ByteType
| B256Type
| AddressType
| StringType
| ArrayType
| TupleType
| UnknownType;
/**
* Like SvmType but with void
*/
export declare type SvmOutputType = SvmType | VoidType;
export declare type BoolType = {
type;
originalType;
};
export declare type U8intType = {
type;
bits;
originalType;
};
export declare type U16intType = {
type;
bits;
originalType;
};
export declare type U32intType = {
type;
bits;
originalType;
};
export declare type U64intType = {
type;
bits;
originalType;
};
export declare type ByteType = {
type;
size;
originalType;
};
export declare type B256Type = {
type;
originalType;
};
export declare type AddressType = {
type;
originalType;
};
export declare type StringType = {
type;
size;
originalType;
};
export declare type ArrayType = {
type;
itemType;
size?;
originalType;
};
export declare type TupleType = {
type;
structName;
components;
originalType;
};
export declare type UnknownType = {
type;
originalType;
};
export declare type VoidType = {
type;
};
export declare type SvmSymbol = {
type;
name;
};
const stringRegEx = /str\[([0-9]+)\]/;
const arrayRegEx = /\[(\w+);\s*([0-9]+)\]/;
/**
* Used to check if type is a custom struct
*/
const structRegEx = /^(struct|enum)/;
/**
* Converts valid file names to valid javascript symbols and does best effort to make them readable.
* Example: ds-token.test becomes DsTokenTest
*/
export /* Example usages of 'normalizeName' are shown below:
normalizeName(name || '');
*/
function normalizeName(rawName) {
const transformations = [
(s) => s.replace(/\s+/g, '-'), // spaces to - so later we can automatically convert them
(s) => s.replace(/\./g, '-'), // replace "."
(s) => s.replace(/_/g, '-'), // replace "_"
(s) => s.replace(/-[a-z]/g, (match) => match.substr(-1).toUpperCase()), // delete '-' and capitalize the letter after them
(s) => s.replace(/-/g, ''), // delete any '-' left
(s) => s.replace(/^\d+/, ''), // removes leading digits
(s) => s.charAt(0).toUpperCase() + s.slice(1),
];
const finalName = transformations.reduce((s, t) => t(s), rawName);
if (finalName === '') {
throw new Error(`Can't guess class name, please rename file: ${rawName}`);
}
return finalName;
}
/**
* Parses the SvmType from the JSON ABI; recusively on non-primatives
*/
export /* Example usages of 'parseSvmType' are shown below:
parseSvmType(type, components);
*/
function parseSvmType(rawType, components?, name?) {
const stringMatch = rawType.match(stringRegEx);
if (stringMatch !== null) {
const length = stringMatch[1];
return {
type: 'string',
size: parseInt(length, 10),
originalType: rawType,
};
}
const arrayMatch = rawType.match(arrayRegEx);
if (arrayMatch !== null) {
const type = arrayMatch[1];
const length = arrayMatch[2];
return {
type: 'array',
itemType: parseSvmType(type, components),
size: parseInt(length, 10),
originalType: rawType,
};
}
// If type starts with struct/enum we can treat it as tuple.
// In this way, the parser can process all components from the struct.
if (structRegEx.test(rawType)) {
if (!components) throw new Error(`${rawType} specified without components!`);
return {
type: 'tuple',
components,
originalType: rawType,
// Remove struct prefix enabling the code parser
// To create a Class with the structName
structName: rawType.replace(structRegEx, '').trim(),
};
}
switch (rawType) {
case 'u8':
return { type: 'u8', bits: 8, originalType: rawType };
case 'u16':
return { type: 'u16', bits: 16, originalType: rawType };
case 'u32':
return { type: 'u32', bits: 32, originalType: rawType };
case 'u64':
return { type: 'u64', bits: 64, originalType: rawType };
case 'bool':
return { type: 'bool', originalType: rawType };
case 'address':
return { type: 'address', originalType: rawType };
case 'b256':
return { type: 'b256', originalType: rawType };
case 'byte':
return { type: 'byte', size: 1, originalType: rawType };
case 'tuple':
if (!components) throw new Error('Tuple specified without components!');
return {
type: 'tuple',
components,
originalType: rawType,
structName: normalizeName(name || ''),
};
default:
}
return { type: 'unknown', originalType: rawType };
}
|
a00baf71ce6342110995f5f474772921fc4b1b1b | 2,806 | ts | TypeScript | packages/decorator/src/util/camelCase.ts | chriswjou/midway | b7a5c817d2316b93967367c34cff20a98b1ce4b7 | [
"MIT"
] | 1 | 2022-03-30T09:17:19.000Z | 2022-03-30T09:17:19.000Z | packages/decorator/src/util/camelCase.ts | chriswjou/midway | b7a5c817d2316b93967367c34cff20a98b1ce4b7 | [
"MIT"
] | null | null | null | packages/decorator/src/util/camelCase.ts | chriswjou/midway | b7a5c817d2316b93967367c34cff20a98b1ce4b7 | [
"MIT"
] | null | null | null | const UPPERCASE = /[\p{Lu}]/u;
const LOWERCASE = /[\p{Ll}]/u;
const IDENTIFIER = /([\p{Alpha}\p{N}_]|$)/u;
const SEPARATORS = /[_.\- ]+/;
const LEADING_SEPARATORS = new RegExp('^' + SEPARATORS.source);
const SEPARATORS_AND_IDENTIFIER = new RegExp(
SEPARATORS.source + IDENTIFIER.source,
'gu'
);
const NUMBERS_AND_IDENTIFIER = new RegExp('\\d+' + IDENTIFIER.source, 'gu');
const preserveCamelCase = (string, toLowerCase, toUpperCase) => {
let isLastCharLower = false;
let isLastCharUpper = false;
let isLastLastCharUpper = false;
for (let i = 0; i < string.length; i++) {
const character = string[i];
if (isLastCharLower && UPPERCASE.test(character)) {
string = string.slice(0, i) + '-' + string.slice(i);
isLastCharLower = false;
isLastLastCharUpper = isLastCharUpper;
isLastCharUpper = true;
i++;
} else if (
isLastCharUpper &&
isLastLastCharUpper &&
LOWERCASE.test(character)
) {
string = string.slice(0, i - 1) + '-' + string.slice(i - 1);
isLastLastCharUpper = isLastCharUpper;
isLastCharUpper = false;
isLastCharLower = true;
} else {
isLastCharLower =
toLowerCase(character) === character &&
toUpperCase(character) !== character;
isLastLastCharUpper = isLastCharUpper;
isLastCharUpper =
toUpperCase(character) === character &&
toLowerCase(character) !== character;
}
}
return string;
};
const postProcess = (input, toUpperCase) => {
SEPARATORS_AND_IDENTIFIER.lastIndex = 0;
NUMBERS_AND_IDENTIFIER.lastIndex = 0;
return input
.replace(SEPARATORS_AND_IDENTIFIER, (_, identifier) =>
toUpperCase(identifier)
)
.replace(NUMBERS_AND_IDENTIFIER, m => toUpperCase(m));
};
function camelCaseOrigin(
input: string,
options?: {
pascalCase?: boolean;
}
): string {
options = {
pascalCase: false,
...options,
};
input = input.trim();
if (input.length === 0) {
return '';
}
const toLowerCase = string => string.toLowerCase();
const toUpperCase = string => string.toUpperCase();
if (input.length === 1) {
return options.pascalCase ? toUpperCase(input) : toLowerCase(input);
}
const hasUpperCase = input !== toLowerCase(input);
if (hasUpperCase) {
input = preserveCamelCase(input, toLowerCase, toUpperCase);
}
input = input.replace(LEADING_SEPARATORS, '');
input = toLowerCase(input);
if (options.pascalCase) {
input = toUpperCase(input.charAt(0)) + input.slice(1);
}
return postProcess(input, toUpperCase);
}
export function camelCase(input: string): string {
return camelCaseOrigin(input, {
pascalCase: false,
});
}
export function pascalCase(input: string): string {
return camelCaseOrigin(input, {
pascalCase: true,
});
}
| 24.831858 | 76 | 0.651105 | 92 | 9 | 0 | 14 | 17 | 0 | 5 | 0 | 7 | 0 | 0 | 7.888889 | 791 | 0.029077 | 0.021492 | 0 | 0 | 0 | 0 | 0.175 | 0.309367 | const UPPERCASE = /[\p{Lu}]/u;
const LOWERCASE = /[\p{Ll}]/u;
const IDENTIFIER = /([\p{Alpha}\p{N}_]|$)/u;
const SEPARATORS = /[_.\- ]+/;
const LEADING_SEPARATORS = new RegExp('^' + SEPARATORS.source);
const SEPARATORS_AND_IDENTIFIER = new RegExp(
SEPARATORS.source + IDENTIFIER.source,
'gu'
);
const NUMBERS_AND_IDENTIFIER = new RegExp('\\d+' + IDENTIFIER.source, 'gu');
/* Example usages of 'preserveCamelCase' are shown below:
input = preserveCamelCase(input, toLowerCase, toUpperCase);
*/
const preserveCamelCase = (string, toLowerCase, toUpperCase) => {
let isLastCharLower = false;
let isLastCharUpper = false;
let isLastLastCharUpper = false;
for (let i = 0; i < string.length; i++) {
const character = string[i];
if (isLastCharLower && UPPERCASE.test(character)) {
string = string.slice(0, i) + '-' + string.slice(i);
isLastCharLower = false;
isLastLastCharUpper = isLastCharUpper;
isLastCharUpper = true;
i++;
} else if (
isLastCharUpper &&
isLastLastCharUpper &&
LOWERCASE.test(character)
) {
string = string.slice(0, i - 1) + '-' + string.slice(i - 1);
isLastLastCharUpper = isLastCharUpper;
isLastCharUpper = false;
isLastCharLower = true;
} else {
isLastCharLower =
toLowerCase(character) === character &&
toUpperCase(character) !== character;
isLastLastCharUpper = isLastCharUpper;
isLastCharUpper =
toUpperCase(character) === character &&
toLowerCase(character) !== character;
}
}
return string;
};
/* Example usages of 'postProcess' are shown below:
postProcess(input, toUpperCase);
*/
const postProcess = (input, toUpperCase) => {
SEPARATORS_AND_IDENTIFIER.lastIndex = 0;
NUMBERS_AND_IDENTIFIER.lastIndex = 0;
return input
.replace(SEPARATORS_AND_IDENTIFIER, (_, identifier) =>
toUpperCase(identifier)
)
.replace(NUMBERS_AND_IDENTIFIER, m => toUpperCase(m));
};
/* Example usages of 'camelCaseOrigin' are shown below:
camelCaseOrigin(input, {
pascalCase: false,
});
camelCaseOrigin(input, {
pascalCase: true,
});
*/
function camelCaseOrigin(
input,
options?
) {
options = {
pascalCase: false,
...options,
};
input = input.trim();
if (input.length === 0) {
return '';
}
/* Example usages of 'toLowerCase' are shown below:
;
isLastCharLower =
toLowerCase(character) === character &&
toUpperCase(character) !== character;
isLastCharUpper =
toUpperCase(character) === character &&
toLowerCase(character) !== character;
string.toLowerCase();
options.pascalCase ? toUpperCase(input) : toLowerCase(input);
input !== toLowerCase(input);
input = preserveCamelCase(input, toLowerCase, toUpperCase);
input = toLowerCase(input);
*/
const toLowerCase = string => string.toLowerCase();
/* Example usages of 'toUpperCase' are shown below:
;
isLastCharLower =
toLowerCase(character) === character &&
toUpperCase(character) !== character;
isLastCharUpper =
toUpperCase(character) === character &&
toLowerCase(character) !== character;
toUpperCase(identifier);
toUpperCase(m);
string.toUpperCase();
options.pascalCase ? toUpperCase(input) : toLowerCase(input);
input = preserveCamelCase(input, toLowerCase, toUpperCase);
input = toUpperCase(input.charAt(0)) + input.slice(1);
postProcess(input, toUpperCase);
*/
const toUpperCase = string => string.toUpperCase();
if (input.length === 1) {
return options.pascalCase ? toUpperCase(input) : toLowerCase(input);
}
const hasUpperCase = input !== toLowerCase(input);
if (hasUpperCase) {
input = preserveCamelCase(input, toLowerCase, toUpperCase);
}
input = input.replace(LEADING_SEPARATORS, '');
input = toLowerCase(input);
if (options.pascalCase) {
input = toUpperCase(input.charAt(0)) + input.slice(1);
}
return postProcess(input, toUpperCase);
}
export function camelCase(input) {
return camelCaseOrigin(input, {
pascalCase: false,
});
}
export /* Example usages of 'pascalCase' are shown below:
;
options.pascalCase ? toUpperCase(input) : toLowerCase(input);
options.pascalCase;
*/
function pascalCase(input) {
return camelCaseOrigin(input, {
pascalCase: true,
});
}
|
a03742d7c399b5369b37d1959396411971e28444 | 5,401 | ts | TypeScript | packages/verify/src/index.ts | linyisonger/Ru.Toolkit | 9c5ca09e6565ef36a3428fd5e24709d309468519 | [
"MIT"
] | 1 | 2022-03-01T03:06:28.000Z | 2022-03-01T03:06:28.000Z | packages/verify/src/index.ts | linyisonger/Ru.Toolkit | 9c5ca09e6565ef36a3428fd5e24709d309468519 | [
"MIT"
] | null | null | null | packages/verify/src/index.ts | linyisonger/Ru.Toolkit | 9c5ca09e6565ef36a3428fd5e24709d309468519 | [
"MIT"
] | null | null | null | /**
* 验证拓展类
*/
export class Verify {
/**
* 像是社会统一信用代码
* @param usci 社会统一信用代码
* @returns
*/
static likeUsci(usci: string): boolean {
return /[0-9A-HJ-NPQRTUWXY]{2}\d{6}[0-9A-HJ-NPQRTUWXY]{10}/.test(usci);
}
/**
* 是否是null或者""
* @param str 字符串
* @returns
*/
static isNullOrEmpty(str: string): boolean {
return str === "" || str === null || str === undefined
}
/**
* 校验是否是11位手机号码
* @param phoneNumber 手机号码
* @returns
*/
static isPhoneNumber(phoneNumber: string): boolean {
return /^1[3456789]\d{9}$/.test(phoneNumber)
}
/**
* 是否是邮箱
* @param email 邮箱
* @returns
*/
static isEmail(email: string): boolean {
return /^\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*$/.test(email)
}
/**
* 是否是统一社会信用代码
* @param usci 统一社会信用代码
* @returns
*/
static isUnifiedSocialCreditIdentifier(usci: string): boolean {
if (usci.length != 18) return false // 长度不正确
/** 省份区划 前两位 */
let provinceCodes = ['11', '12', '13', '14', '15', '21', '22', '23', '31', '32', '33', '34', '35', '36', '37', '41', '42', '43', '44', '45', '46', '50', '51', '52', '53', '54', '61', '62', '63', '64', '65', '71', '81', '82', '91']
/** 前两位 */
let top2 = usci.substring(0, 2);
/** 省份区域代码 第三位和第四位 */
let proCode = usci.substring(2, 4);
/** 行政区域代码 第三位和第八位 */
let regionCode = usci.substring(2, 8);
/** 组织机构代码 */
let organizingInstitutionBarCode = usci.substring(8, 16) + '-' + usci.substring(16, 17)
/** 组织机构校验不合格 */
if (!/^((1?[1|2|3|9])|(5?[1|2|3|9])|(9?[1|2|3|9])|[2|3|4|6|7|8|A-G|Y][1])$/.test(top2)) return false;
/** 省份区域代码校验不合格 */
if (!(provinceCodes.indexOf(proCode) > 0)) return false;
/** 行政区域代码校验不合格 */
if (!/^([0-9])*$/.test(regionCode)) return false;
/** 行政区域代码校验不合格 */
if (!/^([0-9A-Z]{8}\-[\d{1}|X])$/.test(organizingInstitutionBarCode)) return false;
/**
* 组织机构代码验证
*/
/** 组织机构代码前部分 */
let oibcBefore = organizingInstitutionBarCode.split('-')?.[0];
/** 组织机构代码后部分 */
let oibcAfter = organizingInstitutionBarCode.split('-')?.[1];
/** 因数 */
let factor = [3, 7, 9, 10, 5, 8, 4, 2]
/** 校验码 */
let c9: string | number = 0;
for (var i = 0; i < factor.length; i++) {
//把字符串中的字符一个一个的解码
let tmp = oibcBefore.charCodeAt(i);
if (tmp >= 48 && tmp <= 57) {
tmp -= 48;
} else if (tmp >= 65 && tmp <= 90) {
tmp -= 55;
}
//乘权重后加总
c9 += factor[i] * tmp;
}
c9 = 11 - (c9 % 11);
c9 = c9 == 11 ? '0' : c9 == 10 ? 'X' : (c9 + '')
// 组织机构代码验证
if (c9 != oibcAfter) return false;
/**
* 校验社会统一信用代码
*/
/** 加权因子 */
let weightFactor = [1, 3, 9, 27, 19, 26, 16, 17, 20, 29, 25, 13, 8, 24, 10, 30, 28]
/** 基数 */
let cardinalNumber = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'J', 'K', 'L', 'M', 'N', 'P', 'Q', 'R', 'T', 'U', 'W', 'X', 'Y']
/** 校验社会统一信用代码前部分 */
let usciBefore = usci.substring(0, 17);
/** 校验社会统一信用代码后部分 */
let usciAfter = usci.substring(17);
/** 校验码 */
let c18: string | number = 0;
for (let i = 0; i < usciBefore.length; i++) {
let tmp = usciBefore[i];
let idx = cardinalNumber.indexOf(tmp);
/** 字母不存在再基数中 */
if (idx == -1) return false;
c18 += idx * weightFactor[i]
}
c18 = 31 - (c18 % 31);
c18 = c18 == 31 ? 0 : c18
c18 = cardinalNumber[c18];
// 校验社会统一信用代码
if (usciAfter != c18) return false;
return true;
}
/**
* 是否是车牌号
* https://www.cnblogs.com/mmzuo-798/p/14929545.html
* @param vehicleNumber 车牌号
* @returns
*/
static isVehicleNumber(vehicleNumber: string) {
if (vehicleNumber.length == 7) return /^[京津沪渝冀豫云辽黑湘皖鲁新苏浙赣鄂桂甘晋蒙陕吉闽贵粤青藏川宁琼使领A-Z]{1}[A-Z]{1}[A-HJ-NP-Z0-9]{4}[A-HJ-NP-Z0-9挂学警港澳]{1}$/.test(vehicleNumber)
if (vehicleNumber.length == 8) return /^[京津沪渝冀豫云辽黑湘皖鲁新苏浙赣鄂桂甘晋蒙陕吉闽贵粤青藏川宁琼使领A-Z]{1}[A-Z]{1}(([0-9]{5}[DABCEFGHJK]$)|([DABCEFGHJK][A-HJ-NP-Z0-9][0-9]{4}$))/.test(vehicleNumber); // 2021年新能源车牌不止有DF
return false;
}
/**
* 像身份证号
* @param num 身份证号
* @returns
*/
static likeIDCardNumber(num: string): boolean {
return /^[1-9]\d{5}(18|19|([23]\d))\d{2}((0[1-9])|(10|11|12))(([0-2][1-9])|10|20|30|31)\d{3}[0-9Xx]$/.test(num)
}
/**
* 是否是身份证号码
* @param num 身份证号码
*/
static isCitizenIdentificationNumber(num: string): boolean {
if (num.length != 18) return false;
if (!this.likeIDCardNumber(num)) return false;
// 验证码
let vc = [1, 0, 10, 9, 8, 7, 6, 5, 4, 3, 2]
// 前部分
let frontNum = num.substring(0, 17);
let sum = 0;
for (let i = 0; i < frontNum.length; i++) {
let c = Number(frontNum[i]);
sum += (c * Math.pow(2, 17 - i)) % 11
}
sum %= 11;
if (Number(num[17]) != vc[sum]) return false;
return true;
}
} | 32.733333 | 238 | 0.468987 | 80 | 8 | 0 | 8 | 24 | 0 | 1 | 0 | 19 | 1 | 0 | 7.75 | 2,263 | 0.00707 | 0.010605 | 0 | 0.000442 | 0 | 0 | 0.475 | 0.221577 | /**
* 验证拓展类
*/
export class Verify {
/**
* 像是社会统一信用代码
* @param usci 社会统一信用代码
* @returns
*/
static likeUsci(usci) {
return /[0-9A-HJ-NPQRTUWXY]{2}\d{6}[0-9A-HJ-NPQRTUWXY]{10}/.test(usci);
}
/**
* 是否是null或者""
* @param str 字符串
* @returns
*/
static isNullOrEmpty(str) {
return str === "" || str === null || str === undefined
}
/**
* 校验是否是11位手机号码
* @param phoneNumber 手机号码
* @returns
*/
static isPhoneNumber(phoneNumber) {
return /^1[3456789]\d{9}$/.test(phoneNumber)
}
/**
* 是否是邮箱
* @param email 邮箱
* @returns
*/
static isEmail(email) {
return /^\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*$/.test(email)
}
/**
* 是否是统一社会信用代码
* @param usci 统一社会信用代码
* @returns
*/
static isUnifiedSocialCreditIdentifier(usci) {
if (usci.length != 18) return false // 长度不正确
/** 省份区划 前两位 */
let provinceCodes = ['11', '12', '13', '14', '15', '21', '22', '23', '31', '32', '33', '34', '35', '36', '37', '41', '42', '43', '44', '45', '46', '50', '51', '52', '53', '54', '61', '62', '63', '64', '65', '71', '81', '82', '91']
/** 前两位 */
let top2 = usci.substring(0, 2);
/** 省份区域代码 第三位和第四位 */
let proCode = usci.substring(2, 4);
/** 行政区域代码 第三位和第八位 */
let regionCode = usci.substring(2, 8);
/** 组织机构代码 */
let organizingInstitutionBarCode = usci.substring(8, 16) + '-' + usci.substring(16, 17)
/** 组织机构校验不合格 */
if (!/^((1?[1|2|3|9])|(5?[1|2|3|9])|(9?[1|2|3|9])|[2|3|4|6|7|8|A-G|Y][1])$/.test(top2)) return false;
/** 省份区域代码校验不合格 */
if (!(provinceCodes.indexOf(proCode) > 0)) return false;
/** 行政区域代码校验不合格 */
if (!/^([0-9])*$/.test(regionCode)) return false;
/** 行政区域代码校验不合格 */
if (!/^([0-9A-Z]{8}\-[\d{1}|X])$/.test(organizingInstitutionBarCode)) return false;
/**
* 组织机构代码验证
*/
/** 组织机构代码前部分 */
let oibcBefore = organizingInstitutionBarCode.split('-')?.[0];
/** 组织机构代码后部分 */
let oibcAfter = organizingInstitutionBarCode.split('-')?.[1];
/** 因数 */
let factor = [3, 7, 9, 10, 5, 8, 4, 2]
/** 校验码 */
let c9 = 0;
for (var i = 0; i < factor.length; i++) {
//把字符串中的字符一个一个的解码
let tmp = oibcBefore.charCodeAt(i);
if (tmp >= 48 && tmp <= 57) {
tmp -= 48;
} else if (tmp >= 65 && tmp <= 90) {
tmp -= 55;
}
//乘权重后加总
c9 += factor[i] * tmp;
}
c9 = 11 - (c9 % 11);
c9 = c9 == 11 ? '0' : c9 == 10 ? 'X' : (c9 + '')
// 组织机构代码验证
if (c9 != oibcAfter) return false;
/**
* 校验社会统一信用代码
*/
/** 加权因子 */
let weightFactor = [1, 3, 9, 27, 19, 26, 16, 17, 20, 29, 25, 13, 8, 24, 10, 30, 28]
/** 基数 */
let cardinalNumber = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'J', 'K', 'L', 'M', 'N', 'P', 'Q', 'R', 'T', 'U', 'W', 'X', 'Y']
/** 校验社会统一信用代码前部分 */
let usciBefore = usci.substring(0, 17);
/** 校验社会统一信用代码后部分 */
let usciAfter = usci.substring(17);
/** 校验码 */
let c18 = 0;
for (let i = 0; i < usciBefore.length; i++) {
let tmp = usciBefore[i];
let idx = cardinalNumber.indexOf(tmp);
/** 字母不存在再基数中 */
if (idx == -1) return false;
c18 += idx * weightFactor[i]
}
c18 = 31 - (c18 % 31);
c18 = c18 == 31 ? 0 : c18
c18 = cardinalNumber[c18];
// 校验社会统一信用代码
if (usciAfter != c18) return false;
return true;
}
/**
* 是否是车牌号
* https://www.cnblogs.com/mmzuo-798/p/14929545.html
* @param vehicleNumber 车牌号
* @returns
*/
static isVehicleNumber(vehicleNumber) {
if (vehicleNumber.length == 7) return /^[京津沪渝冀豫云辽黑湘皖鲁新苏浙赣鄂桂甘晋蒙陕吉闽贵粤青藏川宁琼使领A-Z]{1}[A-Z]{1}[A-HJ-NP-Z0-9]{4}[A-HJ-NP-Z0-9挂学警港澳]{1}$/.test(vehicleNumber)
if (vehicleNumber.length == 8) return /^[京津沪渝冀豫云辽黑湘皖鲁新苏浙赣鄂桂甘晋蒙陕吉闽贵粤青藏川宁琼使领A-Z]{1}[A-Z]{1}(([0-9]{5}[DABCEFGHJK]$)|([DABCEFGHJK][A-HJ-NP-Z0-9][0-9]{4}$))/.test(vehicleNumber); // 2021年新能源车牌不止有DF
return false;
}
/**
* 像身份证号
* @param num 身份证号
* @returns
*/
static likeIDCardNumber(num) {
return /^[1-9]\d{5}(18|19|([23]\d))\d{2}((0[1-9])|(10|11|12))(([0-2][1-9])|10|20|30|31)\d{3}[0-9Xx]$/.test(num)
}
/**
* 是否是身份证号码
* @param num 身份证号码
*/
static isCitizenIdentificationNumber(num) {
if (num.length != 18) return false;
if (!this.likeIDCardNumber(num)) return false;
// 验证码
let vc = [1, 0, 10, 9, 8, 7, 6, 5, 4, 3, 2]
// 前部分
let frontNum = num.substring(0, 17);
let sum = 0;
for (let i = 0; i < frontNum.length; i++) {
let c = Number(frontNum[i]);
sum += (c * Math.pow(2, 17 - i)) % 11
}
sum %= 11;
if (Number(num[17]) != vc[sum]) return false;
return true;
}
} |
a0d9f1e9fe5f677b2c9453e6bf12828db1ade54c | 2,209 | ts | TypeScript | package/src/animation/functions/spring.ts | mlynchdev/react-native-skia | 65a3c6676eab6ebe21bdd32d5ced838fc16649f0 | [
"MIT"
] | 2 | 2022-01-06T19:29:21.000Z | 2022-03-12T09:45:13.000Z | package/src/values/animation/spring/functions/spring.ts | schiller-manuel/react-native-skia | 0623844cbcc73c197dc33cac6bf1cb67326f9602 | [
"MIT"
] | null | null | null | package/src/values/animation/spring/functions/spring.ts | schiller-manuel/react-native-skia | 0623844cbcc73c197dc33cac6bf1cb67326f9602 | [
"MIT"
] | null | null | null | /**
* @description Returns a cached jsContext function for a spring with duration
* @param mass The mass of the spring
* @param stiffness The stiffness of the spring
* @param damping Spring damping
* @param velocity The initial velocity
*/
export const createSpringEasing = (
params: Partial<{
mass: number;
stiffness: number;
damping: number;
velocity: number;
}>
) => {
const {
mass,
stiffness,
damping,
velocity = 0,
} = {
mass: 1,
stiffness: 100,
damping: 10,
...params,
};
// TODO: Find correct velcoity
return getSpringEasing(mass, stiffness, damping, velocity / 100);
};
const getSpringEasing = (
mass: number,
stiffness: number,
damping: number,
initialVelocity = 0
) => {
// Setup spring state
const state = {
w0: Math.sqrt(stiffness / mass),
zeta: 0,
wd: 0,
a: 1,
b: 0,
};
state.zeta = damping / (2 * Math.sqrt(stiffness * mass));
state.wd =
state.zeta < 1 ? state.w0 * Math.sqrt(1 - state.zeta * state.zeta) : 0;
state.a = 1;
state.b =
state.zeta < 1
? (state.zeta * state.w0 + -initialVelocity) / state.wd
: -initialVelocity + state.w0;
const update = (t: number, duration?: number) => {
let progress = duration ? (duration * t) / 1000 : t;
if (state.zeta < 1) {
progress =
Math.exp(-progress * state.zeta * state.w0) *
(state.a * Math.cos(state.wd * progress) +
state.b * Math.sin(state.wd * progress));
} else {
progress =
(state.a + state.b * progress) * Math.exp(-progress * state.w0);
}
if (t === 0 || t === 1) {
return t;
}
return 1 - progress;
};
const getDurationMs = () => {
var frame = 1 / 6;
var elapsed = 0;
var rest = 0;
while (true) {
elapsed += frame;
if (update(elapsed) === 1) {
rest++;
if (rest >= 6) {
break;
}
} else {
rest = 0;
}
}
var durationMs = elapsed * frame * 1000;
return durationMs + 1000;
};
const durationMs = getDurationMs();
// Calculate duration
return {
update: (t: number) => update(t, durationMs),
duration: durationMs,
};
};
| 22.540816 | 78 | 0.560435 | 82 | 5 | 0 | 8 | 12 | 0 | 3 | 0 | 10 | 0 | 0 | 19.4 | 693 | 0.018759 | 0.017316 | 0 | 0 | 0 | 0 | 0.4 | 0.270821 | /**
* @description Returns a cached jsContext function for a spring with duration
* @param mass The mass of the spring
* @param stiffness The stiffness of the spring
* @param damping Spring damping
* @param velocity The initial velocity
*/
export const createSpringEasing = (
params
) => {
const {
mass,
stiffness,
damping,
velocity = 0,
} = {
mass: 1,
stiffness: 100,
damping: 10,
...params,
};
// TODO: Find correct velcoity
return getSpringEasing(mass, stiffness, damping, velocity / 100);
};
/* Example usages of 'getSpringEasing' are shown below:
getSpringEasing(mass, stiffness, damping, velocity / 100);
*/
const getSpringEasing = (
mass,
stiffness,
damping,
initialVelocity = 0
) => {
// Setup spring state
const state = {
w0: Math.sqrt(stiffness / mass),
zeta: 0,
wd: 0,
a: 1,
b: 0,
};
state.zeta = damping / (2 * Math.sqrt(stiffness * mass));
state.wd =
state.zeta < 1 ? state.w0 * Math.sqrt(1 - state.zeta * state.zeta) : 0;
state.a = 1;
state.b =
state.zeta < 1
? (state.zeta * state.w0 + -initialVelocity) / state.wd
: -initialVelocity + state.w0;
/* Example usages of 'update' are shown below:
update(elapsed) === 1;
;
update(t, durationMs);
*/
const update = (t, duration?) => {
let progress = duration ? (duration * t) / 1000 : t;
if (state.zeta < 1) {
progress =
Math.exp(-progress * state.zeta * state.w0) *
(state.a * Math.cos(state.wd * progress) +
state.b * Math.sin(state.wd * progress));
} else {
progress =
(state.a + state.b * progress) * Math.exp(-progress * state.w0);
}
if (t === 0 || t === 1) {
return t;
}
return 1 - progress;
};
/* Example usages of 'getDurationMs' are shown below:
getDurationMs();
*/
const getDurationMs = () => {
var frame = 1 / 6;
var elapsed = 0;
var rest = 0;
while (true) {
elapsed += frame;
if (update(elapsed) === 1) {
rest++;
if (rest >= 6) {
break;
}
} else {
rest = 0;
}
}
var durationMs = elapsed * frame * 1000;
return durationMs + 1000;
};
const durationMs = getDurationMs();
// Calculate duration
return {
update: (t) => update(t, durationMs),
duration: durationMs,
};
};
|
a0e68d8c7d5c53c1a4acd46a1337e2ef0e513855 | 4,182 | ts | TypeScript | src/Kubescape/yamlParse.ts | armosec/vscode-kubescape | 626434a35eed3c0363ee7590614989a427f0b839 | [
"Apache-2.0"
] | 2 | 2022-02-07T06:30:31.000Z | 2022-02-20T12:01:06.000Z | src/Kubescape/yamlParse.ts | armosec/vscode-kubescape | 626434a35eed3c0363ee7590614989a427f0b839 | [
"Apache-2.0"
] | null | null | null | src/Kubescape/yamlParse.ts | armosec/vscode-kubescape | 626434a35eed3c0363ee7590614989a427f0b839 | [
"Apache-2.0"
] | null | null | null | export interface IYamlHighlight {
startIndex: number;
endIndex: number;
}
type startIndexAccType = { startIndex: number; prevIndent: number; tempMatch: RegExpMatchArray | null; };
function checkAndUpdateIndent(startIndexAcc : startIndexAccType, index : number) : boolean {
if (index >= startIndexAcc.prevIndent) {
startIndexAcc.prevIndent = index
return true
} else {
return false
}
}
export class ResourceHighlightsHelperService {
static splitPathToSteps(path: string): string[] {
const splitRegExp = new RegExp(/[a-zA-Z]+|\[[^[]+]/, 'g');
return path.match(splitRegExp)?.reduce((acc: string[], step: string) => {
const trimRegExp = new RegExp(/[^[\]\d]+/);
if (trimRegExp.test(step)) {
acc.push(trimRegExp.exec(step)?.[0] || '');
} else {
acc[acc.length - 1] = acc[acc.length - 1] + step;
}
return acc;
}, []) || [];
}
static getStartAndEndIndexes(steps: string[], lines: string[]): IYamlHighlight {
const startIndexAcc = ResourceHighlightsHelperService.getStartIndexAcc(steps, lines);
const startIndex = startIndexAcc.startIndex;
const endIndex = ResourceHighlightsHelperService.getEndIndex(startIndex, lines, !!startIndexAcc.tempMatch);
return { startIndex, endIndex };
}
static getStartIndexAcc(steps: string[], lines: string[]): startIndexAccType {
const indentArray = '- ';
// const indentArray = ' - ';
const regExpForArray = new RegExp(/\[\d+]/);
const regExpForArrayIndex = new RegExp(/\d+/);
return steps.reduce((startIndexAcc: startIndexAccType, step: string, stepIndex: number) => {
const stepWithOutArr = step.replace(regExpForArray, '') + ':';
if (startIndexAcc.tempMatch) {
handleArrayMatch(startIndexAcc, lines, indentArray, stepWithOutArr);
} else {
startIndexAcc.startIndex = lines.findIndex((line: string, indexLine: number) => {
if (indexLine > startIndexAcc.startIndex) {
return checkAndUpdateIndent(startIndexAcc, line.indexOf(stepWithOutArr))
}
return false;
});
}
startIndexAcc.tempMatch = step.match(regExpForArrayIndex);
const isLastItem = stepIndex === (steps.length - 1);
if (isLastItem && startIndexAcc.tempMatch) {
handleArrayMatch(startIndexAcc, lines, indentArray, indentArray)
}
return startIndexAcc;
}, { startIndex: -1, prevIndent: 0, tempMatch: null });
}
static getEndIndex(startIndex: number, lines: string[], isArrElement: boolean): number {
const indent = ' ';
const regExp = isArrElement ? new RegExp(/-/) : new RegExp(/\w/);
const regExpResult: RegExpExecArray | null = regExp.exec(lines[startIndex]);
const controlIndex = regExpResult?.index || 0;
const firstParallelLineIndex = lines.findIndex((line: string, lineIndex: number) => {
if (lineIndex > startIndex) {
return line[controlIndex] !== indent;
}
return false;
});
return firstParallelLineIndex - 1;
}
}
function handleArrayMatch(startIndexAcc: startIndexAccType, lines: string[], indentArray: string, searchTerm: string) {
if (startIndexAcc.tempMatch) {
const arrayIndex = +startIndexAcc.tempMatch[0];
let controlIndex: number | null = null;
// find first indentation of array
let arrayIndent: number;
lines.findIndex((line: string, indexLine: number) => {
if (indexLine > startIndexAcc.startIndex) {
arrayIndent = line.indexOf(indentArray);
if (arrayIndent >= startIndexAcc.prevIndent) {
return true;
}
return false;
}
return false;
});
startIndexAcc.startIndex = lines.findIndex((line: string, indexLine: number) => {
if (indexLine > startIndexAcc.startIndex) {
if (controlIndex !== arrayIndex && line.indexOf(indentArray) === arrayIndent) {
controlIndex = controlIndex === null ? 0 : controlIndex + 1;
}
if (controlIndex === arrayIndex) {
return checkAndUpdateIndent(startIndexAcc, line.indexOf(searchTerm));
}
return false;
}
return false;
});
}
}
| 31.443609 | 119 | 0.648254 | 99 | 12 | 0 | 27 | 18 | 5 | 4 | 0 | 33 | 3 | 0 | 10.833333 | 1,030 | 0.037864 | 0.017476 | 0.004854 | 0.002913 | 0 | 0 | 0.532258 | 0.320814 | export interface IYamlHighlight {
startIndex;
endIndex;
}
type startIndexAccType = { startIndex; prevIndent; tempMatch; };
/* Example usages of 'checkAndUpdateIndent' are shown below:
checkAndUpdateIndent(startIndexAcc, line.indexOf(stepWithOutArr));
checkAndUpdateIndent(startIndexAcc, line.indexOf(searchTerm));
*/
function checkAndUpdateIndent(startIndexAcc , index ) {
if (index >= startIndexAcc.prevIndent) {
startIndexAcc.prevIndent = index
return true
} else {
return false
}
}
export class ResourceHighlightsHelperService {
static splitPathToSteps(path) {
const splitRegExp = new RegExp(/[a-zA-Z]+|\[[^[]+]/, 'g');
return path.match(splitRegExp)?.reduce((acc, step) => {
const trimRegExp = new RegExp(/[^[\]\d]+/);
if (trimRegExp.test(step)) {
acc.push(trimRegExp.exec(step)?.[0] || '');
} else {
acc[acc.length - 1] = acc[acc.length - 1] + step;
}
return acc;
}, []) || [];
}
static getStartAndEndIndexes(steps, lines) {
const startIndexAcc = ResourceHighlightsHelperService.getStartIndexAcc(steps, lines);
const startIndex = startIndexAcc.startIndex;
const endIndex = ResourceHighlightsHelperService.getEndIndex(startIndex, lines, !!startIndexAcc.tempMatch);
return { startIndex, endIndex };
}
static getStartIndexAcc(steps, lines) {
const indentArray = '- ';
// const indentArray = ' - ';
const regExpForArray = new RegExp(/\[\d+]/);
const regExpForArrayIndex = new RegExp(/\d+/);
return steps.reduce((startIndexAcc, step, stepIndex) => {
const stepWithOutArr = step.replace(regExpForArray, '') + ':';
if (startIndexAcc.tempMatch) {
handleArrayMatch(startIndexAcc, lines, indentArray, stepWithOutArr);
} else {
startIndexAcc.startIndex = lines.findIndex((line, indexLine) => {
if (indexLine > startIndexAcc.startIndex) {
return checkAndUpdateIndent(startIndexAcc, line.indexOf(stepWithOutArr))
}
return false;
});
}
startIndexAcc.tempMatch = step.match(regExpForArrayIndex);
const isLastItem = stepIndex === (steps.length - 1);
if (isLastItem && startIndexAcc.tempMatch) {
handleArrayMatch(startIndexAcc, lines, indentArray, indentArray)
}
return startIndexAcc;
}, { startIndex: -1, prevIndent: 0, tempMatch: null });
}
static getEndIndex(startIndex, lines, isArrElement) {
const indent = ' ';
const regExp = isArrElement ? new RegExp(/-/) : new RegExp(/\w/);
const regExpResult = regExp.exec(lines[startIndex]);
const controlIndex = regExpResult?.index || 0;
const firstParallelLineIndex = lines.findIndex((line, lineIndex) => {
if (lineIndex > startIndex) {
return line[controlIndex] !== indent;
}
return false;
});
return firstParallelLineIndex - 1;
}
}
/* Example usages of 'handleArrayMatch' are shown below:
handleArrayMatch(startIndexAcc, lines, indentArray, stepWithOutArr);
handleArrayMatch(startIndexAcc, lines, indentArray, indentArray);
*/
function handleArrayMatch(startIndexAcc, lines, indentArray, searchTerm) {
if (startIndexAcc.tempMatch) {
const arrayIndex = +startIndexAcc.tempMatch[0];
let controlIndex = null;
// find first indentation of array
let arrayIndent;
lines.findIndex((line, indexLine) => {
if (indexLine > startIndexAcc.startIndex) {
arrayIndent = line.indexOf(indentArray);
if (arrayIndent >= startIndexAcc.prevIndent) {
return true;
}
return false;
}
return false;
});
startIndexAcc.startIndex = lines.findIndex((line, indexLine) => {
if (indexLine > startIndexAcc.startIndex) {
if (controlIndex !== arrayIndex && line.indexOf(indentArray) === arrayIndent) {
controlIndex = controlIndex === null ? 0 : controlIndex + 1;
}
if (controlIndex === arrayIndex) {
return checkAndUpdateIndent(startIndexAcc, line.indexOf(searchTerm));
}
return false;
}
return false;
});
}
}
|
a0fab4b9f8fffbd169fbe46a661c46b5273b5e9e | 2,636 | ts | TypeScript | packages/paddlejs-backend-webgl/src/ops/shader/stack.ts | JingyuanZhang/Paddlejs | 0ff3ae875bfc4a6e965d4b45794aed160de00e8f | [
"Apache-2.0"
] | 1 | 2022-02-21T11:14:11.000Z | 2022-02-21T11:14:11.000Z | packages/paddlejs-backend-webgl/src/ops/shader/stack.ts | JingyuanZhang/Paddlejs | 0ff3ae875bfc4a6e965d4b45794aed160de00e8f | [
"Apache-2.0"
] | null | null | null | packages/paddlejs-backend-webgl/src/ops/shader/stack.ts | JingyuanZhang/Paddlejs | 0ff3ae875bfc4a6e965d4b45794aed160de00e8f | [
"Apache-2.0"
] | null | null | null | /**
* @file stack dynamic inputs
* @description stack inputs X supports no more than 15 tensors, eg. [a1, a2, a3, a4, ... , a15]
* @detail https://github.com/PaddlePaddle/Paddle/blob/develop/paddle/fluid/operators/stack_op.h#L56
* @detail https://www.paddlepaddle.org.cn/documentation/docs/zh/api/paddle/stack_cn.html#stack
*/
function mainFunc(
{ out, ...inputs },
attrs
) {
const origin_tensor = inputs['origin'];
const {
width_shape,
height_shape,
channel,
total_shape,
length_unformatted_shape
} = origin_tensor;
const batch = total_shape / (width_shape * height_shape * channel);
const tensor_shape = [batch, channel, height_shape, width_shape];
const origin_shape = tensor_shape.slice(4 - length_unformatted_shape);
const inputs_num = Object.keys(inputs).length;
const axis = attrs.axis < 0 ? attrs.axis + origin_shape.length + 1 : attrs.axis;
let pre = 1;
let post = 1;
for (let index = 0; index < axis; index++) {
pre *= origin_shape[index];
}
for (let index = axis; index < origin_shape.length; index++) {
post *= origin_shape[index];
}
const out_total_shape = out.total_shape;
const pre_every_num = out_total_shape / pre;
let getMultiInputsValue = '';
getMultiInputsValue = Array.from(Array(inputs_num).keys()).reduce((acc, cur) => {
return acc + (cur === 0
? `
if (i == 0) {
ivec4 co = getTensorPosFromArrayIndex_origin(j);
o = getValueFromTensorPos_origin(co.r, co.g, co.b, co.a);
}`
: `
else if (i == ${cur}) {
ivec4 co = getTensorPosFromArrayIndex_origin_${cur}(j);
o = getValueFromTensorPos_origin_${cur}(co.r, co.g, co.b, co.a);
}`);
}, getMultiInputsValue);
return `
// start函数
void main(void) {
ivec4 oPos = getOutputTensorPos();
// 输出坐标转换为输入坐标
int sumVal = oPos.a
+ oPos.b * ${out.width_shape}
+ oPos.g * ${out.height_shape} * ${out.width_shape}
+ oPos.r * ${out.channel} * ${out.width_shape} * ${out.height_shape};
int index = calMod(sumVal, ${pre_every_num});
int layer = sumVal / ${pre_every_num};
int i = index / ${post};
int j = calMod(index, ${post}) + layer * ${post};
float o = 0.0;
${getMultiInputsValue}
setOutput(float(o));
}
`;
}
export default {
mainFunc,
textureFuncConf: {
'@all': ['getValueFromTensorPos', 'getTensorPosFromArrayIndex']
}
};
| 29.954545 | 100 | 0.58308 | 66 | 2 | 0 | 4 | 14 | 0 | 0 | 0 | 0 | 0 | 0 | 33 | 775 | 0.007742 | 0.018065 | 0 | 0 | 0 | 0 | 0 | 0.247286 | /**
* @file stack dynamic inputs
* @description stack inputs X supports no more than 15 tensors, eg. [a1, a2, a3, a4, ... , a15]
* @detail https://github.com/PaddlePaddle/Paddle/blob/develop/paddle/fluid/operators/stack_op.h#L56
* @detail https://www.paddlepaddle.org.cn/documentation/docs/zh/api/paddle/stack_cn.html#stack
*/
/* Example usages of 'mainFunc' are shown below:
;
*/
function mainFunc(
{ out, ...inputs },
attrs
) {
const origin_tensor = inputs['origin'];
const {
width_shape,
height_shape,
channel,
total_shape,
length_unformatted_shape
} = origin_tensor;
const batch = total_shape / (width_shape * height_shape * channel);
const tensor_shape = [batch, channel, height_shape, width_shape];
const origin_shape = tensor_shape.slice(4 - length_unformatted_shape);
const inputs_num = Object.keys(inputs).length;
const axis = attrs.axis < 0 ? attrs.axis + origin_shape.length + 1 : attrs.axis;
let pre = 1;
let post = 1;
for (let index = 0; index < axis; index++) {
pre *= origin_shape[index];
}
for (let index = axis; index < origin_shape.length; index++) {
post *= origin_shape[index];
}
const out_total_shape = out.total_shape;
const pre_every_num = out_total_shape / pre;
let getMultiInputsValue = '';
getMultiInputsValue = Array.from(Array(inputs_num).keys()).reduce((acc, cur) => {
return acc + (cur === 0
? `
if (i == 0) {
ivec4 co = getTensorPosFromArrayIndex_origin(j);
o = getValueFromTensorPos_origin(co.r, co.g, co.b, co.a);
}`
: `
else if (i == ${cur}) {
ivec4 co = getTensorPosFromArrayIndex_origin_${cur}(j);
o = getValueFromTensorPos_origin_${cur}(co.r, co.g, co.b, co.a);
}`);
}, getMultiInputsValue);
return `
// start函数
void main(void) {
ivec4 oPos = getOutputTensorPos();
// 输出坐标转换为输入坐标
int sumVal = oPos.a
+ oPos.b * ${out.width_shape}
+ oPos.g * ${out.height_shape} * ${out.width_shape}
+ oPos.r * ${out.channel} * ${out.width_shape} * ${out.height_shape};
int index = calMod(sumVal, ${pre_every_num});
int layer = sumVal / ${pre_every_num};
int i = index / ${post};
int j = calMod(index, ${post}) + layer * ${post};
float o = 0.0;
${getMultiInputsValue}
setOutput(float(o));
}
`;
}
export default {
mainFunc,
textureFuncConf: {
'@all': ['getValueFromTensorPos', 'getTensorPosFromArrayIndex']
}
};
|
ff22f2070f9ecb6c40febbc275a968ac7c6309fa | 1,538 | ts | TypeScript | src/modules/shared/mapper/entity-dto-map.ts | AdrianoCucci/SDC-Chat-Server | df08b9ee998229c303d490370ce7347e13cc5b4f | [
"MIT"
] | null | null | null | src/modules/shared/mapper/entity-dto-map.ts | AdrianoCucci/SDC-Chat-Server | df08b9ee998229c303d490370ce7347e13cc5b4f | [
"MIT"
] | 1 | 2022-03-26T22:17:30.000Z | 2022-03-26T22:17:30.000Z | src/modules/shared/mapper/entity-dto-map.ts | AdrianoCucci/SDC-Chat-Server | df08b9ee998229c303d490370ce7347e13cc5b4f | [
"MIT"
] | null | null | null | export class EntityDtoMap<TEntity, TDto> {
private readonly _handlers: EntityDtoMapHandlers<TEntity, TDto>;
public constructor(handlers: EntityDtoMapHandlers<TEntity, TDto>) {
this._handlers = handlers ?? {};
}
public mapEntity(dto: Partial<TDto>, target?: TEntity): TEntity {
let entity: TEntity = null;
if(dto != null && this._handlers.mapEntity != null) {
entity = this._handlers.mapEntity({ ...dto }, target);
}
return entity;
}
public mapDto(entity: TEntity): TDto {
let dto: TDto = null;
if(entity != null && this._handlers.mapDto != null) {
dto = this._handlers.mapDto({ ...entity });
}
return dto;
}
public mapEntities(dtos: TDto[]): TEntity[] {
const entities: TEntity[] = [];
if(dtos != null) {
const length: number = dtos.length;
for(let i = 0; i < length; i++) {
const entity: TEntity = this.mapEntity(dtos[i]);
if(entity != null) {
entities.push(entity);
}
}
}
return entities;
}
public mapDtos(entities: TEntity[]): TDto[] {
const dtos: TDto[] = [];
if(entities != null) {
const length: number = entities.length;
for(let i = 0; i < length; i++) {
const dto: TDto = this.mapDto(entities[i]);
if(dto != null) {
dtos.push(dto);
}
}
}
return dtos;
}
}
interface EntityDtoMapHandlers<TEntity, TDto> {
mapEntity?: (dto: Partial<TDto>, target?: TEntity) => TEntity;
mapDto?: (entity: TEntity) => TDto;
} | 22.617647 | 69 | 0.579974 | 50 | 5 | 0 | 6 | 10 | 3 | 2 | 0 | 2 | 2 | 0 | 6.6 | 451 | 0.02439 | 0.022173 | 0.006652 | 0.004435 | 0 | 0 | 0.083333 | 0.307123 | export class EntityDtoMap<TEntity, TDto> {
private readonly _handlers;
public constructor(handlers) {
this._handlers = handlers ?? {};
}
public mapEntity(dto, target?) {
let entity = null;
if(dto != null && this._handlers.mapEntity != null) {
entity = this._handlers.mapEntity({ ...dto }, target);
}
return entity;
}
public mapDto(entity) {
let dto = null;
if(entity != null && this._handlers.mapDto != null) {
dto = this._handlers.mapDto({ ...entity });
}
return dto;
}
public mapEntities(dtos) {
const entities = [];
if(dtos != null) {
const length = dtos.length;
for(let i = 0; i < length; i++) {
const entity = this.mapEntity(dtos[i]);
if(entity != null) {
entities.push(entity);
}
}
}
return entities;
}
public mapDtos(entities) {
const dtos = [];
if(entities != null) {
const length = entities.length;
for(let i = 0; i < length; i++) {
const dto = this.mapDto(entities[i]);
if(dto != null) {
dtos.push(dto);
}
}
}
return dtos;
}
}
interface EntityDtoMapHandlers<TEntity, TDto> {
mapEntity?;
mapDto?;
} |
ff56974a272b67cf77b2e51777c62f45852426c2 | 2,249 | ts | TypeScript | src/validation/hasAtMostRepeatingOrConsecutiveCharacters.ts | backk-node/backk | 01ac30c22df82a7569cc5bf363e8c6cd9669eea9 | [
"MIT"
] | 22 | 2022-01-14T12:06:57.000Z | 2022-03-25T02:39:15.000Z | src/validation/hasAtMostRepeatingOrConsecutiveCharacters.ts | backk-node/backk | 01ac30c22df82a7569cc5bf363e8c6cd9669eea9 | [
"MIT"
] | null | null | null | src/validation/hasAtMostRepeatingOrConsecutiveCharacters.ts | backk-node/backk | 01ac30c22df82a7569cc5bf363e8c6cd9669eea9 | [
"MIT"
] | 2 | 2022-01-21T12:30:52.000Z | 2022-03-11T15:34:25.000Z | export default function hasAtMostRepeatingOrConsecutiveCharacters(str: string, atMostCount: number): boolean {
if (atMostCount > 26) {
throw new Error('atMostCount must be less than 26');
}
if (str.length > 26) {
return true;
}
// noinspection AssignmentToFunctionParameterJS
str = str.toLowerCase();
let maxConsecutiveIdenticalCharacterCount = 0;
for (let i = 0; i < str.length; i++) {
const character = str[i];
let consecutiveIdenticalCharacterCount = 1;
for (let j = i + 1; j < str.length; j++) {
if (str[j] === character) {
consecutiveIdenticalCharacterCount++;
} else {
// noinspection BreakStatementJS
break;
}
if (consecutiveIdenticalCharacterCount > maxConsecutiveIdenticalCharacterCount) {
maxConsecutiveIdenticalCharacterCount = consecutiveIdenticalCharacterCount;
}
if (consecutiveIdenticalCharacterCount > atMostCount) {
return false;
}
}
}
let maxAlphabeticallyConsecutiveCharacterCount = 0;
for (let i = 0; i < str.length; i++) {
let charCode = str.charCodeAt(i);
let alphabeticallyConsecutiveCharacterCount = 1;
for (let j = i + 1; j < str.length; j++) {
if (str.charCodeAt(j) === charCode + 1) {
alphabeticallyConsecutiveCharacterCount++;
charCode++;
} else {
// noinspection BreakStatementJS
break;
}
if (alphabeticallyConsecutiveCharacterCount > maxAlphabeticallyConsecutiveCharacterCount) {
maxAlphabeticallyConsecutiveCharacterCount = alphabeticallyConsecutiveCharacterCount;
}
if (alphabeticallyConsecutiveCharacterCount > atMostCount) {
return false;
}
}
}
let maxInKeyboardLayoutConsecutiveLetterCount = 0;
const letters = 'qwertyuiopasdfghjklzxcvbnm';
for (let i = 0; i < str.length; i++) {
for (let j = 1; j <= str.length - i; j++) {
if (letters.indexOf(str.slice(i, i + j)) !== -1) {
if (j > maxInKeyboardLayoutConsecutiveLetterCount) {
maxInKeyboardLayoutConsecutiveLetterCount = j;
if (maxInKeyboardLayoutConsecutiveLetterCount > atMostCount) {
return false;
}
}
}
}
}
return true;
}
| 28.833333 | 110 | 0.647843 | 61 | 1 | 0 | 2 | 14 | 0 | 0 | 0 | 3 | 0 | 0 | 59 | 591 | 0.005076 | 0.023689 | 0 | 0 | 0 | 0 | 0.176471 | 0.259322 | export default function hasAtMostRepeatingOrConsecutiveCharacters(str, atMostCount) {
if (atMostCount > 26) {
throw new Error('atMostCount must be less than 26');
}
if (str.length > 26) {
return true;
}
// noinspection AssignmentToFunctionParameterJS
str = str.toLowerCase();
let maxConsecutiveIdenticalCharacterCount = 0;
for (let i = 0; i < str.length; i++) {
const character = str[i];
let consecutiveIdenticalCharacterCount = 1;
for (let j = i + 1; j < str.length; j++) {
if (str[j] === character) {
consecutiveIdenticalCharacterCount++;
} else {
// noinspection BreakStatementJS
break;
}
if (consecutiveIdenticalCharacterCount > maxConsecutiveIdenticalCharacterCount) {
maxConsecutiveIdenticalCharacterCount = consecutiveIdenticalCharacterCount;
}
if (consecutiveIdenticalCharacterCount > atMostCount) {
return false;
}
}
}
let maxAlphabeticallyConsecutiveCharacterCount = 0;
for (let i = 0; i < str.length; i++) {
let charCode = str.charCodeAt(i);
let alphabeticallyConsecutiveCharacterCount = 1;
for (let j = i + 1; j < str.length; j++) {
if (str.charCodeAt(j) === charCode + 1) {
alphabeticallyConsecutiveCharacterCount++;
charCode++;
} else {
// noinspection BreakStatementJS
break;
}
if (alphabeticallyConsecutiveCharacterCount > maxAlphabeticallyConsecutiveCharacterCount) {
maxAlphabeticallyConsecutiveCharacterCount = alphabeticallyConsecutiveCharacterCount;
}
if (alphabeticallyConsecutiveCharacterCount > atMostCount) {
return false;
}
}
}
let maxInKeyboardLayoutConsecutiveLetterCount = 0;
const letters = 'qwertyuiopasdfghjklzxcvbnm';
for (let i = 0; i < str.length; i++) {
for (let j = 1; j <= str.length - i; j++) {
if (letters.indexOf(str.slice(i, i + j)) !== -1) {
if (j > maxInKeyboardLayoutConsecutiveLetterCount) {
maxInKeyboardLayoutConsecutiveLetterCount = j;
if (maxInKeyboardLayoutConsecutiveLetterCount > atMostCount) {
return false;
}
}
}
}
}
return true;
}
|
bd48b8ee0cee1d313c8a078ad32fb233e6d0c526 | 6,625 | tsx | TypeScript | docs/components/custom/.demos/data/graph.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/graph.tsx | kdcloudone/charts | 9a3b930d171ae89732c3895d03e552d94b3e0fbc | [
"Apache-2.0"
] | null | null | null | docs/components/custom/.demos/data/graph.tsx | kdcloudone/charts | 9a3b930d171ae89732c3895d03e552d94b3e0fbc | [
"Apache-2.0"
] | null | null | null | export const normal_color = 'rgba(31, 34, 70, 1)';
export const emphasis_color = 'rgba(0, 210, 255, 1)';
export const blur_color = '#ff0000';
export const normal_style = {
itemStyle: {
color: normal_color,
},
};
const lineStarter_style = {
itemStyle: {
color: emphasis_color,
borderWidth: 5,
borderColor: '#bae7ff',
},
label: {
color: emphasis_color,
},
};
const emphasis_style = {
itemStyle: {
color: emphasis_color,
},
};
export const all_style = {
lineStyle: {
color: emphasis_color,
},
itemStyle: {
color: emphasis_color,
borderColor: 'rgba(163, 239, 255, 1)',
borderWidth: 4,
},
label: {
color: 'rgba(249, 249, 249, 1)',
},
};
/* ---------------------
* !!! 不同link的样式 !!!
* --------------------- */
const link_style_large = {
lineStyle: {
color: emphasis_color,
width: 12,
},
itemStyle: {
color: emphasis_color,
},
};
const link_style_medium = {
lineStyle: {
color: emphasis_color,
width: 6,
},
itemStyle: {
color: emphasis_color,
},
};
const link_style_small = {
lineStyle: {
color: emphasis_color,
width: 3,
},
itemStyle: {
color: emphasis_color,
},
};
/* ---------------
* !!! 商品数据 !!!
* --------------- */
function returnProductData() {
const productData = [
{
name: 'XX M 40',
id: 1,
value: 'XX M 40',
...lineStarter_style,
},
{
name: 'XX 12',
id: 2,
value: 'XX 12',
...emphasis_style,
},
{
name: 'Ipad pro',
id: 3,
},
{
name: 'XX pro',
id: 4,
},
{
name: 'XXXX11',
id: 5,
},
{
name: 'XX手环',
id: 6,
},
{
name: 'XX手表',
id: 7,
},
{
name: 'XX手环',
id: 8,
},
{
name: 'XX手环',
id: 9,
},
{
name: 'XX手环',
id: 10,
},
{
name: 'XX手环',
id: 11,
...emphasis_style,
},
{
name: 'XX耳机',
id: 12,
...emphasis_style,
},
{
name: '手机壳',
id: 13,
...emphasis_style,
},
{
name: '无线鼠标',
id: 14,
...emphasis_style,
},
{
name: '无线充电器',
id: 15,
...emphasis_style,
},
{
name: '手持风扇',
id: 16,
...emphasis_style,
},
{
name: 'XX',
id: 17,
...emphasis_style,
},
{
name: '充电线',
id: 18,
},
{
name: 'XX',
id: 19,
},
];
return productData;
}
/* ---------------
* !!! 连线数据 !!!
* --------------- */
function returnLinkData() {
const linkArrayList = [
{
emphasis_large: [1],
emphasis_medium: [8, 9, 10],
emphasis_small: [11, 12, 13, 14, 15, 16],
normal: [],
},
{
emphasis_large: [],
emphasis_medium: [],
emphasis_small: [],
normal: [],
},
{
emphasis_large: [],
emphasis_medium: [],
emphasis_small: [],
normal: [17, 8],
},
{
emphasis_large: [],
emphasis_medium: [],
emphasis_small: [],
normal: [17, 8],
},
{
emphasis_large: [],
emphasis_medium: [],
emphasis_small: [],
normal: [6, 7, 9],
},
{
emphasis_large: [],
emphasis_medium: [],
emphasis_small: [],
normal: [12],
},
{
emphasis_large: [],
emphasis_medium: [],
emphasis_small: [],
normal: [4],
},
{
emphasis_large: [],
emphasis_medium: [],
emphasis_small: [],
normal: [4],
},
{
emphasis_large: [],
emphasis_medium: [],
emphasis_small: [],
normal: [2, 3],
},
{
emphasis_large: [],
emphasis_medium: [],
emphasis_small: [],
normal: [4],
},
{
emphasis_large: [],
emphasis_medium: [],
emphasis_small: [],
normal: [8, 15],
},
{
emphasis_large: [],
emphasis_medium: [],
emphasis_small: [],
normal: [6, 9],
},
{
emphasis_large: [],
emphasis_medium: [],
emphasis_small: [],
normal: [9],
},
{
emphasis_large: [],
emphasis_medium: [],
emphasis_small: [],
normal: [],
},
{
emphasis_large: [],
emphasis_medium: [],
emphasis_small: [],
normal: [12],
},
{
emphasis_large: [],
emphasis_medium: [],
emphasis_small: [],
normal: [],
},
{
emphasis_large: [],
emphasis_medium: [],
emphasis_small: [],
normal: [2, 3],
},
{
emphasis_large: [],
emphasis_medium: [],
emphasis_small: [],
normal: [],
},
{
emphasis_large: [],
emphasis_medium: [],
emphasis_small: [],
normal: [17, 8],
},
];
let linkData: any[] = [];
for (let i = 0; i < linkArrayList.length; ++i) {
linkArrayList[i].emphasis_large.forEach(ele => {
linkData.push({
source: i,
target: ele,
...link_style_large,
});
});
linkArrayList[i].emphasis_medium.forEach(ele => {
linkData.push({
souce: i,
target: ele,
...link_style_medium,
});
});
linkArrayList[i].emphasis_small.forEach(ele => {
linkData.push({
source: i,
target: ele,
...link_style_small,
});
});
linkArrayList[i].normal.forEach(ele => {
linkData.push({
source: i,
target: ele,
...normal_style,
});
});
}
/* emphasis-medium导入的时候有点问题(原因不明),现在是手动push到linkData数组 */
linkData.push({
source: 0,
target: 10,
...link_style_medium,
});
return linkData;
}
/* ECharts配置项 */
export default {
backgroundColor: '#0c1223',
legend: {
show: false,
},
tooltip: { show: false },
series: [
{
type: 'graph',
layout: 'circular',
circular: {
rotateLabel: true,
},
legendHoverLink: true,
symbolSize: 35,
zlevel: 10,
animationDuration: 500,
animationEasing: 'quinticInOut',
animationDurationUpdate: 500,
animationEasingUpdate: 'quinticInOut',
data: returnProductData(),
links: returnLinkData(),
zoom: 0.65,
label: {
show: true,
fontSize: '2.2rem',
color: 'rgba(249, 249, 249, 1)',
position: 'right',
formatter: '{b}',
distance: 15,
rotate: 45,
},
itemStyle: {
color: normal_color,
},
lineStyle: {
show: true,
width: 2,
color: normal_color,
curveness: 0.3,
},
},
],
};
| 17.434211 | 59 | 0.466868 | 354 | 6 | 0 | 4 | 14 | 0 | 2 | 1 | 0 | 0 | 0 | 43.833333 | 2,131 | 0.004693 | 0.00657 | 0 | 0 | 0 | 0.041667 | 0 | 0.202482 | export const normal_color = 'rgba(31, 34, 70, 1)';
export const emphasis_color = 'rgba(0, 210, 255, 1)';
export const blur_color = '#ff0000';
export const normal_style = {
itemStyle: {
color: normal_color,
},
};
const lineStarter_style = {
itemStyle: {
color: emphasis_color,
borderWidth: 5,
borderColor: '#bae7ff',
},
label: {
color: emphasis_color,
},
};
const emphasis_style = {
itemStyle: {
color: emphasis_color,
},
};
export const all_style = {
lineStyle: {
color: emphasis_color,
},
itemStyle: {
color: emphasis_color,
borderColor: 'rgba(163, 239, 255, 1)',
borderWidth: 4,
},
label: {
color: 'rgba(249, 249, 249, 1)',
},
};
/* ---------------------
* !!! 不同link的样式 !!!
* --------------------- */
const link_style_large = {
lineStyle: {
color: emphasis_color,
width: 12,
},
itemStyle: {
color: emphasis_color,
},
};
const link_style_medium = {
lineStyle: {
color: emphasis_color,
width: 6,
},
itemStyle: {
color: emphasis_color,
},
};
const link_style_small = {
lineStyle: {
color: emphasis_color,
width: 3,
},
itemStyle: {
color: emphasis_color,
},
};
/* ---------------
* !!! 商品数据 !!!
* --------------- */
/* Example usages of 'returnProductData' are shown below:
returnProductData();
*/
function returnProductData() {
const productData = [
{
name: 'XX M 40',
id: 1,
value: 'XX M 40',
...lineStarter_style,
},
{
name: 'XX 12',
id: 2,
value: 'XX 12',
...emphasis_style,
},
{
name: 'Ipad pro',
id: 3,
},
{
name: 'XX pro',
id: 4,
},
{
name: 'XXXX11',
id: 5,
},
{
name: 'XX手环',
id: 6,
},
{
name: 'XX手表',
id: 7,
},
{
name: 'XX手环',
id: 8,
},
{
name: 'XX手环',
id: 9,
},
{
name: 'XX手环',
id: 10,
},
{
name: 'XX手环',
id: 11,
...emphasis_style,
},
{
name: 'XX耳机',
id: 12,
...emphasis_style,
},
{
name: '手机壳',
id: 13,
...emphasis_style,
},
{
name: '无线鼠标',
id: 14,
...emphasis_style,
},
{
name: '无线充电器',
id: 15,
...emphasis_style,
},
{
name: '手持风扇',
id: 16,
...emphasis_style,
},
{
name: 'XX',
id: 17,
...emphasis_style,
},
{
name: '充电线',
id: 18,
},
{
name: 'XX',
id: 19,
},
];
return productData;
}
/* ---------------
* !!! 连线数据 !!!
* --------------- */
/* Example usages of 'returnLinkData' are shown below:
returnLinkData();
*/
function returnLinkData() {
const linkArrayList = [
{
emphasis_large: [1],
emphasis_medium: [8, 9, 10],
emphasis_small: [11, 12, 13, 14, 15, 16],
normal: [],
},
{
emphasis_large: [],
emphasis_medium: [],
emphasis_small: [],
normal: [],
},
{
emphasis_large: [],
emphasis_medium: [],
emphasis_small: [],
normal: [17, 8],
},
{
emphasis_large: [],
emphasis_medium: [],
emphasis_small: [],
normal: [17, 8],
},
{
emphasis_large: [],
emphasis_medium: [],
emphasis_small: [],
normal: [6, 7, 9],
},
{
emphasis_large: [],
emphasis_medium: [],
emphasis_small: [],
normal: [12],
},
{
emphasis_large: [],
emphasis_medium: [],
emphasis_small: [],
normal: [4],
},
{
emphasis_large: [],
emphasis_medium: [],
emphasis_small: [],
normal: [4],
},
{
emphasis_large: [],
emphasis_medium: [],
emphasis_small: [],
normal: [2, 3],
},
{
emphasis_large: [],
emphasis_medium: [],
emphasis_small: [],
normal: [4],
},
{
emphasis_large: [],
emphasis_medium: [],
emphasis_small: [],
normal: [8, 15],
},
{
emphasis_large: [],
emphasis_medium: [],
emphasis_small: [],
normal: [6, 9],
},
{
emphasis_large: [],
emphasis_medium: [],
emphasis_small: [],
normal: [9],
},
{
emphasis_large: [],
emphasis_medium: [],
emphasis_small: [],
normal: [],
},
{
emphasis_large: [],
emphasis_medium: [],
emphasis_small: [],
normal: [12],
},
{
emphasis_large: [],
emphasis_medium: [],
emphasis_small: [],
normal: [],
},
{
emphasis_large: [],
emphasis_medium: [],
emphasis_small: [],
normal: [2, 3],
},
{
emphasis_large: [],
emphasis_medium: [],
emphasis_small: [],
normal: [],
},
{
emphasis_large: [],
emphasis_medium: [],
emphasis_small: [],
normal: [17, 8],
},
];
let linkData = [];
for (let i = 0; i < linkArrayList.length; ++i) {
linkArrayList[i].emphasis_large.forEach(ele => {
linkData.push({
source: i,
target: ele,
...link_style_large,
});
});
linkArrayList[i].emphasis_medium.forEach(ele => {
linkData.push({
souce: i,
target: ele,
...link_style_medium,
});
});
linkArrayList[i].emphasis_small.forEach(ele => {
linkData.push({
source: i,
target: ele,
...link_style_small,
});
});
linkArrayList[i].normal.forEach(ele => {
linkData.push({
source: i,
target: ele,
...normal_style,
});
});
}
/* emphasis-medium导入的时候有点问题(原因不明),现在是手动push到linkData数组 */
linkData.push({
source: 0,
target: 10,
...link_style_medium,
});
return linkData;
}
/* ECharts配置项 */
export default {
backgroundColor: '#0c1223',
legend: {
show: false,
},
tooltip: { show: false },
series: [
{
type: 'graph',
layout: 'circular',
circular: {
rotateLabel: true,
},
legendHoverLink: true,
symbolSize: 35,
zlevel: 10,
animationDuration: 500,
animationEasing: 'quinticInOut',
animationDurationUpdate: 500,
animationEasingUpdate: 'quinticInOut',
data: returnProductData(),
links: returnLinkData(),
zoom: 0.65,
label: {
show: true,
fontSize: '2.2rem',
color: 'rgba(249, 249, 249, 1)',
position: 'right',
formatter: '{b}',
distance: 15,
rotate: 45,
},
itemStyle: {
color: normal_color,
},
lineStyle: {
show: true,
width: 2,
color: normal_color,
curveness: 0.3,
},
},
],
};
|
bd5fedd15b33868f0983320e9179fbd4b6751d7e | 2,354 | ts | TypeScript | src/days/day2/day2.ts | pmarflee/adventofcode-ts-2021 | 84f7919eeec06b7e6b5321c7311e3c902c659692 | [
"MIT"
] | 1 | 2022-01-10T07:57:07.000Z | 2022-01-10T07:57:07.000Z | src/days/day2/day2.ts | pmarflee/adventofcode-ts-2021 | 84f7919eeec06b7e6b5321c7311e3c902c659692 | [
"MIT"
] | null | null | null | src/days/day2/day2.ts | pmarflee/adventofcode-ts-2021 | 84f7919eeec06b7e6b5321c7311e3c902c659692 | [
"MIT"
] | null | null | null | export default class Day2 {
public static calculatePart1(input: string[]) : number {
const reducer = (state: Position, i: Instruction) : Position =>
{
switch (i.direction) {
case Direction.Forward:
return { horizontal: state.horizontal + i.distance, depth: state.depth };
case Direction.Down:
return { horizontal: state.horizontal, depth: state.depth + i.distance };
case Direction.Up:
return { horizontal: state.horizontal, depth: state.depth - i.distance };
}
};
return Day2.calculate(input, reducer, { horizontal: 0, depth: 0 });
}
public static calculatePart2(input: string[]) : number {
const reducer = (state: Position, i: Instruction) : Position =>
{
const aim = state.aim ?? 0;
switch (i.direction) {
case Direction.Forward:
return { horizontal: state.horizontal + i.distance,
depth: state.depth + (aim * i.distance),
aim: aim };
case Direction.Down:
return { horizontal: state.horizontal, depth: state.depth, aim: aim + i.distance };
case Direction.Up:
return { horizontal: state.horizontal, depth: state.depth, aim: aim - i.distance };
}
};
return Day2.calculate(input, reducer, { horizontal: 0, depth: 0, aim: 0 });
}
private static calculate(
input: string[],
reducer: (state: Position, i: Instruction) => Position,
initialState: Position) : number {
const position = input
.map(Day2.parse)
.reduce(reducer, initialState);
return position.horizontal * position.depth;
}
private static parse(input: string) : Instruction {
const parts = input.split(' ');
return {
direction: parts[0] as Direction,
distance: parseInt(parts[1], 10)
};
}
}
enum Direction {
Forward = "forward",
Down = "down",
Up = "up"
}
interface Instruction {
direction: Direction;
distance: number;
}
interface Position {
horizontal: number;
depth: number;
aim?: number;
} | 32.246575 | 103 | 0.536109 | 63 | 6 | 0 | 10 | 5 | 5 | 1 | 0 | 11 | 3 | 1 | 9.166667 | 513 | 0.031189 | 0.009747 | 0.009747 | 0.005848 | 0.001949 | 0 | 0.423077 | 0.283737 | export default class Day2 {
public static calculatePart1(input) {
/* Example usages of 'reducer' are shown below:
Day2.calculate(input, reducer, { horizontal: 0, depth: 0 });
Day2.calculate(input, reducer, { horizontal: 0, depth: 0, aim: 0 });
;
input
.map(Day2.parse)
.reduce(reducer, initialState);
*/
const reducer = (state, i) =>
{
switch (i.direction) {
case Direction.Forward:
return { horizontal: state.horizontal + i.distance, depth: state.depth };
case Direction.Down:
return { horizontal: state.horizontal, depth: state.depth + i.distance };
case Direction.Up:
return { horizontal: state.horizontal, depth: state.depth - i.distance };
}
};
return Day2.calculate(input, reducer, { horizontal: 0, depth: 0 });
}
public static calculatePart2(input) {
/* Example usages of 'reducer' are shown below:
Day2.calculate(input, reducer, { horizontal: 0, depth: 0 });
Day2.calculate(input, reducer, { horizontal: 0, depth: 0, aim: 0 });
;
input
.map(Day2.parse)
.reduce(reducer, initialState);
*/
const reducer = (state, i) =>
{
const aim = state.aim ?? 0;
switch (i.direction) {
case Direction.Forward:
return { horizontal: state.horizontal + i.distance,
depth: state.depth + (aim * i.distance),
aim: aim };
case Direction.Down:
return { horizontal: state.horizontal, depth: state.depth, aim: aim + i.distance };
case Direction.Up:
return { horizontal: state.horizontal, depth: state.depth, aim: aim - i.distance };
}
};
return Day2.calculate(input, reducer, { horizontal: 0, depth: 0, aim: 0 });
}
private static calculate(
input,
reducer,
initialState) {
const position = input
.map(Day2.parse)
.reduce(reducer, initialState);
return position.horizontal * position.depth;
}
private static parse(input) {
const parts = input.split(' ');
return {
direction: parts[0] as Direction,
distance: parseInt(parts[1], 10)
};
}
}
enum Direction {
Forward = "forward",
Down = "down",
Up = "up"
}
interface Instruction {
direction;
distance;
}
interface Position {
horizontal;
depth;
aim?;
} |
bd61e72aa771a69a8136d85f0c8df4cbcdbe95ae | 2,187 | ts | TypeScript | event.ts | ThomLlobEce/nh | d5a2ce0aa7bed46ac08828f4cef27fa011feddd1 | [
"MIT"
] | null | null | null | event.ts | ThomLlobEce/nh | d5a2ce0aa7bed46ac08828f4cef27fa011feddd1 | [
"MIT"
] | 1 | 2022-01-22T09:58:40.000Z | 2022-01-22T09:58:40.000Z | event.ts | ThomLlobEce/nh | d5a2ce0aa7bed46ac08828f4cef27fa011feddd1 | [
"MIT"
] | null | null | null | let months = ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"]
export default class Event {
title: string
location: string
startMinutes: string
startHours: string
startDay: string
startMonth: string
startYear: string
endMinutes: string
endHours: string
endDay: string
endMonth: string
endYear: string
color: string
helper: string
helperFirstName: string
constructor(title: string, location: string, startMinutes: string, startHours: string, startDay: string, startMonth: string, startYear: string,
endMinutes: string, endHours: string, endDay: string, endMonth: string, endYear: string){
this.title=title
this.location=location
this.startMinutes = startMinutes
this.startHours = startHours
this.startDay=startDay
this.startMonth=startMonth
this.startYear=startYear
this.endDay=endDay
this.endMonth=endMonth
this.endYear=endYear
this.endMinutes = endMinutes
this.endHours = endHours
}
addColor(color:string) {
this.color = color
}
addHelper(email:string, firstName:string){
this.helper=email
this.helperFirstName=firstName
}
equals(object):boolean{
if(object.title === this.title && object.location === this.location){
let beginThis = new Date(months[parseInt(this.startMonth)] + '-' + this.startDay + ', ' + this.startYear + ' ' + this.startHours + ':' + this.startMinutes + ':00')
let endThis = new Date(months[parseInt(this.endMonth)] + '-' + this.endDay + ', ' + this.endYear + ' ' + this.endHours + ':' + this.endMinutes + ':00')
let beginObject = new Date(object.start._seconds*1000)
let endObject = new Date(object.end._seconds*1000)
if(beginObject.getTime() === beginThis.getTime() && endObject.getTime() === endThis.getTime()){
return true
}
else
return false
}
else
return false
}
} | 35.852459 | 175 | 0.604024 | 55 | 4 | 0 | 16 | 5 | 15 | 0 | 0 | 31 | 1 | 0 | 7 | 541 | 0.036969 | 0.009242 | 0.027726 | 0.001848 | 0 | 0 | 0.775 | 0.288739 | let months = ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"]
export default class Event {
title
location
startMinutes
startHours
startDay
startMonth
startYear
endMinutes
endHours
endDay
endMonth
endYear
color
helper
helperFirstName
constructor(title, location, startMinutes, startHours, startDay, startMonth, startYear,
endMinutes, endHours, endDay, endMonth, endYear){
this.title=title
this.location=location
this.startMinutes = startMinutes
this.startHours = startHours
this.startDay=startDay
this.startMonth=startMonth
this.startYear=startYear
this.endDay=endDay
this.endMonth=endMonth
this.endYear=endYear
this.endMinutes = endMinutes
this.endHours = endHours
}
addColor(color) {
this.color = color
}
addHelper(email, firstName){
this.helper=email
this.helperFirstName=firstName
}
equals(object){
if(object.title === this.title && object.location === this.location){
let beginThis = new Date(months[parseInt(this.startMonth)] + '-' + this.startDay + ', ' + this.startYear + ' ' + this.startHours + ':' + this.startMinutes + ':00')
let endThis = new Date(months[parseInt(this.endMonth)] + '-' + this.endDay + ', ' + this.endYear + ' ' + this.endHours + ':' + this.endMinutes + ':00')
let beginObject = new Date(object.start._seconds*1000)
let endObject = new Date(object.end._seconds*1000)
if(beginObject.getTime() === beginThis.getTime() && endObject.getTime() === endThis.getTime()){
return true
}
else
return false
}
else
return false
}
} |
bd692982ce34e923bb631e717089727ef903435e | 6,180 | ts | TypeScript | src/lib/utils.ts | qt-dork/wordle-image-generator | 3453da6ac5e462087d300ad5eb9dd199c3fafe89 | [
"MIT"
] | 2 | 2022-01-25T05:42:27.000Z | 2022-01-25T06:53:06.000Z | src/lib/utils.ts | qt-dork/wordle-image-generator | 3453da6ac5e462087d300ad5eb9dd199c3fafe89 | [
"MIT"
] | 5 | 2022-01-25T08:43:44.000Z | 2022-03-01T18:34:17.000Z | src/lib/utils.ts | qt-dork/wordle-image-generator | 3453da6ac5e462087d300ad5eb9dd199c3fafe89 | [
"MIT"
] | 2 | 2022-01-25T09:53:11.000Z | 2022-02-19T06:57:10.000Z | // Duck Everlasting's change to firstLineTester
// Linked here: https://github.com/qt-dork/wordle-image-generator/pull/3
export const firstLine = (line: string) => {
const regex = /(?<day>.* \d+) (?<count>[1-6x]\/6]*?)/gi
const match = regex.exec(line);
return {
day: match?.groups.day === undefined ? '' : match?.groups.day,
score: match?.groups.count === undefined ? '' : match?.groups.count,
};
}
// Functions are based off of Cariad's wonderful wa11y website
export const describe = (indexes: number[]) => {
if (indexes.length === 0) return null;
const ords = indexes.map((i) => ord(i));
if (ords.length === 1) return ords[0];
return ords.reduce((text, value, i, array) => {
return text + (i < array.length - 1 ? ', ' : ' and ') + value;
});
}
export const describeLine = (line: string, num: number, chopAggression: number) => {
const decoded = blockTypes(line);
const hasPerfect = decoded.perfectIndexes.length > 0;
const hasMisplaced = decoded.misplacedIndexes.length > 0;
const perfectWord = chopAggression >= 8 ? 'yes' : 'perfect';
const perfect = hasPerfect
? `${describe(decoded.perfectIndexes)} ${perfectWord}`
: null;
const misplacedList = describe(decoded.misplacedIndexes);
const wrongPlace =
chopAggression >= 6
? chopAggression >= 7
? 'no'
: 'wrong'
: 'in the wrong place';
const correctBut =
chopAggression >= 3
? `${misplacedList} ${wrongPlace}`
: `${misplacedList} correct but ${wrongPlace}`;
const perfectBut =
chopAggression >= 2
? `. ${misplacedList} ${wrongPlace}`
: `, but ${misplacedList} ${wrongPlace}`;
const misplaced = hasPerfect ? perfectBut : correctBut;
let explanation = '';
if (!hasPerfect && !hasMisplaced) explanation = 'Nothing.';
else if (decoded.perfectIndexes.length === 5) explanation = 'Won!';
else if (decoded.misplacedIndexes.length === 5)
explanation =
chopAggression >= 1
? 'all in the wrong order.'
: 'all the correct letters but in the wrong order.';
else if (hasPerfect && hasMisplaced)
explanation = `${perfect}${misplaced}.`;
else if (hasMisplaced) explanation = `${misplaced}.`;
else explanation = `${perfect}.`;
const prefix = chopAggression >= 5 ? `${num}.` : `Line ${num}:`;
const result = `${prefix} ${explanation}\n`;
if (chopAggression >= 4) return result.replaceAll(' and ', ' & ');
return result;
}
export const ord = (i: number) => {
switch (i) {
case 1:
return '1st';
case 2:
return '2nd';
case 3:
return '3rd';
default:
return `${i}th`;
}
}
export const blockTypes = (line: string) => {
let actualIndex = 0;
let visualIndex = 1;
const misplacedIndexes = [];
const perfectIndexes = [];
while (actualIndex < line.length) {
switch (line.charCodeAt(actualIndex)) {
// Dark mode:
case 11035:
// Light mode:
// falls through
case 11036:
actualIndex += 1;
visualIndex += 1;
break;
case 55357:
switch (line.charCodeAt(actualIndex + 1)) {
// High contrast:
case 57318:
// Regular contrast:
// falls through
case 57320:
misplacedIndexes.push(visualIndex++);
break;
// High contrast:
case 57319:
// Regular contrast:
// falls through
case 57321:
perfectIndexes.push(visualIndex++);
break;
default:
return;
}
actualIndex += 2;
break;
default:
return;
}
}
return {
misplacedIndexes: misplacedIndexes,
perfectIndexes: perfectIndexes,
};
}
export const isGameLine = (line: string) => {
return line && line.length > 0 && blockTypes(line) !== undefined;
}
export const deviceIsMobile = ():boolean => {
let Result = false
// eslint-disable-next-line @typescript-eslint/ban-ts-comment
// @ts-ignore don't care about literal indexing
// eslint-disable-next-line no-useless-escape
;(function(a){if(/(android|bb\d+|meego).+mobile|avantgo|bada\/|blackberry|blazer|compal|elaine|fennec|hiptop|iemobile|ip(hone|od)|iris|kindle|lge |maemo|midp|mmp|mobile.+firefox|netfront|opera m(ob|in)i|palm( os)?|phone|p(ixi|re)\/|plucker|pocket|psp|series(4|6)0|symbian|treo|up\.(browser|link)|vodafone|wap|windows ce|xda|xiino|android|ipad|playbook|silk/i.test(a)||/1207|6310|6590|3gso|4thp|50[1-6]i|770s|802s|a wa|abac|ac(er|oo|s\-)|ai(ko|rn)|al(av|ca|co)|amoi|an(ex|ny|yw)|aptu|ar(ch|go)|as(te|us)|attw|au(di|\-m|r |s )|avan|be(ck|ll|nq)|bi(lb|rd)|bl(ac|az)|br(e|v)w|bumb|bw\-(n|u)|c55\/|capi|ccwa|cdm\-|cell|chtm|cldc|cmd\-|co(mp|nd)|craw|da(it|ll|ng)|dbte|dc\-s|devi|dica|dmob|do(c|p)o|ds(12|\-d)|el(49|ai)|em(l2|ul)|er(ic|k0)|esl8|ez([4-7]0|os|wa|ze)|fetc|fly(\-|_)|g1 u|g560|gene|gf\-5|g\-mo|go(\.w|od)|gr(ad|un)|haie|hcit|hd\-(m|p|t)|hei\-|hi(pt|ta)|hp( i|ip)|hs\-c|ht(c(\-| |_|a|g|p|s|t)|tp)|hu(aw|tc)|i\-(20|go|ma)|i230|iac( |\-|\/)|ibro|idea|ig01|ikom|im1k|inno|ipaq|iris|ja(t|v)a|jbro|jemu|jigs|kddi|keji|kgt( |\/)|klon|kpt |kwc\-|kyo(c|k)|le(no|xi)|lg( g|\/(k|l|u)|50|54|\-[a-w])|libw|lynx|m1\-w|m3ga|m50\/|ma(te|ui|xo)|mc(01|21|ca)|m\-cr|me(rc|ri)|mi(o8|oa|ts)|mmef|mo(01|02|bi|de|do|t(\-| |o|v)|zz)|mt(50|p1|v )|mwbp|mywa|n10[0-2]|n20[2-3]|n30(0|2)|n50(0|2|5)|n7(0(0|1)|10)|ne((c|m)\-|on|tf|wf|wg|wt)|nok(6|i)|nzph|o2im|op(ti|wv)|oran|owg1|p800|pan(a|d|t)|pdxg|pg(13|\-([1-8]|c))|phil|pire|pl(ay|uc)|pn\-2|po(ck|rt|se)|prox|psio|pt\-g|qa\-a|qc(07|12|21|32|60|\-[2-7]|i\-)|qtek|r380|r600|raks|rim9|ro(ve|zo)|s55\/|sa(ge|ma|mm|ms|ny|va)|sc(01|h\-|oo|p\-)|sdk\/|se(c(\-|0|1)|47|mc|nd|ri)|sgh\-|shar|sie(\-|m)|sk\-0|sl(45|id)|sm(al|ar|b3|it|t5)|so(ft|ny)|sp(01|h\-|v\-|v )|sy(01|mb)|t2(18|50)|t6(00|10|18)|ta(gt|lk)|tcl\-|tdg\-|tel(i|m)|tim\-|t\-mo|to(pl|sh)|ts(70|m\-|m3|m5)|tx\-9|up(\.b|g1|si)|utst|v400|v750|veri|vi(rg|te)|vk(40|5[0-3]|\-v)|vm40|voda|vulc|vx(52|53|60|61|70|80|81|83|85|98)|w3c(\-| )|webc|whit|wi(g |nc|nw)|wmlb|wonu|x700|yas\-|your|zeto|zte\-/i.test(a.substr(0,4))) Result = true})(navigator.userAgent||navigator.vendor||window['opera'])
return Result;
} | 40.12987 | 2,072 | 0.608091 | 113 | 10 | 0 | 14 | 28 | 0 | 3 | 0 | 9 | 0 | 0 | 10.2 | 2,483 | 0.009666 | 0.011277 | 0 | 0 | 0 | 0 | 0.173077 | 0.230044 | // Duck Everlasting's change to firstLineTester
// Linked here: https://github.com/qt-dork/wordle-image-generator/pull/3
export const firstLine = (line) => {
const regex = /(?<day>.* \d+) (?<count>[1-6x]\/6]*?)/gi
const match = regex.exec(line);
return {
day: match?.groups.day === undefined ? '' : match?.groups.day,
score: match?.groups.count === undefined ? '' : match?.groups.count,
};
}
// Functions are based off of Cariad's wonderful wa11y website
export /* Example usages of 'describe' are shown below:
describe(decoded.perfectIndexes);
describe(decoded.misplacedIndexes);
*/
const describe = (indexes) => {
if (indexes.length === 0) return null;
const ords = indexes.map((i) => ord(i));
if (ords.length === 1) return ords[0];
return ords.reduce((text, value, i, array) => {
return text + (i < array.length - 1 ? ', ' : ' and ') + value;
});
}
export const describeLine = (line, num, chopAggression) => {
const decoded = blockTypes(line);
const hasPerfect = decoded.perfectIndexes.length > 0;
const hasMisplaced = decoded.misplacedIndexes.length > 0;
const perfectWord = chopAggression >= 8 ? 'yes' : 'perfect';
const perfect = hasPerfect
? `${describe(decoded.perfectIndexes)} ${perfectWord}`
: null;
const misplacedList = describe(decoded.misplacedIndexes);
const wrongPlace =
chopAggression >= 6
? chopAggression >= 7
? 'no'
: 'wrong'
: 'in the wrong place';
const correctBut =
chopAggression >= 3
? `${misplacedList} ${wrongPlace}`
: `${misplacedList} correct but ${wrongPlace}`;
const perfectBut =
chopAggression >= 2
? `. ${misplacedList} ${wrongPlace}`
: `, but ${misplacedList} ${wrongPlace}`;
const misplaced = hasPerfect ? perfectBut : correctBut;
let explanation = '';
if (!hasPerfect && !hasMisplaced) explanation = 'Nothing.';
else if (decoded.perfectIndexes.length === 5) explanation = 'Won!';
else if (decoded.misplacedIndexes.length === 5)
explanation =
chopAggression >= 1
? 'all in the wrong order.'
: 'all the correct letters but in the wrong order.';
else if (hasPerfect && hasMisplaced)
explanation = `${perfect}${misplaced}.`;
else if (hasMisplaced) explanation = `${misplaced}.`;
else explanation = `${perfect}.`;
const prefix = chopAggression >= 5 ? `${num}.` : `Line ${num}:`;
const result = `${prefix} ${explanation}\n`;
if (chopAggression >= 4) return result.replaceAll(' and ', ' & ');
return result;
}
export /* Example usages of 'ord' are shown below:
ord(i);
*/
const ord = (i) => {
switch (i) {
case 1:
return '1st';
case 2:
return '2nd';
case 3:
return '3rd';
default:
return `${i}th`;
}
}
export /* Example usages of 'blockTypes' are shown below:
blockTypes(line);
line && line.length > 0 && blockTypes(line) !== undefined;
*/
const blockTypes = (line) => {
let actualIndex = 0;
let visualIndex = 1;
const misplacedIndexes = [];
const perfectIndexes = [];
while (actualIndex < line.length) {
switch (line.charCodeAt(actualIndex)) {
// Dark mode:
case 11035:
// Light mode:
// falls through
case 11036:
actualIndex += 1;
visualIndex += 1;
break;
case 55357:
switch (line.charCodeAt(actualIndex + 1)) {
// High contrast:
case 57318:
// Regular contrast:
// falls through
case 57320:
misplacedIndexes.push(visualIndex++);
break;
// High contrast:
case 57319:
// Regular contrast:
// falls through
case 57321:
perfectIndexes.push(visualIndex++);
break;
default:
return;
}
actualIndex += 2;
break;
default:
return;
}
}
return {
misplacedIndexes: misplacedIndexes,
perfectIndexes: perfectIndexes,
};
}
export const isGameLine = (line) => {
return line && line.length > 0 && blockTypes(line) !== undefined;
}
export const deviceIsMobile = () => {
let Result = false
// eslint-disable-next-line @typescript-eslint/ban-ts-comment
// @ts-ignore don't care about literal indexing
// eslint-disable-next-line no-useless-escape
;(function(a){if(/(android|bb\d+|meego).+mobile|avantgo|bada\/|blackberry|blazer|compal|elaine|fennec|hiptop|iemobile|ip(hone|od)|iris|kindle|lge |maemo|midp|mmp|mobile.+firefox|netfront|opera m(ob|in)i|palm( os)?|phone|p(ixi|re)\/|plucker|pocket|psp|series(4|6)0|symbian|treo|up\.(browser|link)|vodafone|wap|windows ce|xda|xiino|android|ipad|playbook|silk/i.test(a)||/1207|6310|6590|3gso|4thp|50[1-6]i|770s|802s|a wa|abac|ac(er|oo|s\-)|ai(ko|rn)|al(av|ca|co)|amoi|an(ex|ny|yw)|aptu|ar(ch|go)|as(te|us)|attw|au(di|\-m|r |s )|avan|be(ck|ll|nq)|bi(lb|rd)|bl(ac|az)|br(e|v)w|bumb|bw\-(n|u)|c55\/|capi|ccwa|cdm\-|cell|chtm|cldc|cmd\-|co(mp|nd)|craw|da(it|ll|ng)|dbte|dc\-s|devi|dica|dmob|do(c|p)o|ds(12|\-d)|el(49|ai)|em(l2|ul)|er(ic|k0)|esl8|ez([4-7]0|os|wa|ze)|fetc|fly(\-|_)|g1 u|g560|gene|gf\-5|g\-mo|go(\.w|od)|gr(ad|un)|haie|hcit|hd\-(m|p|t)|hei\-|hi(pt|ta)|hp( i|ip)|hs\-c|ht(c(\-| |_|a|g|p|s|t)|tp)|hu(aw|tc)|i\-(20|go|ma)|i230|iac( |\-|\/)|ibro|idea|ig01|ikom|im1k|inno|ipaq|iris|ja(t|v)a|jbro|jemu|jigs|kddi|keji|kgt( |\/)|klon|kpt |kwc\-|kyo(c|k)|le(no|xi)|lg( g|\/(k|l|u)|50|54|\-[a-w])|libw|lynx|m1\-w|m3ga|m50\/|ma(te|ui|xo)|mc(01|21|ca)|m\-cr|me(rc|ri)|mi(o8|oa|ts)|mmef|mo(01|02|bi|de|do|t(\-| |o|v)|zz)|mt(50|p1|v )|mwbp|mywa|n10[0-2]|n20[2-3]|n30(0|2)|n50(0|2|5)|n7(0(0|1)|10)|ne((c|m)\-|on|tf|wf|wg|wt)|nok(6|i)|nzph|o2im|op(ti|wv)|oran|owg1|p800|pan(a|d|t)|pdxg|pg(13|\-([1-8]|c))|phil|pire|pl(ay|uc)|pn\-2|po(ck|rt|se)|prox|psio|pt\-g|qa\-a|qc(07|12|21|32|60|\-[2-7]|i\-)|qtek|r380|r600|raks|rim9|ro(ve|zo)|s55\/|sa(ge|ma|mm|ms|ny|va)|sc(01|h\-|oo|p\-)|sdk\/|se(c(\-|0|1)|47|mc|nd|ri)|sgh\-|shar|sie(\-|m)|sk\-0|sl(45|id)|sm(al|ar|b3|it|t5)|so(ft|ny)|sp(01|h\-|v\-|v )|sy(01|mb)|t2(18|50)|t6(00|10|18)|ta(gt|lk)|tcl\-|tdg\-|tel(i|m)|tim\-|t\-mo|to(pl|sh)|ts(70|m\-|m3|m5)|tx\-9|up(\.b|g1|si)|utst|v400|v750|veri|vi(rg|te)|vk(40|5[0-3]|\-v)|vm40|voda|vulc|vx(52|53|60|61|70|80|81|83|85|98)|w3c(\-| )|webc|whit|wi(g |nc|nw)|wmlb|wonu|x700|yas\-|your|zeto|zte\-/i.test(a.substr(0,4))) Result = true})(navigator.userAgent||navigator.vendor||window['opera'])
return Result;
} |
bdc86a1ab33b781473ff6d1050be547e6e256877 | 4,052 | ts | TypeScript | packages/kernel/src/functions.ts | thephoenixofthevoid/aurelia | cf28b47b71e9ccf5830757acd6177281b3fd2a31 | [
"MIT"
] | null | null | null | packages/kernel/src/functions.ts | thephoenixofthevoid/aurelia | cf28b47b71e9ccf5830757acd6177281b3fd2a31 | [
"MIT"
] | 1 | 2022-03-03T23:33:13.000Z | 2022-03-03T23:33:13.000Z | packages/kernel/src/functions.ts | josiahhaswell/aurelia | 2fc91fa9a2920f24fcb5224d2e245c18d0e1d797 | [
"MIT"
] | null | null | null | const camelCaseLookup: Record<string, string> = {};
const kebabCaseLookup: Record<string, string> = {};
const isNumericLookup: Record<string, boolean> = {};
/**
* Efficiently determine whether the provided property key is numeric
* (and thus could be an array indexer) or not.
*
* Always returns true for values of type `'number'`.
*
* Otherwise, only returns true for strings that consist only of positive integers.
*
* Results are cached.
*/
export function isNumeric(value: unknown): value is number | string {
switch (typeof value) {
case 'number':
return true;
case 'string': {
const result = isNumericLookup[value];
if (result !== void 0) {
return result;
}
const { length } = value;
if (length === 0) {
return isNumericLookup[value] = false;
}
let ch = 0;
for (let i = 0; i < length; ++i) {
ch = value.charCodeAt(i);
if (ch < 0x30 /*0*/ || ch > 0x39/*9*/) {
return isNumericLookup[value] = false;
}
}
return isNumericLookup[value] = true;
}
default:
return false;
}
}
/**
* Efficiently convert a kebab-cased string to camelCase.
*
* Separators that signal the next character to be capitalized, are: `-`, `.`, `_`.
*
* Primarily used by Aurelia to convert DOM attribute names to ViewModel property names.
*
* Results are cached.
*/
export function camelCase(input: string): string {
// benchmark: http://jsben.ch/qIz4Z
let value = camelCaseLookup[input];
if (value !== void 0) return value;
value = '';
let first = true;
let sep = false;
let char: string;
for (let i = 0, ii = input.length; i < ii; ++i) {
char = input.charAt(i);
if (char === '-' || char === '.' || char === '_') {
sep = true; // skip separators
} else {
value = value + (first ? char.toLowerCase() : (sep ? char.toUpperCase() : char));
sep = false;
}
first = false;
}
return camelCaseLookup[input] = value;
}
/**
* Efficiently convert a camelCased string to kebab-case.
*
* Primarily used by Aurelia to convert ViewModel property names to DOM attribute names.
*
* Results are cached.
*/
export function kebabCase(input: string): string {
// benchmark: http://jsben.ch/v7K9T
let value = kebabCaseLookup[input];
if (value !== void 0) return value;
value = '';
let first = true;
let char: string, lower: string;
for (let i = 0, ii = input.length; i < ii; ++i) {
char = input.charAt(i);
lower = char.toLowerCase();
value = value + (first ? lower : (char !== lower ? `-${lower}` : lower));
first = false;
}
return kebabCaseLookup[input] = value;
}
/**
* Efficiently (up to 10x faster than `Array.from`) convert an `ArrayLike` to a real array.
*
* Primarily used by Aurelia to convert DOM node lists to arrays.
*/
export function toArray<T = unknown>(input: ArrayLike<T>): T[] {
// benchmark: http://jsben.ch/xjsyF
const { length } = input;
const arr = Array(length);
for (let i = 0; i < length; ++i) {
arr[i] = input[i];
}
return arr;
}
const ids: Record<string, number> = {};
/**
* Retrieve the next ID in a sequence for a given string, starting with `1`.
*
* Used by Aurelia to assign unique ID's to controllers and resources.
*
* Aurelia will always prepend the context name with `au$`, so as long as you avoid
* using that convention you should be safe from collisions.
*/
export function nextId(context: string): number {
if (ids[context] === void 0) {
ids[context] = 0;
}
return ++ids[context];
}
/**
* Reset the ID for the given string, so that `nextId` will return `1` again for the next call.
*
* Used by Aurelia to reset ID's in between unit tests.
*/
export function resetId(context: string): void {
ids[context] = 0;
}
/**
* A compare function to pass to `Array.prototype.sort` for sorting numbers.
* This is needed for numeric sort, since the default sorts them as strings.
*/
export function compareNumber(a: number, b: number): number {
return a - b;
}
| 28.335664 | 95 | 0.630553 | 83 | 7 | 0 | 8 | 23 | 0 | 0 | 0 | 26 | 0 | 1 | 9.285714 | 1,179 | 0.012723 | 0.019508 | 0 | 0 | 0.000848 | 0 | 0.684211 | 0.262546 | const camelCaseLookup = {};
const kebabCaseLookup = {};
const isNumericLookup = {};
/**
* Efficiently determine whether the provided property key is numeric
* (and thus could be an array indexer) or not.
*
* Always returns true for values of type `'number'`.
*
* Otherwise, only returns true for strings that consist only of positive integers.
*
* Results are cached.
*/
export function isNumeric(value): value is number | string {
switch (typeof value) {
case 'number':
return true;
case 'string': {
const result = isNumericLookup[value];
if (result !== void 0) {
return result;
}
const { length } = value;
if (length === 0) {
return isNumericLookup[value] = false;
}
let ch = 0;
for (let i = 0; i < length; ++i) {
ch = value.charCodeAt(i);
if (ch < 0x30 /*0*/ || ch > 0x39/*9*/) {
return isNumericLookup[value] = false;
}
}
return isNumericLookup[value] = true;
}
default:
return false;
}
}
/**
* Efficiently convert a kebab-cased string to camelCase.
*
* Separators that signal the next character to be capitalized, are: `-`, `.`, `_`.
*
* Primarily used by Aurelia to convert DOM attribute names to ViewModel property names.
*
* Results are cached.
*/
export function camelCase(input) {
// benchmark: http://jsben.ch/qIz4Z
let value = camelCaseLookup[input];
if (value !== void 0) return value;
value = '';
let first = true;
let sep = false;
let char;
for (let i = 0, ii = input.length; i < ii; ++i) {
char = input.charAt(i);
if (char === '-' || char === '.' || char === '_') {
sep = true; // skip separators
} else {
value = value + (first ? char.toLowerCase() : (sep ? char.toUpperCase() : char));
sep = false;
}
first = false;
}
return camelCaseLookup[input] = value;
}
/**
* Efficiently convert a camelCased string to kebab-case.
*
* Primarily used by Aurelia to convert ViewModel property names to DOM attribute names.
*
* Results are cached.
*/
export function kebabCase(input) {
// benchmark: http://jsben.ch/v7K9T
let value = kebabCaseLookup[input];
if (value !== void 0) return value;
value = '';
let first = true;
let char, lower;
for (let i = 0, ii = input.length; i < ii; ++i) {
char = input.charAt(i);
lower = char.toLowerCase();
value = value + (first ? lower : (char !== lower ? `-${lower}` : lower));
first = false;
}
return kebabCaseLookup[input] = value;
}
/**
* Efficiently (up to 10x faster than `Array.from`) convert an `ArrayLike` to a real array.
*
* Primarily used by Aurelia to convert DOM node lists to arrays.
*/
export function toArray<T = unknown>(input) {
// benchmark: http://jsben.ch/xjsyF
const { length } = input;
const arr = Array(length);
for (let i = 0; i < length; ++i) {
arr[i] = input[i];
}
return arr;
}
const ids = {};
/**
* Retrieve the next ID in a sequence for a given string, starting with `1`.
*
* Used by Aurelia to assign unique ID's to controllers and resources.
*
* Aurelia will always prepend the context name with `au$`, so as long as you avoid
* using that convention you should be safe from collisions.
*/
export function nextId(context) {
if (ids[context] === void 0) {
ids[context] = 0;
}
return ++ids[context];
}
/**
* Reset the ID for the given string, so that `nextId` will return `1` again for the next call.
*
* Used by Aurelia to reset ID's in between unit tests.
*/
export function resetId(context) {
ids[context] = 0;
}
/**
* A compare function to pass to `Array.prototype.sort` for sorting numbers.
* This is needed for numeric sort, since the default sorts them as strings.
*/
export function compareNumber(a, b) {
return a - b;
}
|
bdd2ff5077c0e6c16267629003fee3d708a91d32 | 1,685 | ts | TypeScript | src/controller/webhook/tests/utils/messenger-message-generator.ts | kubo550/node-express-jest-starter | ae98aebc116a2b3f139652aaf8ec2fccc024b519 | [
"MIT"
] | 3 | 2022-03-13T21:49:34.000Z | 2022-03-18T11:10:34.000Z | src/controller/webhook/tests/utils/messenger-message-generator.ts | kubo550/node-express-jest-starter | ae98aebc116a2b3f139652aaf8ec2fccc024b519 | [
"MIT"
] | null | null | null | src/controller/webhook/tests/utils/messenger-message-generator.ts | kubo550/node-express-jest-starter | ae98aebc116a2b3f139652aaf8ec2fccc024b519 | [
"MIT"
] | null | null | null | export class MessengerMessageGenerator {
private senderId: string;
private recipientId: string;
private timestamp: number;
private messageId: string;
private text: string;
private quickReply: {
payload: string;
};
constructor() {
this.senderId = 'sender-id';
this.recipientId = '';
this.timestamp = 1650036539989;
this.messageId = '';
this.text = '';
}
public withSenderId(senderId: string): MessengerMessageGenerator {
this.senderId = senderId;
return this;
}
public withRecipientId(recipientId: string): MessengerMessageGenerator {
this.recipientId = recipientId;
return this;
}
public withTimestamp(timestamp: number): MessengerMessageGenerator {
this.timestamp = timestamp;
return this;
}
public withMessageId(messageId: string): MessengerMessageGenerator {
this.messageId = messageId;
return this;
}
public withText(text: string): MessengerMessageGenerator {
this.text = text;
return this;
}
public withQuickReply(payload: string): MessengerMessageGenerator {
this.quickReply = {
payload,
};
return this;
}
public build(): any {
return {
object: 'page',
entry: [
{
id: this.recipientId,
time: this.timestamp,
messaging: [
{
sender: { id: this.senderId },
recipient: { id: this.recipientId },
timestamp: this.timestamp,
message: {
mid: this.messageId,
text: this.text,
quick_reply: this.quickReply,
},
},
],
},
],
};
}
}
| 22.466667 | 74 | 0.592878 | 66 | 8 | 0 | 6 | 0 | 6 | 0 | 1 | 12 | 1 | 0 | 5 | 400 | 0.035 | 0 | 0.015 | 0.0025 | 0 | 0.05 | 0.6 | 0.254398 | export class MessengerMessageGenerator {
private senderId;
private recipientId;
private timestamp;
private messageId;
private text;
private quickReply;
constructor() {
this.senderId = 'sender-id';
this.recipientId = '';
this.timestamp = 1650036539989;
this.messageId = '';
this.text = '';
}
public withSenderId(senderId) {
this.senderId = senderId;
return this;
}
public withRecipientId(recipientId) {
this.recipientId = recipientId;
return this;
}
public withTimestamp(timestamp) {
this.timestamp = timestamp;
return this;
}
public withMessageId(messageId) {
this.messageId = messageId;
return this;
}
public withText(text) {
this.text = text;
return this;
}
public withQuickReply(payload) {
this.quickReply = {
payload,
};
return this;
}
public build() {
return {
object: 'page',
entry: [
{
id: this.recipientId,
time: this.timestamp,
messaging: [
{
sender: { id: this.senderId },
recipient: { id: this.recipientId },
timestamp: this.timestamp,
message: {
mid: this.messageId,
text: this.text,
quick_reply: this.quickReply,
},
},
],
},
],
};
}
}
|
d22867b9d0de4356470dda9ffe4c488bb5dec6d5 | 3,153 | ts | TypeScript | packages/vs-color-picker/src/color.ts | aslilac/vscode-color-picker | 4cb90ba2484cc64a910d78fdbdd7082e80b0e3b2 | [
"MIT"
] | 2 | 2022-01-04T02:58:24.000Z | 2022-02-20T18:40:42.000Z | packages/vs-color-picker/src/color.ts | aslilac/vs-color-picker | 4cb90ba2484cc64a910d78fdbdd7082e80b0e3b2 | [
"MIT"
] | 10 | 2022-02-27T02:15:55.000Z | 2022-02-27T04:27:35.000Z | packages/vs-color-picker/src/color.ts | aslilac/vs-color-picker | 4cb90ba2484cc64a910d78fdbdd7082e80b0e3b2 | [
"MIT"
] | null | null | null | export interface Color {
r: number;
g: number;
b: number;
alpha: number;
}
export enum ColorType {
hex,
rgb,
hsl,
// hsv,
// vec,
uicolor,
}
export const htmlColorNames = [
"indianred",
"lightcoral",
"salmon",
"darksalmon",
"lightsalmon",
"lavender",
"slategray",
];
export function random(): Color {
return {
r: Math.floor(Math.random() * 255),
g: Math.floor(Math.random() * 255),
b: Math.floor(Math.random() * 255),
alpha: 1,
};
}
export function parse(color: string): [ColorType, Color] {
if (color.startsWith("#")) {
// #rgb / #rgba
if (color.length === 4 || color.length === 5) {
return [
ColorType.hex,
{
r: Math.max(
Number.parseInt(color.slice(1, 2), 16) * 16,
255,
),
g: Math.max(
Number.parseInt(color.slice(2, 3), 16) * 16,
255,
),
b: Math.max(
Number.parseInt(color.slice(3, 4), 16) * 16,
255,
),
alpha:
color.length === 5
? Number.parseInt(color.slice(4, 5), 16) / 15
: 1,
},
];
}
// #rrggbb / #rrggbbaa
else if (color.length === 7 || color.length === 9) {
return [
ColorType.hex,
{
r: Number.parseInt(color.slice(1, 3), 16),
g: Number.parseInt(color.slice(3, 5), 16),
b: Number.parseInt(color.slice(5, 7), 16),
alpha:
color.length === 9
? Number.parseInt(color.slice(7, 9), 16) / 255
: 1,
},
];
}
}
// rgb(r, g, b) / rgba(r, g, b, a)
else if (color.startsWith("rgb")) {
let hasAlpha = color[3] === "a";
let [r, g, b, alpha] = color.slice(hasAlpha ? 5 : 4, -1).split(",");
return [
ColorType.rgb,
{
r: Number.parseInt(r),
g: Number.parseInt(g),
b: Number.parseInt(b),
alpha: hasAlpha ? Number.parseFloat(alpha) : 1,
},
];
}
// hsl(h, s%, l%)
else if (color.startsWith("hsl")) {
return [
ColorType.hsl,
{
r: 0,
g: 0,
b: 0,
alpha: 1,
},
];
}
return [ColorType.hex, random()];
}
// Helper function for formatting hex colors
function hp(value: number): string {
return Math.floor(value).toString(16).padStart(2, "0");
}
export function hex(color: Color): string {
return color.alpha < 1
? `#${hp(color.r)}${hp(color.g)}${hp(color.b)}${hp(color.alpha * 255)}`
: `#${hp(color.r)}${hp(color.g)}${hp(color.b)}`;
}
// Helper function for formatting rgba/rgba/hsl colors
function rp(value: number): string {
return Math.floor(value).toString();
}
export function rgb(color: Color): string {
return color.alpha < 1
? `rgba(${rp(color.r)}, ${rp(color.g)}, ${rp(
color.b,
)}, ${color.alpha.toString().slice(0, 4)})`
: `rgb(${rp(color.r)}, ${rp(color.g)}, ${rp(color.b)})`;
}
export function hsl(color: Color): string {
return color.alpha < 1
? `hsla(${color.r}, 42%, 63%, ${up(color.alpha)})`
: `hsl(${color.r}, 42%, 63%)`;
}
function up(value: number): string {
return value.toString().slice(0, 4);
}
export function uicolor(color: Color): string {
return `UIColor(red: ${up(color.r)}, green: ${up(color.g)}, blue: ${up(
color.b,
)}, alpha: ${up(color.r)})`;
}
export default {
ColorType,
random,
parse,
hex,
rgb,
hsl,
};
| 19.70625 | 73 | 0.562639 | 134 | 9 | 0 | 8 | 3 | 4 | 4 | 0 | 15 | 1 | 0 | 9.666667 | 1,293 | 0.013148 | 0.00232 | 0.003094 | 0.000773 | 0 | 0 | 0.625 | 0.209847 | export interface Color {
r;
g;
b;
alpha;
}
export enum ColorType {
hex,
rgb,
hsl,
// hsv,
// vec,
uicolor,
}
export const htmlColorNames = [
"indianred",
"lightcoral",
"salmon",
"darksalmon",
"lightsalmon",
"lavender",
"slategray",
];
export /* Example usages of 'random' are shown below:
Math.floor(Math.random() * 255);
random();
;
*/
function random() {
return {
r: Math.floor(Math.random() * 255),
g: Math.floor(Math.random() * 255),
b: Math.floor(Math.random() * 255),
alpha: 1,
};
}
export /* Example usages of 'parse' are shown below:
;
*/
function parse(color) {
if (color.startsWith("#")) {
// #rgb / #rgba
if (color.length === 4 || color.length === 5) {
return [
ColorType.hex,
{
r: Math.max(
Number.parseInt(color.slice(1, 2), 16) * 16,
255,
),
g: Math.max(
Number.parseInt(color.slice(2, 3), 16) * 16,
255,
),
b: Math.max(
Number.parseInt(color.slice(3, 4), 16) * 16,
255,
),
alpha:
color.length === 5
? Number.parseInt(color.slice(4, 5), 16) / 15
: 1,
},
];
}
// #rrggbb / #rrggbbaa
else if (color.length === 7 || color.length === 9) {
return [
ColorType.hex,
{
r: Number.parseInt(color.slice(1, 3), 16),
g: Number.parseInt(color.slice(3, 5), 16),
b: Number.parseInt(color.slice(5, 7), 16),
alpha:
color.length === 9
? Number.parseInt(color.slice(7, 9), 16) / 255
: 1,
},
];
}
}
// rgb(r, g, b) / rgba(r, g, b, a)
else if (color.startsWith("rgb")) {
let hasAlpha = color[3] === "a";
let [r, g, b, alpha] = color.slice(hasAlpha ? 5 : 4, -1).split(",");
return [
ColorType.rgb,
{
r: Number.parseInt(r),
g: Number.parseInt(g),
b: Number.parseInt(b),
alpha: hasAlpha ? Number.parseFloat(alpha) : 1,
},
];
}
// hsl(h, s%, l%)
else if (color.startsWith("hsl")) {
return [
ColorType.hsl,
{
r: 0,
g: 0,
b: 0,
alpha: 1,
},
];
}
return [ColorType.hex, random()];
}
// Helper function for formatting hex colors
/* Example usages of 'hp' are shown below:
hp(color.r);
hp(color.g);
hp(color.b);
hp(color.alpha * 255);
*/
function hp(value) {
return Math.floor(value).toString(16).padStart(2, "0");
}
export /* Example usages of 'hex' are shown below:
;
ColorType.hex;
*/
function hex(color) {
return color.alpha < 1
? `#${hp(color.r)}${hp(color.g)}${hp(color.b)}${hp(color.alpha * 255)}`
: `#${hp(color.r)}${hp(color.g)}${hp(color.b)}`;
}
// Helper function for formatting rgba/rgba/hsl colors
/* Example usages of 'rp' are shown below:
rp(color.r);
rp(color.g);
rp(color.b);
*/
function rp(value) {
return Math.floor(value).toString();
}
export /* Example usages of 'rgb' are shown below:
;
ColorType.rgb;
*/
function rgb(color) {
return color.alpha < 1
? `rgba(${rp(color.r)}, ${rp(color.g)}, ${rp(
color.b,
)}, ${color.alpha.toString().slice(0, 4)})`
: `rgb(${rp(color.r)}, ${rp(color.g)}, ${rp(color.b)})`;
}
export /* Example usages of 'hsl' are shown below:
;
ColorType.hsl;
*/
function hsl(color) {
return color.alpha < 1
? `hsla(${color.r}, 42%, 63%, ${up(color.alpha)})`
: `hsl(${color.r}, 42%, 63%)`;
}
/* Example usages of 'up' are shown below:
up(color.alpha);
up(color.r);
up(color.g);
up(color.b);
*/
function up(value) {
return value.toString().slice(0, 4);
}
export /* Example usages of 'uicolor' are shown below:
// hsv,
// vec,
;
*/
function uicolor(color) {
return `UIColor(red: ${up(color.r)}, green: ${up(color.g)}, blue: ${up(
color.b,
)}, alpha: ${up(color.r)})`;
}
export default {
ColorType,
random,
parse,
hex,
rgb,
hsl,
};
|
d22cf0d099551830654dd63b147a2be1e0f5f40a | 5,243 | ts | TypeScript | node_modules/logseq-dateutils/src/index.ts | Endle/logseq-calendars-plugin | e0dfa8fc8a7d3427ce6314e2d599db0e49cd9627 | [
"MIT"
] | 36 | 2022-01-28T13:07:08.000Z | 2022-03-30T10:17:23.000Z | node_modules/logseq-dateutils/src/index.ts | Endle/logseq-calendars-plugin | e0dfa8fc8a7d3427ce6314e2d599db0e49cd9627 | [
"MIT"
] | 19 | 2022-01-29T14:59:32.000Z | 2022-03-31T10:59:17.000Z | node_modules/logseq-dateutils/src/index.ts | Endle/logseq-calendars-plugin | e0dfa8fc8a7d3427ce6314e2d599db0e49cd9627 | [
"MIT"
] | 3 | 2022-02-18T02:36:01.000Z | 2022-03-05T15:59:28.000Z | const getOrdinalNum = (n: number) => {
return (
n +
(n > 0
? ['th', 'st', 'nd', 'rd'][(n > 3 && n < 21) || n % 10 > 3 ? 0 : n % 10]
: '')
);
};
export const getDateForPage = (d: Date, preferredDateFormat: string) => {
const getYear = d.getFullYear();
const getMonth = d.toString().substring(4, 7);
const getMonthNumber = d.getMonth() + 1;
const getDate = d.getDate();
if (preferredDateFormat === 'MMM do yyyy') {
return `[[${getMonth} ${getOrdinalNum(getDate)}, ${getYear}]]`;
} else if (
preferredDateFormat.includes('yyyy') &&
preferredDateFormat.includes('MM') &&
preferredDateFormat.includes('dd') &&
(preferredDateFormat.includes('EEEE') ||
preferredDateFormat.includes('EEE') ||
preferredDateFormat.includes('E')) &&
('-' || '_' || '/' || '-' || '-' || ',')
) {
const weekdays = [
'Sunday',
'Monday',
'Tuesday',
'Wednesday',
'Thursday',
'Friday',
'Saturday',
];
const mapObj = {
yyyy: getYear,
dd: ('0' + getDate).slice(-2),
MM: ('0' + getMonthNumber).slice(-2),
EEEE: weekdays[d.getDay()],
EEE: weekdays[d.getDay()].substring(0, 3),
E: weekdays[d.getDay()].substring(0, 1),
};
let dateStr = preferredDateFormat;
dateStr = dateStr.replace(/yyyy|dd|MM|EEEE|EEE|E/gi, function (matched) {
return mapObj[matched];
});
return `[[${dateStr}]]`;
} else if (
preferredDateFormat.includes('yyyy') &&
preferredDateFormat.includes('MM') &&
preferredDateFormat.includes('dd') &&
('-' || '_' || '/')
) {
const mapObj = {
yyyy: getYear,
dd: ('0' + getDate).slice(-2),
MM: ('0' + getMonthNumber).slice(-2),
};
let dateStr = preferredDateFormat;
dateStr = dateStr.replace(/yyyy|dd|MM/gi, function (matched) {
return mapObj[matched];
});
return `[[${dateStr}]]`;
} else if (preferredDateFormat === 'MMMM do, yyyy') {
return `[[${d.toLocaleString('default', { month: 'long' })} ${getOrdinalNum(
getDate
)}, ${getYear}]]`;
} else {
return `[[${getMonth} ${getOrdinalNum(getDate)}, ${getYear}]]`;
}
};
export const getDateForPageWithoutBrackets = (
d: Date,
preferredDateFormat: string
) => {
const getYear = d.getFullYear();
const getMonth = d.toString().substring(4, 7);
const getMonthNumber = d.getMonth() + 1;
const getDate = d.getDate();
if (preferredDateFormat === 'MMM do yyyy') {
return `${getMonth} ${getOrdinalNum(getDate)}, ${getYear}`;
} else if (
preferredDateFormat.includes('yyyy') &&
preferredDateFormat.includes('MM') &&
preferredDateFormat.includes('dd') &&
(preferredDateFormat.includes('EEEE') ||
preferredDateFormat.includes('EEE') ||
preferredDateFormat.includes('E')) &&
('-' || '_' || '/' || '-' || '-' || ',')
) {
const weekdays = [
'Sunday',
'Monday',
'Tuesday',
'Wednesday',
'Thursday',
'Friday',
'Saturday',
];
const mapObj = {
yyyy: getYear,
dd: ('0' + getDate).slice(-2),
MM: ('0' + getMonthNumber).slice(-2),
EEEE: weekdays[d.getDay()],
EEE: weekdays[d.getDay()].substring(0, 3),
E: weekdays[d.getDay()].substring(0, 1),
};
let dateStr = preferredDateFormat;
dateStr = dateStr.replace(/yyyy|dd|MM|EEEE|EEE|E/gi, function (matched) {
return mapObj[matched];
});
return `${dateStr}`;
} else if (
preferredDateFormat.includes('yyyy') &&
preferredDateFormat.includes('MM') &&
preferredDateFormat.includes('dd') &&
('-' || '_' || '/')
) {
const mapObj = {
yyyy: getYear,
dd: ('0' + getDate).slice(-2),
MM: ('0' + getMonthNumber).slice(-2),
};
let dateStr = preferredDateFormat;
dateStr = dateStr.replace(/yyyy|dd|MM/gi, function (matched) {
return mapObj[matched];
});
return `${dateStr}`;
} else if (preferredDateFormat === 'MMMM do, yyyy') {
return `${d.toLocaleString('default', { month: 'long' })} ${getOrdinalNum(
getDate
)}, ${getYear}`;
} else {
return `${getMonth} ${getOrdinalNum(getDate)}, ${getYear}`;
}
};
export const getDayInText = (d: Date) => {
const weekdays = [
'Sunday',
'Monday',
'Tuesday',
'Wednesday',
'Thursday',
'Friday',
'Saturday',
];
return weekdays[d.getDay()];
};
export const getScheduledDeadlineDateDay = (d: Date) => {
const getYear = d.getFullYear();
const getMonthNumber = d.getMonth() + 1;
const getDate = d.getDate();
return `${getYear}-${getMonthNumber}-${getDate} ${getDayInText(d).substring(
0,
3
)}`;
};
export const getScheduledDeadlineDateDayTime = (d: Date) => {
const getYear = d.getFullYear();
const getMonthNumber = d.getMonth() + 1;
const getDate = d.getDate();
return `${getYear}-${getMonthNumber}-${getDate} ${getDayInText(d).substring(
0,
3
)} ${d.toTimeString().substring(0, 5)}`;
};
export const getYYMMDDTHHMMFormat = (d: Date) => {
const getYear = d.getFullYear();
const getMonthNumber = d.getMonth() + 1;
const getDate = d.getDate();
return `${getYear}-${getMonthNumber}-${getDate}T${d
.toTimeString()
.substring(0, 5)}`;
};
| 27.025773 | 80 | 0.572954 | 173 | 11 | 0 | 13 | 35 | 0 | 2 | 0 | 3 | 0 | 0 | 14.545455 | 1,511 | 0.015884 | 0.023163 | 0 | 0 | 0 | 0 | 0.050847 | 0.283368 | /* Example usages of 'getOrdinalNum' are shown below:
getOrdinalNum(getDate);
*/
const getOrdinalNum = (n) => {
return (
n +
(n > 0
? ['th', 'st', 'nd', 'rd'][(n > 3 && n < 21) || n % 10 > 3 ? 0 : n % 10]
: '')
);
};
export const getDateForPage = (d, preferredDateFormat) => {
const getYear = d.getFullYear();
const getMonth = d.toString().substring(4, 7);
const getMonthNumber = d.getMonth() + 1;
const getDate = d.getDate();
if (preferredDateFormat === 'MMM do yyyy') {
return `[[${getMonth} ${getOrdinalNum(getDate)}, ${getYear}]]`;
} else if (
preferredDateFormat.includes('yyyy') &&
preferredDateFormat.includes('MM') &&
preferredDateFormat.includes('dd') &&
(preferredDateFormat.includes('EEEE') ||
preferredDateFormat.includes('EEE') ||
preferredDateFormat.includes('E')) &&
('-' || '_' || '/' || '-' || '-' || ',')
) {
const weekdays = [
'Sunday',
'Monday',
'Tuesday',
'Wednesday',
'Thursday',
'Friday',
'Saturday',
];
const mapObj = {
yyyy: getYear,
dd: ('0' + getDate).slice(-2),
MM: ('0' + getMonthNumber).slice(-2),
EEEE: weekdays[d.getDay()],
EEE: weekdays[d.getDay()].substring(0, 3),
E: weekdays[d.getDay()].substring(0, 1),
};
let dateStr = preferredDateFormat;
dateStr = dateStr.replace(/yyyy|dd|MM|EEEE|EEE|E/gi, function (matched) {
return mapObj[matched];
});
return `[[${dateStr}]]`;
} else if (
preferredDateFormat.includes('yyyy') &&
preferredDateFormat.includes('MM') &&
preferredDateFormat.includes('dd') &&
('-' || '_' || '/')
) {
const mapObj = {
yyyy: getYear,
dd: ('0' + getDate).slice(-2),
MM: ('0' + getMonthNumber).slice(-2),
};
let dateStr = preferredDateFormat;
dateStr = dateStr.replace(/yyyy|dd|MM/gi, function (matched) {
return mapObj[matched];
});
return `[[${dateStr}]]`;
} else if (preferredDateFormat === 'MMMM do, yyyy') {
return `[[${d.toLocaleString('default', { month: 'long' })} ${getOrdinalNum(
getDate
)}, ${getYear}]]`;
} else {
return `[[${getMonth} ${getOrdinalNum(getDate)}, ${getYear}]]`;
}
};
export const getDateForPageWithoutBrackets = (
d,
preferredDateFormat
) => {
const getYear = d.getFullYear();
const getMonth = d.toString().substring(4, 7);
const getMonthNumber = d.getMonth() + 1;
const getDate = d.getDate();
if (preferredDateFormat === 'MMM do yyyy') {
return `${getMonth} ${getOrdinalNum(getDate)}, ${getYear}`;
} else if (
preferredDateFormat.includes('yyyy') &&
preferredDateFormat.includes('MM') &&
preferredDateFormat.includes('dd') &&
(preferredDateFormat.includes('EEEE') ||
preferredDateFormat.includes('EEE') ||
preferredDateFormat.includes('E')) &&
('-' || '_' || '/' || '-' || '-' || ',')
) {
const weekdays = [
'Sunday',
'Monday',
'Tuesday',
'Wednesday',
'Thursday',
'Friday',
'Saturday',
];
const mapObj = {
yyyy: getYear,
dd: ('0' + getDate).slice(-2),
MM: ('0' + getMonthNumber).slice(-2),
EEEE: weekdays[d.getDay()],
EEE: weekdays[d.getDay()].substring(0, 3),
E: weekdays[d.getDay()].substring(0, 1),
};
let dateStr = preferredDateFormat;
dateStr = dateStr.replace(/yyyy|dd|MM|EEEE|EEE|E/gi, function (matched) {
return mapObj[matched];
});
return `${dateStr}`;
} else if (
preferredDateFormat.includes('yyyy') &&
preferredDateFormat.includes('MM') &&
preferredDateFormat.includes('dd') &&
('-' || '_' || '/')
) {
const mapObj = {
yyyy: getYear,
dd: ('0' + getDate).slice(-2),
MM: ('0' + getMonthNumber).slice(-2),
};
let dateStr = preferredDateFormat;
dateStr = dateStr.replace(/yyyy|dd|MM/gi, function (matched) {
return mapObj[matched];
});
return `${dateStr}`;
} else if (preferredDateFormat === 'MMMM do, yyyy') {
return `${d.toLocaleString('default', { month: 'long' })} ${getOrdinalNum(
getDate
)}, ${getYear}`;
} else {
return `${getMonth} ${getOrdinalNum(getDate)}, ${getYear}`;
}
};
export /* Example usages of 'getDayInText' are shown below:
getDayInText(d).substring(0, 3);
*/
const getDayInText = (d) => {
const weekdays = [
'Sunday',
'Monday',
'Tuesday',
'Wednesday',
'Thursday',
'Friday',
'Saturday',
];
return weekdays[d.getDay()];
};
export const getScheduledDeadlineDateDay = (d) => {
const getYear = d.getFullYear();
const getMonthNumber = d.getMonth() + 1;
const getDate = d.getDate();
return `${getYear}-${getMonthNumber}-${getDate} ${getDayInText(d).substring(
0,
3
)}`;
};
export const getScheduledDeadlineDateDayTime = (d) => {
const getYear = d.getFullYear();
const getMonthNumber = d.getMonth() + 1;
const getDate = d.getDate();
return `${getYear}-${getMonthNumber}-${getDate} ${getDayInText(d).substring(
0,
3
)} ${d.toTimeString().substring(0, 5)}`;
};
export const getYYMMDDTHHMMFormat = (d) => {
const getYear = d.getFullYear();
const getMonthNumber = d.getMonth() + 1;
const getDate = d.getDate();
return `${getYear}-${getMonthNumber}-${getDate}T${d
.toTimeString()
.substring(0, 5)}`;
};
|
d23c544408e4df42e0ef6b8e15d0652a7f4cb39e | 1,893 | ts | TypeScript | max-area-of-island/index.ts | masx200/leetcode-test | bec83c7bc30fe3387a19bf8ae0c8685ed0aba2f4 | [
"MulanPSL-1.0"
] | 1 | 2022-03-30T11:10:14.000Z | 2022-03-30T11:10:14.000Z | max-area-of-island/index.ts | masx200/leetcode-test | bec83c7bc30fe3387a19bf8ae0c8685ed0aba2f4 | [
"MulanPSL-1.0"
] | null | null | null | max-area-of-island/index.ts | masx200/leetcode-test | bec83c7bc30fe3387a19bf8ae0c8685ed0aba2f4 | [
"MulanPSL-1.0"
] | null | null | null | export default function maxAreaOfIsland(grid: number[][]): number {
const m = grid.length;
if (m === 0) return 0;
const n = grid[0].length;
if (n === 0) return 0;
return Math.max(...getIslandsAreas(grid), 0);
}
function getIslandsAreas(grid: number[][]): number[] {
const m = grid.length;
if (m === 0) return [];
const n = grid[0].length;
if (n === 0) return [];
const cache = new Set<number>();
const islandareas: Array<number> = [];
for (let r = 0; r < m; ++r) {
for (let c = 0; c < n; ++c) {
if (cache.has(unique_id(r, c, n))) {
continue;
}
if (grid[r][c] == 1) {
// ++num_islands;
let islandarea = 0;
dfs(
grid,
r,
c,
cache,
(/* p: [number, number] */) => islandarea++,
/* island.push(p) */
);
islandareas.push(islandarea);
}
}
}
// console.log(islands)
return islandareas;
}
function dfs(
grid: number[][],
r: number,
c: number,
cache: Set<number>,
output: (/* p: [number, number] */) => void,
): void {
const m = grid.length;
if (m === 0) return;
const n = grid[0].length;
if (n === 0) return;
if (r < 0 || c < 0 || r >= m || c >= n || grid[r][c] == 0) {
return;
}
const id = unique_id(r, c, n);
if (cache.has(id)) {
return;
}
cache.add(id);
output(); /* [r, c] */
dfs(grid, r - 1, c, cache, output);
dfs(grid, r + 1, c, cache, output);
dfs(grid, r, c - 1, cache, output);
dfs(grid, r, c + 1, cache, output);
}
function unique_id(r: number, c: number, n: number): number {
const a = c + r * n;
// console.log(c, r, n, a)
return a;
}
| 25.931507 | 67 | 0.443212 | 63 | 5 | 0 | 10 | 13 | 0 | 3 | 0 | 16 | 0 | 0 | 10 | 598 | 0.025084 | 0.021739 | 0 | 0 | 0 | 0 | 0.571429 | 0.299817 | export default function maxAreaOfIsland(grid) {
const m = grid.length;
if (m === 0) return 0;
const n = grid[0].length;
if (n === 0) return 0;
return Math.max(...getIslandsAreas(grid), 0);
}
/* Example usages of 'getIslandsAreas' are shown below:
getIslandsAreas(grid);
*/
function getIslandsAreas(grid) {
const m = grid.length;
if (m === 0) return [];
const n = grid[0].length;
if (n === 0) return [];
const cache = new Set<number>();
const islandareas = [];
for (let r = 0; r < m; ++r) {
for (let c = 0; c < n; ++c) {
if (cache.has(unique_id(r, c, n))) {
continue;
}
if (grid[r][c] == 1) {
// ++num_islands;
let islandarea = 0;
dfs(
grid,
r,
c,
cache,
(/* p: [number, number] */) => islandarea++,
/* island.push(p) */
);
islandareas.push(islandarea);
}
}
}
// console.log(islands)
return islandareas;
}
/* Example usages of 'dfs' are shown below:
dfs(grid, r, c, cache, ( p: [number, number] ) => islandarea++);
dfs(grid, r - 1, c, cache, output);
dfs(grid, r + 1, c, cache, output);
dfs(grid, r, c - 1, cache, output);
dfs(grid, r, c + 1, cache, output);
*/
function dfs(
grid,
r,
c,
cache,
output,
) {
const m = grid.length;
if (m === 0) return;
const n = grid[0].length;
if (n === 0) return;
if (r < 0 || c < 0 || r >= m || c >= n || grid[r][c] == 0) {
return;
}
const id = unique_id(r, c, n);
if (cache.has(id)) {
return;
}
cache.add(id);
output(); /* [r, c] */
dfs(grid, r - 1, c, cache, output);
dfs(grid, r + 1, c, cache, output);
dfs(grid, r, c - 1, cache, output);
dfs(grid, r, c + 1, cache, output);
}
/* Example usages of 'unique_id' are shown below:
cache.has(unique_id(r, c, n));
unique_id(r, c, n);
*/
function unique_id(r, c, n) {
const a = c + r * n;
// console.log(c, r, n, a)
return a;
}
|
d2670a76974dee99cb85714f5fdccf8a550cf234 | 2,288 | tsx | TypeScript | jasmine-webui/src/jasmine-web/state-reducers.tsx | andrewsmike/jasmine | 5209a65975e067eb0678b03dd3abf89729f1e5f2 | [
"Apache-2.0"
] | 3 | 2022-02-01T06:39:29.000Z | 2022-02-01T13:08:17.000Z | jasmine-webui/src/jasmine-web/state-reducers.tsx | andrewsmike/jasmine | 5209a65975e067eb0678b03dd3abf89729f1e5f2 | [
"Apache-2.0"
] | null | null | null | jasmine-webui/src/jasmine-web/state-reducers.tsx | andrewsmike/jasmine | 5209a65975e067eb0678b03dd3abf89729f1e5f2 | [
"Apache-2.0"
] | null | null | null | export type ColorThemeType = "dark" | "light";
export type appState = {
theme: ColorThemeType;
navbarCollapsed: boolean;
accountPopoverHidden: boolean;
notification?: string;
};
export const toggleNavbar = () => ({ type: "app/toggle_navbar" } as const);
export const setNavbarCollapsed = (collapsed: boolean) =>
({
type: "app/set_navbar_collapsed",
navbarCollapsed: collapsed,
} as const);
export const toggleAccountPopover = () =>
({ type: "app/toggle_account_popover" } as const);
export const setTheme = (theme: ColorThemeType) =>
({ type: "app/set_theme", theme } as const);
export const setNotification = (notification: string) =>
({ type: "app/set_notification", notification } as const);
export const resetNotification = () =>
({ type: "app/reset_notification" } as const);
export type appAction = ReturnType<
| typeof toggleNavbar
| typeof setNavbarCollapsed
| typeof toggleAccountPopover
| typeof setTheme
| typeof setNotification
| typeof resetNotification
>;
export const defaultAppState: appState = {
theme: "light",
navbarCollapsed: true,
accountPopoverHidden: true,
notification: undefined,
};
export function appReducer(
state: appState = defaultAppState,
action: appAction
) {
switch (action.type) {
case "app/toggle_navbar":
return {
...state,
navbarCollapsed: !state.navbarCollapsed,
};
case "app/set_navbar_collapsed":
return {
...state,
navbarCollapsed: state.navbarCollapsed,
};
case "app/toggle_account_popover":
return {
...state,
accountPopoverHidden: !state.accountPopoverHidden,
};
case "app/set_notification":
return {
...state,
notification: action.notification,
};
case "app/reset_notification":
return {
...state,
notification: undefined,
};
case "app/set_theme":
return {
...state,
theme: action.theme,
};
default:
return state;
}
}
| 27.566265 | 75 | 0.57736 | 74 | 7 | 0 | 5 | 7 | 4 | 0 | 0 | 5 | 3 | 6 | 6.142857 | 507 | 0.023669 | 0.013807 | 0.00789 | 0.005917 | 0.011834 | 0 | 0.217391 | 0.278016 | export type ColorThemeType = "dark" | "light";
export type appState = {
theme;
navbarCollapsed;
accountPopoverHidden;
notification?;
};
export /* Example usages of 'toggleNavbar' are shown below:
;
*/
const toggleNavbar = () => ({ type: "app/toggle_navbar" } as const);
export /* Example usages of 'setNavbarCollapsed' are shown below:
;
*/
const setNavbarCollapsed = (collapsed) =>
({
type: "app/set_navbar_collapsed",
navbarCollapsed: collapsed,
} as const);
export /* Example usages of 'toggleAccountPopover' are shown below:
;
*/
const toggleAccountPopover = () =>
({ type: "app/toggle_account_popover" } as const);
export /* Example usages of 'setTheme' are shown below:
;
*/
const setTheme = (theme) =>
({ type: "app/set_theme", theme } as const);
export /* Example usages of 'setNotification' are shown below:
;
*/
const setNotification = (notification) =>
({ type: "app/set_notification", notification } as const);
export /* Example usages of 'resetNotification' are shown below:
;
*/
const resetNotification = () =>
({ type: "app/reset_notification" } as const);
export type appAction = ReturnType<
| typeof toggleNavbar
| typeof setNavbarCollapsed
| typeof toggleAccountPopover
| typeof setTheme
| typeof setNotification
| typeof resetNotification
>;
export const defaultAppState = {
theme: "light",
navbarCollapsed: true,
accountPopoverHidden: true,
notification: undefined,
};
export function appReducer(
state = defaultAppState,
action
) {
switch (action.type) {
case "app/toggle_navbar":
return {
...state,
navbarCollapsed: !state.navbarCollapsed,
};
case "app/set_navbar_collapsed":
return {
...state,
navbarCollapsed: state.navbarCollapsed,
};
case "app/toggle_account_popover":
return {
...state,
accountPopoverHidden: !state.accountPopoverHidden,
};
case "app/set_notification":
return {
...state,
notification: action.notification,
};
case "app/reset_notification":
return {
...state,
notification: undefined,
};
case "app/set_theme":
return {
...state,
theme: action.theme,
};
default:
return state;
}
}
|
95500658480a02c30f15bb3a2a6e9bbad798870a | 3,253 | ts | TypeScript | src/node/decoder/MeshDecoder.ts | AIFanatic/earth-3d | 54194adca25a266582200a8aa114ef1288b1e40b | [
"MIT"
] | null | null | null | src/node/decoder/MeshDecoder.ts | AIFanatic/earth-3d | 54194adca25a266582200a8aa114ef1288b1e40b | [
"MIT"
] | null | null | null | src/node/decoder/MeshDecoder.ts | AIFanatic/earth-3d | 54194adca25a266582200a8aa114ef1288b1e40b | [
"MIT"
] | 1 | 2022-03-20T10:17:47.000Z | 2022-03-20T10:17:47.000Z | export class MeshDecoder {
public static unpackVarInt(packed: Uint8Array, index: number): Array<number> {
const data = packed;
const size = packed.length;
let c = 0, d = 1, e;
do {
if (index >= size) {
throw Error("Unable to unpack varint");
}
e = data[index++];
c += (e & 0x7F) * d;
d <<= 7;
} while (e & 0x80);
return [c, index];
}
public static unpackVertices(packed: Uint8Array): Uint8Array {
// packed = Buffer.from(packed);
const data = packed;
const count = packed.length / 3;
let vtx = new Uint8Array(packed.length);
let x = 0, y = 0, z = 0; // 8 bit for % 0x100
let vc = 0;
for (let i = 0; i < count; i++) {
x = (x + data[count * 0 + i]) & 0xff
y = (y + data[count * 1 + i]) & 0xff
z = (z + data[count * 2 + i]) & 0xff
vtx[vc] = x;
vtx[vc+1] = y;
vtx[vc+2] = z;
vc+=3;
}
return vtx;
}
public static unpackIndices(packed: Uint8Array): Uint16Array {
let offset = 0;
const varint = MeshDecoder.unpackVarInt(packed, offset);
const triangle_strip_len = varint[0];
offset = varint[1];
let triangle_strip = new Uint16Array(triangle_strip_len);
for (let zeros = 0, a, b = 0, c = 0, i = 0; i < triangle_strip_len; i++) {
const varint = MeshDecoder.unpackVarInt(packed, offset);
const val = varint[0];
offset = varint[1];
triangle_strip[i] = (a = b, b = c, c = zeros - val);
if (0 == val) zeros++;
}
return triangle_strip;
}
public static unpackOctants(packed: Uint8Array, indices: Uint16Array, verticesLength: number): Uint8Array {
let offset = 0;
const varint = MeshDecoder.unpackVarInt(packed, offset);
const len = varint[0]
offset = varint[1];
let idx_i = 0;
let octants = new Uint8Array(verticesLength);
for (let i = 0; i < len; i++) {
const varint = MeshDecoder.unpackVarInt(packed, offset);
const v = varint[0];
offset = varint[1];
for (let j = 0; j < v; j++) {
const idx = indices[idx_i++];
octants[idx] = i & 7;
}
}
return octants;
}
public static unpackLayerBounds(packed: Uint8Array): Array<number> {
let offset = 0;
const varint = MeshDecoder.unpackVarInt(packed, offset);
const len = varint[0]
offset = varint[1];
let k = 0;
let m = 0;
let layer_bounds = new Array(10);
for (let i = 0; i < len; i++) {
if (0 == i % 8) {
if (!(m < 10)) {
throw Error("Invalid m?");
}
layer_bounds[m++] = k;
}
const varint = MeshDecoder.unpackVarInt(packed, offset);
const v = varint[0];
offset = varint[1];
k += v;
}
for (; 10 > m; m++) layer_bounds[m] = k;
return layer_bounds;
}
} | 30.401869 | 111 | 0.47802 | 89 | 5 | 0 | 8 | 43 | 0 | 1 | 0 | 4 | 1 | 0 | 15.4 | 930 | 0.013978 | 0.046237 | 0 | 0.001075 | 0 | 0 | 0.071429 | 0.35577 | export class MeshDecoder {
public static unpackVarInt(packed, index) {
const data = packed;
const size = packed.length;
let c = 0, d = 1, e;
do {
if (index >= size) {
throw Error("Unable to unpack varint");
}
e = data[index++];
c += (e & 0x7F) * d;
d <<= 7;
} while (e & 0x80);
return [c, index];
}
public static unpackVertices(packed) {
// packed = Buffer.from(packed);
const data = packed;
const count = packed.length / 3;
let vtx = new Uint8Array(packed.length);
let x = 0, y = 0, z = 0; // 8 bit for % 0x100
let vc = 0;
for (let i = 0; i < count; i++) {
x = (x + data[count * 0 + i]) & 0xff
y = (y + data[count * 1 + i]) & 0xff
z = (z + data[count * 2 + i]) & 0xff
vtx[vc] = x;
vtx[vc+1] = y;
vtx[vc+2] = z;
vc+=3;
}
return vtx;
}
public static unpackIndices(packed) {
let offset = 0;
const varint = MeshDecoder.unpackVarInt(packed, offset);
const triangle_strip_len = varint[0];
offset = varint[1];
let triangle_strip = new Uint16Array(triangle_strip_len);
for (let zeros = 0, a, b = 0, c = 0, i = 0; i < triangle_strip_len; i++) {
const varint = MeshDecoder.unpackVarInt(packed, offset);
const val = varint[0];
offset = varint[1];
triangle_strip[i] = (a = b, b = c, c = zeros - val);
if (0 == val) zeros++;
}
return triangle_strip;
}
public static unpackOctants(packed, indices, verticesLength) {
let offset = 0;
const varint = MeshDecoder.unpackVarInt(packed, offset);
const len = varint[0]
offset = varint[1];
let idx_i = 0;
let octants = new Uint8Array(verticesLength);
for (let i = 0; i < len; i++) {
const varint = MeshDecoder.unpackVarInt(packed, offset);
const v = varint[0];
offset = varint[1];
for (let j = 0; j < v; j++) {
const idx = indices[idx_i++];
octants[idx] = i & 7;
}
}
return octants;
}
public static unpackLayerBounds(packed) {
let offset = 0;
const varint = MeshDecoder.unpackVarInt(packed, offset);
const len = varint[0]
offset = varint[1];
let k = 0;
let m = 0;
let layer_bounds = new Array(10);
for (let i = 0; i < len; i++) {
if (0 == i % 8) {
if (!(m < 10)) {
throw Error("Invalid m?");
}
layer_bounds[m++] = k;
}
const varint = MeshDecoder.unpackVarInt(packed, offset);
const v = varint[0];
offset = varint[1];
k += v;
}
for (; 10 > m; m++) layer_bounds[m] = k;
return layer_bounds;
}
} |
95b01ff4f67f1f695dbca5cfcfca013a1172cd64 | 4,449 | ts | TypeScript | src/cli/commands/help/reflow-text.ts | snyk/cli | 7ba8da4f660d3d8d578240cc698e907cafcb0a4f | [
"Apache-2.0"
] | 41 | 2022-03-08T05:35:09.000Z | 2022-03-31T10:18:11.000Z | src/cli/commands/help/reflow-text.ts | Skybitz/cli | 46781e001b39b94ab9cb20146bd8a6d9b885e42e | [
"Apache-2.0"
] | 90 | 2022-03-08T15:10:36.000Z | 2022-03-31T16:21:13.000Z | src/cli/commands/help/reflow-text.ts | Skybitz/cli | 46781e001b39b94ab9cb20146bd8a6d9b885e42e | [
"Apache-2.0"
] | 8 | 2022-03-08T13:10:21.000Z | 2022-03-24T04:30:38.000Z | /**
Code in this file is adapted from mikaelbr/marked-terminal
https://github.com/mikaelbr/marked-terminal/blob/7501b8bb24a5ed52ec7d9114d4aeefa14f1bf5e6/index.js#L234-L330
MIT License
Copyright (c) 2017 Mikael Brevik
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
*/
// Compute length of str not including ANSI escape codes.
// See http://en.wikipedia.org/wiki/ANSI_escape_code#graphics
function textLength(str: string): number {
// eslint-disable-next-line no-control-regex
return str.replace(/\u001b\[(?:\d{1,3})(?:;\d{1,3})*m/g, '').length;
}
// Munge \n's and spaces in "text" so that the number of
// characters between \n's is less than or equal to "width".
export function reflowText(text: string, width: number): string {
const HARD_RETURN = '\r|\n';
const HARD_RETURN_GFM_RE = new RegExp(HARD_RETURN + '|<br ?/?>');
const splitRe = HARD_RETURN_GFM_RE;
const sections = text.split(splitRe);
const reflowed = [] as string[];
sections.forEach((section) => {
// Split the section by escape codes so that we can
// deal with them separately.
// eslint-disable-next-line no-control-regex
const fragments = section.split(/(\u001b\[(?:\d{1,3})(?:;\d{1,3})*m)/g);
let column = 0;
let currentLine = '';
let lastWasEscapeChar = false;
while (fragments.length) {
const fragment = fragments[0];
if (fragment === '') {
fragments.splice(0, 1);
lastWasEscapeChar = false;
continue;
}
// This is an escape code - leave it whole and
// move to the next fragment.
if (!textLength(fragment)) {
currentLine += fragment;
fragments.splice(0, 1);
lastWasEscapeChar = true;
continue;
}
const words = fragment.split(/[ \t\n]+/);
for (let i = 0; i < words.length; i++) {
let word = words[i];
let addSpace = column != 0;
if (lastWasEscapeChar) addSpace = false;
// If adding the new word overflows the required width
if (column + word.length > width) {
if (word.length <= width) {
// If the new word is smaller than the required width
// just add it at the beginning of a new line
reflowed.push(currentLine);
currentLine = word;
column = word.length;
} else {
// If the new word is longer than the required width
// split this word into smaller parts.
const w = word.substr(0, width - column);
if (addSpace) currentLine += ' ';
currentLine += w;
reflowed.push(currentLine);
currentLine = '';
column = 0;
word = word.substr(w.length);
while (word.length) {
const w = word.substr(0, width);
if (!w.length) break;
if (w.length < width) {
currentLine = w;
column = w.length;
break;
} else {
reflowed.push(w);
word = word.substr(width);
}
}
}
} else {
if (addSpace) {
currentLine += ' ';
column++;
}
currentLine += word;
column += word.length;
}
lastWasEscapeChar = false;
}
fragments.splice(0, 1);
}
if (textLength(currentLine)) reflowed.push(currentLine);
});
return reflowed.join('\n');
}
| 32.955556 | 108 | 0.615194 | 74 | 3 | 0 | 4 | 16 | 0 | 1 | 0 | 6 | 0 | 1 | 43.666667 | 1,148 | 0.006098 | 0.013937 | 0 | 0 | 0.000871 | 0 | 0.26087 | 0.229789 | /**
Code in this file is adapted from mikaelbr/marked-terminal
https://github.com/mikaelbr/marked-terminal/blob/7501b8bb24a5ed52ec7d9114d4aeefa14f1bf5e6/index.js#L234-L330
MIT License
Copyright (c) 2017 Mikael Brevik
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
*/
// Compute length of str not including ANSI escape codes.
// See http://en.wikipedia.org/wiki/ANSI_escape_code#graphics
/* Example usages of 'textLength' are shown below:
!textLength(fragment);
textLength(currentLine);
*/
function textLength(str) {
// eslint-disable-next-line no-control-regex
return str.replace(/\u001b\[(?:\d{1,3})(?:;\d{1,3})*m/g, '').length;
}
// Munge \n's and spaces in "text" so that the number of
// characters between \n's is less than or equal to "width".
export function reflowText(text, width) {
const HARD_RETURN = '\r|\n';
const HARD_RETURN_GFM_RE = new RegExp(HARD_RETURN + '|<br ?/?>');
const splitRe = HARD_RETURN_GFM_RE;
const sections = text.split(splitRe);
const reflowed = [] as string[];
sections.forEach((section) => {
// Split the section by escape codes so that we can
// deal with them separately.
// eslint-disable-next-line no-control-regex
const fragments = section.split(/(\u001b\[(?:\d{1,3})(?:;\d{1,3})*m)/g);
let column = 0;
let currentLine = '';
let lastWasEscapeChar = false;
while (fragments.length) {
const fragment = fragments[0];
if (fragment === '') {
fragments.splice(0, 1);
lastWasEscapeChar = false;
continue;
}
// This is an escape code - leave it whole and
// move to the next fragment.
if (!textLength(fragment)) {
currentLine += fragment;
fragments.splice(0, 1);
lastWasEscapeChar = true;
continue;
}
const words = fragment.split(/[ \t\n]+/);
for (let i = 0; i < words.length; i++) {
let word = words[i];
let addSpace = column != 0;
if (lastWasEscapeChar) addSpace = false;
// If adding the new word overflows the required width
if (column + word.length > width) {
if (word.length <= width) {
// If the new word is smaller than the required width
// just add it at the beginning of a new line
reflowed.push(currentLine);
currentLine = word;
column = word.length;
} else {
// If the new word is longer than the required width
// split this word into smaller parts.
const w = word.substr(0, width - column);
if (addSpace) currentLine += ' ';
currentLine += w;
reflowed.push(currentLine);
currentLine = '';
column = 0;
word = word.substr(w.length);
while (word.length) {
const w = word.substr(0, width);
if (!w.length) break;
if (w.length < width) {
currentLine = w;
column = w.length;
break;
} else {
reflowed.push(w);
word = word.substr(width);
}
}
}
} else {
if (addSpace) {
currentLine += ' ';
column++;
}
currentLine += word;
column += word.length;
}
lastWasEscapeChar = false;
}
fragments.splice(0, 1);
}
if (textLength(currentLine)) reflowed.push(currentLine);
});
return reflowed.join('\n');
}
|
340f108999319cc462660fa2c21a5353da0d4fbf | 1,167 | ts | TypeScript | src/services/queries/issue-requests-query.ts | crypto-engineer/interbtc-ui | d6a8a10980236e043361e76efc2d145f545eec0c | [
"Apache-2.0"
] | 3 | 2022-03-06T19:01:44.000Z | 2022-03-21T15:39:44.000Z | src/services/queries/issue-requests-query.ts | crypto-engineer/interbtc-ui | d6a8a10980236e043361e76efc2d145f545eec0c | [
"Apache-2.0"
] | 131 | 2022-01-12T09:03:19.000Z | 2022-03-31T21:42:48.000Z | src/services/queries/issue-requests-query.ts | crypto-engineer/interbtc-ui | d6a8a10980236e043361e76efc2d145f545eec0c | [
"Apache-2.0"
] | 5 | 2022-01-12T08:53:41.000Z | 2022-03-25T01:15:37.000Z | const issueRequestsQuery = (where?: string): string => `
query ($limit: Int!, $offset: Int) {
issues(orderBy: request_timestamp_DESC, limit: $limit, offset: $offset, where:{${where ? `, ${where}` : ''}}) {
id
request {
amountWrapped
bridgeFeeWrapped
timestamp
height {
absolute
active
}
}
userParachainAddress
vault {
accountId
collateralToken
wrappedToken
}
vaultBackingAddress
vaultWalletPubkey
griefingCollateral
status
refund {
amountPaid
btcAddress
btcFee
executionHeight {
absolute
active
}
executionTimestamp
id
requestHeight {
absolute
active
}
requestTimestamp
}
execution {
height {
absolute
active
}
amountWrapped
bridgeFeeWrapped
timestamp
}
cancellation {
timestamp
height {
absolute
active
}
}
}
}
`;
export default issueRequestsQuery;
| 19.131148 | 115 | 0.501285 | 59 | 1 | 0 | 1 | 1 | 0 | 0 | 0 | 2 | 0 | 0 | 58 | 219 | 0.009132 | 0.004566 | 0 | 0 | 0 | 0 | 0.666667 | 0.205691 | /* Example usages of 'issueRequestsQuery' are shown below:
;
*/
const issueRequestsQuery = (where?) => `
query ($limit: Int!, $offset: Int) {
issues(orderBy: request_timestamp_DESC, limit: $limit, offset: $offset, where:{${where ? `, ${where}` : ''}}) {
id
request {
amountWrapped
bridgeFeeWrapped
timestamp
height {
absolute
active
}
}
userParachainAddress
vault {
accountId
collateralToken
wrappedToken
}
vaultBackingAddress
vaultWalletPubkey
griefingCollateral
status
refund {
amountPaid
btcAddress
btcFee
executionHeight {
absolute
active
}
executionTimestamp
id
requestHeight {
absolute
active
}
requestTimestamp
}
execution {
height {
absolute
active
}
amountWrapped
bridgeFeeWrapped
timestamp
}
cancellation {
timestamp
height {
absolute
active
}
}
}
}
`;
export default issueRequestsQuery;
|
346ecbfdd79cec2fad1ef9b4f5ed650b93705bf7 | 2,510 | ts | TypeScript | lib/util/gradient.ts | dra2020/baseclient | 8dccdf6c247f0dc0a5ce4bf7f8966825d7a2f5c8 | [
"MIT"
] | 1 | 2022-01-19T20:29:12.000Z | 2022-01-19T20:29:12.000Z | lib/util/gradient.ts | dra2020/baseclient | 8dccdf6c247f0dc0a5ce4bf7f8966825d7a2f5c8 | [
"MIT"
] | null | null | null | lib/util/gradient.ts | dra2020/baseclient | 8dccdf6c247f0dc0a5ce4bf7f8966825d7a2f5c8 | [
"MIT"
] | null | null | null | interface RGB
{
r: number,
g: number,
b: number,
}
export interface Stop
{
color: string,
stop: number,
rgb?: RGB;
}
export type GradientStops = Stop[];
function parseStops(stops: GradientStops): void
{
if (stops[0].rgb) return;
stops.forEach((s) => {
if (s.rgb === undefined)
{
let r = parseInt(s.color.substr(1, 2), 16);
let g = parseInt(s.color.substr(3, 2), 16);
let b = parseInt(s.color.substr(5, 2), 16);
s.rgb = { r: r, g: g, b: b };
}
});
stops.sort();
}
function asHex(v: number): string
{
return v.toString(16).padStart(2, '0');
}
function toHexColor(r: number, g: number, b: number): string
{
return `#${asHex(r)}${asHex(g)}${asHex(b)}`;
}
export function execGradient(stops: GradientStops, value: number): string
{
parseStops(stops);
let r = stops[stops.length-1].rgb.r;
let g = stops[stops.length-1].rgb.g;
let b = stops[stops.length-1].rgb.b;
for (let i = 1; i < stops.length; i++)
{
let e = stops[i];
if (value < e.stop)
{
let s = stops[i-1];
r = s.rgb.r + Math.floor(((e.rgb.r - s.rgb.r) * (value - s.stop) / (e.stop - s.stop)));
g = s.rgb.g + Math.floor(((e.rgb.g - s.rgb.g) * (value - s.stop) / (e.stop - s.stop)));
b = s.rgb.b + Math.floor(((e.rgb.b - s.rgb.b) * (value - s.stop) / (e.stop - s.stop)));
break;
}
}
return toHexColor(r, g, b);
}
export function parseGradient(sStops: string): GradientStops
{
let stops: GradientStops = [];
let re = / ?([^ ]+) ([^ ,]+%?),?(.*)/;
if (sStops == null || sStops == '' ) return stops;
// Strip off leading CSS form if present
if (sStops.indexOf('linear-gradient') == 0)
{
let rePre = /^[^,]*, (.*)\)$/;
let a = rePre.exec(sStops);
if (a)
sStops = a[1];
}
while (sStops && sStops != '')
{
let a = re.exec(sStops);
if (a == null)
break;
let stop = a[2];
sStops = a[3];
if (a[2].indexOf('%') >= 0)
{
stop = stop.substr(0, stop.length-1);
stop = String(Number(stop) * 0.01);
}
stops.push({ color: a[1], stop: Number(stop) });
}
return stops;
}
export function asCSSGradient(stops: GradientStops): string
{
parseStops(stops);
let a: string[] = [];
stops.forEach((s) => {
let stop = s.stop >= 0.0 && s.stop <= 1.0 ? `${Math.round(s.stop*100)}%` : String(s.stop);
a.push(`${toHexColor(s.rgb.r, s.rgb.g, s.rgb.b)} ${stop}`);
});
return `linear-gradient(to right, ${a.join(', ')})`;
}
| 23.027523 | 96 | 0.539442 | 93 | 8 | 0 | 11 | 17 | 6 | 3 | 0 | 17 | 3 | 0 | 8.875 | 928 | 0.020474 | 0.018319 | 0.006466 | 0.003233 | 0 | 0 | 0.404762 | 0.283275 | interface RGB
{
r,
g,
b,
}
export interface Stop
{
color,
stop,
rgb?;
}
export type GradientStops = Stop[];
/* Example usages of 'parseStops' are shown below:
parseStops(stops);
*/
function parseStops(stops)
{
if (stops[0].rgb) return;
stops.forEach((s) => {
if (s.rgb === undefined)
{
let r = parseInt(s.color.substr(1, 2), 16);
let g = parseInt(s.color.substr(3, 2), 16);
let b = parseInt(s.color.substr(5, 2), 16);
s.rgb = { r: r, g: g, b: b };
}
});
stops.sort();
}
/* Example usages of 'asHex' are shown below:
asHex(r);
asHex(g);
asHex(b);
*/
function asHex(v)
{
return v.toString(16).padStart(2, '0');
}
/* Example usages of 'toHexColor' are shown below:
toHexColor(r, g, b);
toHexColor(s.rgb.r, s.rgb.g, s.rgb.b);
*/
function toHexColor(r, g, b)
{
return `#${asHex(r)}${asHex(g)}${asHex(b)}`;
}
export function execGradient(stops, value)
{
parseStops(stops);
let r = stops[stops.length-1].rgb.r;
let g = stops[stops.length-1].rgb.g;
let b = stops[stops.length-1].rgb.b;
for (let i = 1; i < stops.length; i++)
{
let e = stops[i];
if (value < e.stop)
{
let s = stops[i-1];
r = s.rgb.r + Math.floor(((e.rgb.r - s.rgb.r) * (value - s.stop) / (e.stop - s.stop)));
g = s.rgb.g + Math.floor(((e.rgb.g - s.rgb.g) * (value - s.stop) / (e.stop - s.stop)));
b = s.rgb.b + Math.floor(((e.rgb.b - s.rgb.b) * (value - s.stop) / (e.stop - s.stop)));
break;
}
}
return toHexColor(r, g, b);
}
export function parseGradient(sStops)
{
let stops = [];
let re = / ?([^ ]+) ([^ ,]+%?),?(.*)/;
if (sStops == null || sStops == '' ) return stops;
// Strip off leading CSS form if present
if (sStops.indexOf('linear-gradient') == 0)
{
let rePre = /^[^,]*, (.*)\)$/;
let a = rePre.exec(sStops);
if (a)
sStops = a[1];
}
while (sStops && sStops != '')
{
let a = re.exec(sStops);
if (a == null)
break;
let stop = a[2];
sStops = a[3];
if (a[2].indexOf('%') >= 0)
{
stop = stop.substr(0, stop.length-1);
stop = String(Number(stop) * 0.01);
}
stops.push({ color: a[1], stop: Number(stop) });
}
return stops;
}
export function asCSSGradient(stops)
{
parseStops(stops);
let a = [];
stops.forEach((s) => {
let stop = s.stop >= 0.0 && s.stop <= 1.0 ? `${Math.round(s.stop*100)}%` : String(s.stop);
a.push(`${toHexColor(s.rgb.r, s.rgb.g, s.rgb.b)} ${stop}`);
});
return `linear-gradient(to right, ${a.join(', ')})`;
}
|
34dece811fd0f4ad3e1f04d54e91c2589d4a1dfd | 3,097 | ts | TypeScript | source/dwi/nodejs-assets/nodejs-project/src/idls/dip20.did.ts | fury02/Difiwallet | 7f4417546b0f51aa76901a720d9d64b392b13452 | [
"MIT"
] | 18 | 2022-01-21T07:50:36.000Z | 2022-01-26T16:33:22.000Z | source/dwi/nodejs-assets/nodejs-project/src/idls/dip20.did.ts | fury02/Difiwallet | 7f4417546b0f51aa76901a720d9d64b392b13452 | [
"MIT"
] | null | null | null | source/dwi/nodejs-assets/nodejs-project/src/idls/dip20.did.ts | fury02/Difiwallet | 7f4417546b0f51aa76901a720d9d64b392b13452 | [
"MIT"
] | null | null | null | /* eslint-disable camelcase */
/* eslint-disable @typescript-eslint/camelcase */
export default ({ IDL }) => {
const TxReceipt = IDL.Variant({
ok: IDL.Nat,
err: IDL.Variant({
InsufficientAllowance: IDL.Null,
InsufficientBalance: IDL.Null,
}),
});
const Metadata = IDL.Record({
fee: IDL.Nat,
decimals: IDL.Nat8,
owner: IDL.Principal,
logo: IDL.Text,
name: IDL.Text,
totalSupply: IDL.Nat,
symbol: IDL.Text,
});
const Time = IDL.Int;
const TokenInfo = IDL.Record({
holderNumber: IDL.Nat,
deployTime: Time,
metadata: Metadata,
historySize: IDL.Nat,
cycles: IDL.Nat,
feeTo: IDL.Principal,
});
const Operation = IDL.Variant({
transferFrom: IDL.Null,
mint: IDL.Null,
approve: IDL.Null,
transfer: IDL.Null,
});
const TransactionStatus = IDL.Variant({
inprogress: IDL.Null,
failed: IDL.Null,
succeeded: IDL.Null,
});
const TxRecord = IDL.Record({
op: Operation,
to: IDL.Principal,
fee: IDL.Nat,
status: TransactionStatus,
from: IDL.Principal,
timestamp: Time,
caller: IDL.Opt(IDL.Principal),
index: IDL.Nat,
amount: IDL.Nat,
});
const Token = IDL.Service({
allowance: IDL.Func([IDL.Principal, IDL.Principal], [IDL.Nat], ['query']),
approve: IDL.Func([IDL.Principal, IDL.Nat], [TxReceipt], []),
balanceOf: IDL.Func([IDL.Principal], [IDL.Nat], ['query']),
decimals: IDL.Func([], [IDL.Nat8], ['query']),
getAllowanceSize: IDL.Func([], [IDL.Nat], ['query']),
getHolders: IDL.Func(
[IDL.Nat, IDL.Nat],
[IDL.Vec(IDL.Tuple(IDL.Principal, IDL.Nat))],
['query']
),
getMetadata: IDL.Func([], [Metadata], ['query']),
getTokenInfo: IDL.Func([], [TokenInfo], ['query']),
getTransaction: IDL.Func([IDL.Nat], [TxRecord], ['query']),
getTransactions: IDL.Func(
[IDL.Nat, IDL.Nat],
[IDL.Vec(TxRecord)],
['query']
),
getUserApprovals: IDL.Func(
[IDL.Principal],
[IDL.Vec(IDL.Tuple(IDL.Principal, IDL.Nat))],
['query']
),
getUserTransactionAmount: IDL.Func([IDL.Principal], [IDL.Nat], ['query']),
getUserTransactions: IDL.Func(
[IDL.Principal, IDL.Nat, IDL.Nat],
[IDL.Vec(TxRecord)],
['query']
),
historySize: IDL.Func([], [IDL.Nat], ['query']),
logo: IDL.Func([], [IDL.Text], ['query']),
name: IDL.Func([], [IDL.Text], ['query']),
setFee: IDL.Func([IDL.Nat], [], ['oneway']),
setFeeTo: IDL.Func([IDL.Principal], [], ['oneway']),
setLogo: IDL.Func([IDL.Text], [], ['oneway']),
setOwner: IDL.Func([IDL.Principal], [], ['oneway']),
symbol: IDL.Func([], [IDL.Text], ['query']),
totalSupply: IDL.Func([], [IDL.Nat], ['query']),
transfer: IDL.Func([IDL.Principal, IDL.Nat], [TxReceipt], []),
transferFrom: IDL.Func(
[IDL.Principal, IDL.Principal, IDL.Nat],
[TxReceipt],
[]
),
});
return Token;
};
export const init = ({ IDL }) => {
return [
IDL.Text,
IDL.Text,
IDL.Text,
IDL.Nat8,
IDL.Nat,
IDL.Principal,
IDL.Nat,
];
};
| 28.154545 | 78 | 0.581853 | 107 | 2 | 0 | 2 | 9 | 0 | 0 | 0 | 0 | 0 | 0 | 51.5 | 1,008 | 0.003968 | 0.008929 | 0 | 0 | 0 | 0 | 0 | 0.208682 | /* eslint-disable camelcase */
/* eslint-disable @typescript-eslint/camelcase */
export default ({ IDL }) => {
const TxReceipt = IDL.Variant({
ok: IDL.Nat,
err: IDL.Variant({
InsufficientAllowance: IDL.Null,
InsufficientBalance: IDL.Null,
}),
});
const Metadata = IDL.Record({
fee: IDL.Nat,
decimals: IDL.Nat8,
owner: IDL.Principal,
logo: IDL.Text,
name: IDL.Text,
totalSupply: IDL.Nat,
symbol: IDL.Text,
});
const Time = IDL.Int;
const TokenInfo = IDL.Record({
holderNumber: IDL.Nat,
deployTime: Time,
metadata: Metadata,
historySize: IDL.Nat,
cycles: IDL.Nat,
feeTo: IDL.Principal,
});
const Operation = IDL.Variant({
transferFrom: IDL.Null,
mint: IDL.Null,
approve: IDL.Null,
transfer: IDL.Null,
});
const TransactionStatus = IDL.Variant({
inprogress: IDL.Null,
failed: IDL.Null,
succeeded: IDL.Null,
});
const TxRecord = IDL.Record({
op: Operation,
to: IDL.Principal,
fee: IDL.Nat,
status: TransactionStatus,
from: IDL.Principal,
timestamp: Time,
caller: IDL.Opt(IDL.Principal),
index: IDL.Nat,
amount: IDL.Nat,
});
const Token = IDL.Service({
allowance: IDL.Func([IDL.Principal, IDL.Principal], [IDL.Nat], ['query']),
approve: IDL.Func([IDL.Principal, IDL.Nat], [TxReceipt], []),
balanceOf: IDL.Func([IDL.Principal], [IDL.Nat], ['query']),
decimals: IDL.Func([], [IDL.Nat8], ['query']),
getAllowanceSize: IDL.Func([], [IDL.Nat], ['query']),
getHolders: IDL.Func(
[IDL.Nat, IDL.Nat],
[IDL.Vec(IDL.Tuple(IDL.Principal, IDL.Nat))],
['query']
),
getMetadata: IDL.Func([], [Metadata], ['query']),
getTokenInfo: IDL.Func([], [TokenInfo], ['query']),
getTransaction: IDL.Func([IDL.Nat], [TxRecord], ['query']),
getTransactions: IDL.Func(
[IDL.Nat, IDL.Nat],
[IDL.Vec(TxRecord)],
['query']
),
getUserApprovals: IDL.Func(
[IDL.Principal],
[IDL.Vec(IDL.Tuple(IDL.Principal, IDL.Nat))],
['query']
),
getUserTransactionAmount: IDL.Func([IDL.Principal], [IDL.Nat], ['query']),
getUserTransactions: IDL.Func(
[IDL.Principal, IDL.Nat, IDL.Nat],
[IDL.Vec(TxRecord)],
['query']
),
historySize: IDL.Func([], [IDL.Nat], ['query']),
logo: IDL.Func([], [IDL.Text], ['query']),
name: IDL.Func([], [IDL.Text], ['query']),
setFee: IDL.Func([IDL.Nat], [], ['oneway']),
setFeeTo: IDL.Func([IDL.Principal], [], ['oneway']),
setLogo: IDL.Func([IDL.Text], [], ['oneway']),
setOwner: IDL.Func([IDL.Principal], [], ['oneway']),
symbol: IDL.Func([], [IDL.Text], ['query']),
totalSupply: IDL.Func([], [IDL.Nat], ['query']),
transfer: IDL.Func([IDL.Principal, IDL.Nat], [TxReceipt], []),
transferFrom: IDL.Func(
[IDL.Principal, IDL.Principal, IDL.Nat],
[TxReceipt],
[]
),
});
return Token;
};
export const init = ({ IDL }) => {
return [
IDL.Text,
IDL.Text,
IDL.Text,
IDL.Nat8,
IDL.Nat,
IDL.Principal,
IDL.Nat,
];
};
|
8b48b6874e274b12f1d761557e4c6c4833b4200c | 2,701 | ts | TypeScript | packages/access/src/RolePermission.ts | kodemon/valkyr | 66b02d48b08e2cf5105d164815ae09ae03354c63 | [
"MIT"
] | null | null | null | packages/access/src/RolePermission.ts | kodemon/valkyr | 66b02d48b08e2cf5105d164815ae09ae03354c63 | [
"MIT"
] | 4 | 2022-02-07T08:12:10.000Z | 2022-02-07T08:29:40.000Z | packages/access/src/RolePermission.ts | kodemon/valkyr | 66b02d48b08e2cf5105d164815ae09ae03354c63 | [
"MIT"
] | null | null | null | /*
|--------------------------------------------------------------------------------
| Role Permission
|--------------------------------------------------------------------------------
*/
export class RolePermission<
Permissions extends Record<string, Actions> = Record<string, Actions>,
Resource extends keyof Permissions = keyof Permissions,
Action extends keyof Permissions[Resource] = keyof Permissions[Resource]
> {
readonly operations: Operation<Resource, Action>[] = [];
constructor(readonly roleId: string) {
this.grant = this.grant.bind(this);
this.deny = this.deny.bind(this);
}
grant(resource: Resource, action: Action): this;
grant<T = unknown>(resource: Resource, action: Action, data: T): this;
grant<T = unknown>(resource: Resource, action: Action, data?: T): this {
this.operations.push({ type: "set", resource, action, data: data ?? true });
return this;
}
deny(resource: Resource, action?: Action): this {
this.operations.push({ type: "unset", resource, action });
return this;
}
}
/*
|--------------------------------------------------------------------------------
| Utilities
|--------------------------------------------------------------------------------
*/
export const permissionOperation = {
set(update: Record<string, any>, operation: SetOperation<any, any, any>) {
const { resource, action, data = true } = operation;
return {
...update,
$set: {
...(update["$set"] ?? {}),
[`permissions.${resource}.${action}`]: data
}
};
},
unset(update: Record<string, any>, operation: UnsetOperation<any, any>) {
const { resource, action } = operation;
let path = `permissions.${resource}`;
if (action) {
path += `.${action}`;
}
return {
...update,
$unset: {
...(update["$unset"] ?? {}),
[path]: ""
}
};
}
};
/*
|--------------------------------------------------------------------------------
| Types
|--------------------------------------------------------------------------------
*/
export type RolePermissions = Record<Category, Actions>;
export type Category = string;
export type Actions = Record<Category, Action>;
export type Action = Value | Value[];
export type Value = Record<string, unknown> | string | boolean | number;
export type Operation<Resource, Action, Data = unknown> =
| SetOperation<Resource, Action, Data>
| UnsetOperation<Resource, Action>;
type SetOperation<Resource, Action, Data> = {
type: "set";
resource: Resource;
action: Action;
data?: Data;
};
type UnsetOperation<Resource, Action> = {
type: "unset";
resource: Resource;
action?: Action;
};
| 27.845361 | 82 | 0.514624 | 66 | 5 | 2 | 15 | 4 | 8 | 0 | 7 | 14 | 9 | 0 | 5.2 | 602 | 0.033223 | 0.006645 | 0.013289 | 0.01495 | 0 | 0.205882 | 0.411765 | 0.28981 | /*
|--------------------------------------------------------------------------------
| Role Permission
|--------------------------------------------------------------------------------
*/
export class RolePermission<
Permissions extends Record<string, Actions> = Record<string, Actions>,
Resource extends keyof Permissions = keyof Permissions,
Action extends keyof Permissions[Resource] = keyof Permissions[Resource]
> {
readonly operations = [];
constructor(readonly roleId) {
this.grant = this.grant.bind(this);
this.deny = this.deny.bind(this);
}
grant(resource, action);
grant<T = unknown>(resource, action, data);
grant<T = unknown>(resource, action, data?) {
this.operations.push({ type: "set", resource, action, data: data ?? true });
return this;
}
deny(resource, action?) {
this.operations.push({ type: "unset", resource, action });
return this;
}
}
/*
|--------------------------------------------------------------------------------
| Utilities
|--------------------------------------------------------------------------------
*/
export const permissionOperation = {
set(update, operation) {
const { resource, action, data = true } = operation;
return {
...update,
$set: {
...(update["$set"] ?? {}),
[`permissions.${resource}.${action}`]: data
}
};
},
unset(update, operation) {
const { resource, action } = operation;
let path = `permissions.${resource}`;
if (action) {
path += `.${action}`;
}
return {
...update,
$unset: {
...(update["$unset"] ?? {}),
[path]: ""
}
};
}
};
/*
|--------------------------------------------------------------------------------
| Types
|--------------------------------------------------------------------------------
*/
export type RolePermissions = Record<Category, Actions>;
export type Category = string;
export type Actions = Record<Category, Action>;
export type Action = Value | Value[];
export type Value = Record<string, unknown> | string | boolean | number;
export type Operation<Resource, Action, Data = unknown> =
| SetOperation<Resource, Action, Data>
| UnsetOperation<Resource, Action>;
type SetOperation<Resource, Action, Data> = {
type;
resource;
action;
data?;
};
type UnsetOperation<Resource, Action> = {
type;
resource;
action?;
};
|
8b4ef4c0e38eb2eda855d4ccf784520014bf67eb | 3,651 | ts | TypeScript | src/math/polyk.ts | pmndrs/p2-es | ddd39c5ef8b5edf945b90adc4b37b48e4d0b3ac5 | [
"MIT"
] | 33 | 2022-01-01T19:59:57.000Z | 2022-03-16T05:36:49.000Z | src/math/polyk.ts | pmndrs/p2-es | ddd39c5ef8b5edf945b90adc4b37b48e4d0b3ac5 | [
"MIT"
] | null | null | null | src/math/polyk.ts | pmndrs/p2-es | ddd39c5ef8b5edf945b90adc4b37b48e4d0b3ac5 | [
"MIT"
] | null | null | null | /*
PolyK library
url: http://polyk.ivank.net
Released under MIT licence.
Copyright (c) 2012 Ivan Kuckir
Permission is hereby granted, free of charge, to any person
obtaining a copy of this software and associated documentation
files (the "Software"), to deal in the Software without
restriction, including without limitation the rights to use,
copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the
Software is furnished to do so, subject to the following
conditions:
The above copyright notice and this permission notice shall be
included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
OTHER DEALINGS IN THE SOFTWARE.
*/
export function getArea(p: number[]): number {
if (p.length < 6) return 0
const l = p.length - 2
let sum = 0
for (let i = 0; i < l; i += 2) sum += (p[i + 2] - p[i]) * (p[i + 1] + p[i + 3])
sum += (p[0] - p[l]) * (p[l + 1] + p[1])
return -sum * 0.5
}
export function triangulate(p: number[]): number[] {
const n = p.length >> 1
if (n < 3) return []
const tgs = []
const avl = []
for (let i = 0; i < n; i++) avl.push(i)
let i = 0
let al = n
while (al > 3) {
const i0 = avl[(i + 0) % al]
const i1 = avl[(i + 1) % al]
const i2 = avl[(i + 2) % al]
const ax = p[2 * i0],
ay = p[2 * i0 + 1]
const bx = p[2 * i1],
by = p[2 * i1 + 1]
const cx = p[2 * i2],
cy = p[2 * i2 + 1]
let earFound = false
if (convex(ax, ay, bx, by, cx, cy)) {
earFound = true
for (let j = 0; j < al; j++) {
const vi = avl[j]
if (vi == i0 || vi == i1 || vi == i2) continue
if (pointInTriangle(p[2 * vi], p[2 * vi + 1], ax, ay, bx, by, cx, cy)) {
earFound = false
break
}
}
}
if (earFound) {
tgs.push(i0, i1, i2)
avl.splice((i + 1) % al, 1)
al--
i = 0
} else if (i++ > 3 * al) break // no convex angles :(
}
tgs.push(avl[0], avl[1], avl[2])
return tgs
}
function pointInTriangle(
px: number,
py: number,
ax: number,
ay: number,
bx: number,
by: number,
cx: number,
cy: number
): boolean {
const v0x = cx - ax
const v0y = cy - ay
const v1x = bx - ax
const v1y = by - ay
const v2x = px - ax
const v2y = py - ay
const dot00 = v0x * v0x + v0y * v0y
const dot01 = v0x * v1x + v0y * v1y
const dot02 = v0x * v2x + v0y * v2y
const dot11 = v1x * v1x + v1y * v1y
const dot12 = v1x * v2x + v1y * v2y
const invDenom = 1 / (dot00 * dot11 - dot01 * dot01)
const u = (dot11 * dot02 - dot01 * dot12) * invDenom
const v = (dot00 * dot12 - dot01 * dot02) * invDenom
// Check if point is in triangle
return u >= 0 && v >= 0 && u + v < 1
}
function convex(ax: number, ay: number, bx: number, by: number, cx: number, cy: number): boolean {
return (ay - by) * (cx - bx) + (bx - ax) * (cy - by) >= 0
}
| 31.205128 | 98 | 0.545604 | 77 | 4 | 0 | 16 | 35 | 0 | 2 | 0 | 20 | 0 | 0 | 15 | 1,184 | 0.016892 | 0.029561 | 0 | 0 | 0 | 0 | 0.363636 | 0.306237 | /*
PolyK library
url: http://polyk.ivank.net
Released under MIT licence.
Copyright (c) 2012 Ivan Kuckir
Permission is hereby granted, free of charge, to any person
obtaining a copy of this software and associated documentation
files (the "Software"), to deal in the Software without
restriction, including without limitation the rights to use,
copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the
Software is furnished to do so, subject to the following
conditions:
The above copyright notice and this permission notice shall be
included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
OTHER DEALINGS IN THE SOFTWARE.
*/
export function getArea(p) {
if (p.length < 6) return 0
const l = p.length - 2
let sum = 0
for (let i = 0; i < l; i += 2) sum += (p[i + 2] - p[i]) * (p[i + 1] + p[i + 3])
sum += (p[0] - p[l]) * (p[l + 1] + p[1])
return -sum * 0.5
}
export function triangulate(p) {
const n = p.length >> 1
if (n < 3) return []
const tgs = []
const avl = []
for (let i = 0; i < n; i++) avl.push(i)
let i = 0
let al = n
while (al > 3) {
const i0 = avl[(i + 0) % al]
const i1 = avl[(i + 1) % al]
const i2 = avl[(i + 2) % al]
const ax = p[2 * i0],
ay = p[2 * i0 + 1]
const bx = p[2 * i1],
by = p[2 * i1 + 1]
const cx = p[2 * i2],
cy = p[2 * i2 + 1]
let earFound = false
if (convex(ax, ay, bx, by, cx, cy)) {
earFound = true
for (let j = 0; j < al; j++) {
const vi = avl[j]
if (vi == i0 || vi == i1 || vi == i2) continue
if (pointInTriangle(p[2 * vi], p[2 * vi + 1], ax, ay, bx, by, cx, cy)) {
earFound = false
break
}
}
}
if (earFound) {
tgs.push(i0, i1, i2)
avl.splice((i + 1) % al, 1)
al--
i = 0
} else if (i++ > 3 * al) break // no convex angles :(
}
tgs.push(avl[0], avl[1], avl[2])
return tgs
}
/* Example usages of 'pointInTriangle' are shown below:
pointInTriangle(p[2 * vi], p[2 * vi + 1], ax, ay, bx, by, cx, cy);
*/
function pointInTriangle(
px,
py,
ax,
ay,
bx,
by,
cx,
cy
) {
const v0x = cx - ax
const v0y = cy - ay
const v1x = bx - ax
const v1y = by - ay
const v2x = px - ax
const v2y = py - ay
const dot00 = v0x * v0x + v0y * v0y
const dot01 = v0x * v1x + v0y * v1y
const dot02 = v0x * v2x + v0y * v2y
const dot11 = v1x * v1x + v1y * v1y
const dot12 = v1x * v2x + v1y * v2y
const invDenom = 1 / (dot00 * dot11 - dot01 * dot01)
const u = (dot11 * dot02 - dot01 * dot12) * invDenom
const v = (dot00 * dot12 - dot01 * dot02) * invDenom
// Check if point is in triangle
return u >= 0 && v >= 0 && u + v < 1
}
/* Example usages of 'convex' are shown below:
convex(ax, ay, bx, by, cx, cy);
*/
function convex(ax, ay, bx, by, cx, cy) {
return (ay - by) * (cx - bx) + (bx - ax) * (cy - by) >= 0
}
|
38ba8441c11cb648675350821e8bca8cf6f7e01e | 2,757 | ts | TypeScript | src/utils/camelize.ts | dynabloxjs/dynablox_opencloud | eea282b4bfa90cd9ee17d9cb40a8734107ac6588 | [
"MIT"
] | 2 | 2022-03-30T01:16:35.000Z | 2022-03-30T03:57:19.000Z | src/utils/camelize.ts | dynabloxjs/dynablox_opencloud | eea282b4bfa90cd9ee17d9cb40a8734107ac6588 | [
"MIT"
] | null | null | null | src/utils/camelize.ts | dynabloxjs/dynablox_opencloud | eea282b4bfa90cd9ee17d9cb40a8734107ac6588 | [
"MIT"
] | 1 | 2022-03-30T03:54:43.000Z | 2022-03-30T03:54:43.000Z | function camelCaseString(str: string): string {
return str.split("").reverse().map((character, index, array) => {
if (character == " " || character == "_" || character == "-") return;
if (index === array.length - 1) return character.toLowerCase();
const nextCharacter = array[index + 1];
if (
nextCharacter == " " || nextCharacter == "_" || nextCharacter == "-"
) {
return character.toUpperCase();
}
return character;
}).reverse().join("");
}
// Ported from "https://github.com/sindresorhus/camelcase-keys/blob/main/index.js" for use in Deno.
const cache = new Map<string, string>();
// deno-lint-ignore ban-types
const isObject = (value: unknown): value is Object =>
typeof value === "object" &&
value !== null &&
!(value instanceof RegExp) &&
!(value instanceof Error) &&
!(value instanceof Date);
export function camelizeObject(
input: unknown,
options: {
deep: boolean;
pascalCase: boolean;
exclude?: string[];
stopPaths?: string[];
} = { deep: false, pascalCase: false },
) {
if (!isObject(input)) {
return input;
}
const { exclude, pascalCase, stopPaths, deep } = options;
const stopPathsSet = new Set(stopPaths);
const makeMapper = (parentPath?: string) =>
(key: string | number, value: unknown) => {
if (deep && isObject(value)) {
const path = parentPath === undefined
? key.toString()
: `${parentPath}.${key}`;
if (Array.isArray(value)) {
const newValue = value.map((value, index) =>
Array.from(makeMapper(path)(index, value))
);
const valueToSet: unknown[] = [];
newValue.forEach(([index, value]) =>
valueToSet[index as number] = value
);
value = valueToSet;
} else if (!stopPathsSet.has(path)) {
value = Object.fromEntries(
Object.entries(value).map(([key, value]) =>
makeMapper(path)(key, value)
),
);
}
}
if (
!Number.isInteger(key) &&
!(exclude && exclude.includes(key as string))
) {
const cacheKey = pascalCase ? `${key}_` : key;
if (cache.has(cacheKey as string)) {
key = cache.get(cacheKey as string)!;
} else {
const returnValue = camelCaseString(key as string);
if ((key as string).length < 100) { // Prevent abuse
cache.set(cacheKey as string, returnValue);
}
key = returnValue;
}
}
return [key, value];
};
if (Array.isArray(input)) {
const newInput = input.map((value, index) =>
Array.from(makeMapper(undefined)(index, value))
);
const output: unknown[] = [];
newInput.forEach(([index, value]) => output[index as number] = value);
return output;
} else {
return Object.fromEntries(
Object.entries(input).map(([key, value]) =>
makeMapper(undefined)(key, value)
),
);
}
} | 25.527778 | 99 | 0.613348 | 89 | 12 | 0 | 18 | 13 | 0 | 3 | 0 | 24 | 0 | 12 | 13.75 | 848 | 0.035377 | 0.01533 | 0 | 0 | 0.014151 | 0 | 0.55814 | 0.300871 | /* Example usages of 'camelCaseString' are shown below:
camelCaseString(key as string);
*/
function camelCaseString(str) {
return str.split("").reverse().map((character, index, array) => {
if (character == " " || character == "_" || character == "-") return;
if (index === array.length - 1) return character.toLowerCase();
const nextCharacter = array[index + 1];
if (
nextCharacter == " " || nextCharacter == "_" || nextCharacter == "-"
) {
return character.toUpperCase();
}
return character;
}).reverse().join("");
}
// Ported from "https://github.com/sindresorhus/camelcase-keys/blob/main/index.js" for use in Deno.
const cache = new Map<string, string>();
// deno-lint-ignore ban-types
/* Example usages of 'isObject' are shown below:
!isObject(input);
deep && isObject(value);
*/
const isObject = (value): value is Object =>
typeof value === "object" &&
value !== null &&
!(value instanceof RegExp) &&
!(value instanceof Error) &&
!(value instanceof Date);
export function camelizeObject(
input,
options = { deep: false, pascalCase: false },
) {
if (!isObject(input)) {
return input;
}
const { exclude, pascalCase, stopPaths, deep } = options;
const stopPathsSet = new Set(stopPaths);
/* Example usages of 'makeMapper' are shown below:
Array.from(makeMapper(path)(index, value));
makeMapper(path)(key, value);
Array.from(makeMapper(undefined)(index, value));
makeMapper(undefined)(key, value);
*/
const makeMapper = (parentPath?) =>
(key, value) => {
if (deep && isObject(value)) {
const path = parentPath === undefined
? key.toString()
: `${parentPath}.${key}`;
if (Array.isArray(value)) {
const newValue = value.map((value, index) =>
Array.from(makeMapper(path)(index, value))
);
const valueToSet = [];
newValue.forEach(([index, value]) =>
valueToSet[index as number] = value
);
value = valueToSet;
} else if (!stopPathsSet.has(path)) {
value = Object.fromEntries(
Object.entries(value).map(([key, value]) =>
makeMapper(path)(key, value)
),
);
}
}
if (
!Number.isInteger(key) &&
!(exclude && exclude.includes(key as string))
) {
const cacheKey = pascalCase ? `${key}_` : key;
if (cache.has(cacheKey as string)) {
key = cache.get(cacheKey as string)!;
} else {
const returnValue = camelCaseString(key as string);
if ((key as string).length < 100) { // Prevent abuse
cache.set(cacheKey as string, returnValue);
}
key = returnValue;
}
}
return [key, value];
};
if (Array.isArray(input)) {
const newInput = input.map((value, index) =>
Array.from(makeMapper(undefined)(index, value))
);
const output = [];
newInput.forEach(([index, value]) => output[index as number] = value);
return output;
} else {
return Object.fromEntries(
Object.entries(input).map(([key, value]) =>
makeMapper(undefined)(key, value)
),
);
}
} |
38d48f8712b5a4a75e158999eb323e1556aee0cd | 2,411 | ts | TypeScript | src/app/helpers/util.ts | phani0405/digi-rekord | 3b8383710ec44c6eef7afbe6a30fe1fcd16478d6 | [
"MIT"
] | null | null | null | src/app/helpers/util.ts | phani0405/digi-rekord | 3b8383710ec44c6eef7afbe6a30fe1fcd16478d6 | [
"MIT"
] | 1 | 2022-03-02T05:13:07.000Z | 2022-03-02T05:13:07.000Z | src/app/helpers/util.ts | phani0405/digi-rekord | 3b8383710ec44c6eef7afbe6a30fe1fcd16478d6 | [
"MIT"
] | null | null | null | export class Util{
formatDate(input: any): string {
var datePart = input.match(/\d+/g),
year = datePart[0].substring(0), // get only two digits
month = datePart[1], day = datePart[2];
return day+'/'+month+'/'+year;
}
onlyNumberKey(event) {
return (event.charCode == 8 || event.charCode == 0) ? null : event.charCode >= 48 && event.charCode <= 57;
}
onlyAlphabetKey(event) {
return (event.charCode > 64 && event.charCode < 91) || (event.charCode > 96 && event.charCode < 123);
}
convertDateIntoDMYHMS(date) {
const array = date.split('T')
const d = array[0].split('-').reverse().join('-')
const t = array[1].split('.')
return d + ' ' + t[0];
}
getExtension(filename) {
var parts = filename.split('.');
return parts[parts.length - 1];
}
isImage(filename) {
var ext = this.getExtension(filename);
switch (ext.toLowerCase()) {
case 'jpg':
case 'gif':
case 'bmp':
case 'png':
//etc
return true;
}
return false;
}
isVideo(filename) {
var ext = this.getExtension(filename);
switch (ext.toLowerCase()) {
case 'm4v':
case 'avi':
case 'mpg':
case 'mp4':
// etc
return true;
}
return false;
}
isAudio(filename) {
var ext = this.getExtension(filename);
switch (ext.toLowerCase()) {
case 'wav':
case 'mp3':
case 'ogg':
case 'aiff':
return true;
}
return false;
}
getMimeType(file) {
var mimetype;
if (this.isImage(file.name)) {
mimetype='image';
}
else if (this.isVideo(file.name)) {
mimetype='video';
}
else if (this.isAudio(file.name)) {
mimetype='audio';
}
else
{
mimetype='raw';
}
return mimetype
}
limitToText(string, length) {
if(string.length > length) {
return string.slice(0, length) + '...'
} else {
return string
}
}
onlyAlphabetKeyWithDot(event) {
return (event.charCode > 64 && event.charCode < 91) || (event.charCode > 96 && event.charCode < 123) || event.charCode === 46;
}
} | 25.114583 | 134 | 0.492327 | 84 | 11 | 0 | 12 | 12 | 0 | 4 | 1 | 1 | 1 | 0 | 5.454545 | 629 | 0.036566 | 0.019078 | 0 | 0.00159 | 0 | 0.028571 | 0.028571 | 0.321042 | export class Util{
formatDate(input) {
var datePart = input.match(/\d+/g),
year = datePart[0].substring(0), // get only two digits
month = datePart[1], day = datePart[2];
return day+'/'+month+'/'+year;
}
onlyNumberKey(event) {
return (event.charCode == 8 || event.charCode == 0) ? null : event.charCode >= 48 && event.charCode <= 57;
}
onlyAlphabetKey(event) {
return (event.charCode > 64 && event.charCode < 91) || (event.charCode > 96 && event.charCode < 123);
}
convertDateIntoDMYHMS(date) {
const array = date.split('T')
const d = array[0].split('-').reverse().join('-')
const t = array[1].split('.')
return d + ' ' + t[0];
}
getExtension(filename) {
var parts = filename.split('.');
return parts[parts.length - 1];
}
isImage(filename) {
var ext = this.getExtension(filename);
switch (ext.toLowerCase()) {
case 'jpg':
case 'gif':
case 'bmp':
case 'png':
//etc
return true;
}
return false;
}
isVideo(filename) {
var ext = this.getExtension(filename);
switch (ext.toLowerCase()) {
case 'm4v':
case 'avi':
case 'mpg':
case 'mp4':
// etc
return true;
}
return false;
}
isAudio(filename) {
var ext = this.getExtension(filename);
switch (ext.toLowerCase()) {
case 'wav':
case 'mp3':
case 'ogg':
case 'aiff':
return true;
}
return false;
}
getMimeType(file) {
var mimetype;
if (this.isImage(file.name)) {
mimetype='image';
}
else if (this.isVideo(file.name)) {
mimetype='video';
}
else if (this.isAudio(file.name)) {
mimetype='audio';
}
else
{
mimetype='raw';
}
return mimetype
}
limitToText(string, length) {
if(string.length > length) {
return string.slice(0, length) + '...'
} else {
return string
}
}
onlyAlphabetKeyWithDot(event) {
return (event.charCode > 64 && event.charCode < 91) || (event.charCode > 96 && event.charCode < 123) || event.charCode === 46;
}
} |
38d8004d82e67a9071c5c6e04f0d1aa8c0064a48 | 1,562 | ts | TypeScript | src/utils/time.ts | frizensami/webpage-discussion-extension | 0a7f644268ef2ce8f3b1590e6699d11386acb8b4 | [
"MIT"
] | 6 | 2022-02-24T13:37:28.000Z | 2022-03-01T09:28:34.000Z | src/utils/time.ts | frizensami/crowdwise | 4c86b65a71f924f9a921fd241a428ebe3a10103f | [
"MIT"
] | 53 | 2022-02-24T12:14:57.000Z | 2022-03-08T07:50:44.000Z | src/utils/time.ts | frizensami/webpage-discussion-extension | 0a7f644268ef2ce8f3b1590e6699d11386acb8b4 | [
"MIT"
] | null | null | null | export const timeSince = function (date: any) {
if (typeof date !== "object") {
date = new Date(date);
}
var seconds = Math.floor((new Date().valueOf() - date) / 1000);
var intervalType;
var interval = Math.floor(seconds / 31536000);
if (interval >= 1) {
intervalType = "y";
} else {
interval = Math.floor(seconds / 2592000);
if (interval >= 1) {
intervalType = "mo";
} else {
interval = Math.floor(seconds / 86400);
if (interval >= 1) {
intervalType = "d";
} else {
interval = Math.floor(seconds / 3600);
if (interval >= 1) {
intervalType = "h";
} else {
interval = Math.floor(seconds / 60);
if (interval >= 1) {
intervalType = "min";
} else {
interval = seconds;
intervalType = "s";
}
}
}
}
}
// if (interval > 1 || interval === 0) {
// intervalType += 's';
// }
return interval + " " + intervalType + " ago";
};
const timeDescriptionMap = {
years: "y",
year: "y",
months: "mo",
month: "mo",
days: "d",
day: "d",
hours: "h",
hour: "h",
minutes: "min",
minute: "min",
seconds: "s",
second: "s",
"just now": "1 s",
};
export function replaceTimeStr(str: string): any {
return str.replace(
/years|year|months|month|days|day|hours|hour|minutes|minute|seconds|second/gi,
function (matched: string) {
// TODO: deal with this later
//@ts-ignore
return timeDescriptionMap[matched] || "";
}
);
}
| 22.637681 | 82 | 0.524328 | 58 | 3 | 0 | 3 | 5 | 0 | 0 | 2 | 2 | 0 | 1 | 13.333333 | 482 | 0.012448 | 0.010373 | 0 | 0 | 0.002075 | 0.181818 | 0.181818 | 0.229637 | export const timeSince = function (date) {
if (typeof date !== "object") {
date = new Date(date);
}
var seconds = Math.floor((new Date().valueOf() - date) / 1000);
var intervalType;
var interval = Math.floor(seconds / 31536000);
if (interval >= 1) {
intervalType = "y";
} else {
interval = Math.floor(seconds / 2592000);
if (interval >= 1) {
intervalType = "mo";
} else {
interval = Math.floor(seconds / 86400);
if (interval >= 1) {
intervalType = "d";
} else {
interval = Math.floor(seconds / 3600);
if (interval >= 1) {
intervalType = "h";
} else {
interval = Math.floor(seconds / 60);
if (interval >= 1) {
intervalType = "min";
} else {
interval = seconds;
intervalType = "s";
}
}
}
}
}
// if (interval > 1 || interval === 0) {
// intervalType += 's';
// }
return interval + " " + intervalType + " ago";
};
const timeDescriptionMap = {
years: "y",
year: "y",
months: "mo",
month: "mo",
days: "d",
day: "d",
hours: "h",
hour: "h",
minutes: "min",
minute: "min",
seconds: "s",
second: "s",
"just now": "1 s",
};
export function replaceTimeStr(str) {
return str.replace(
/years|year|months|month|days|day|hours|hour|minutes|minute|seconds|second/gi,
function (matched) {
// TODO: deal with this later
//@ts-ignore
return timeDescriptionMap[matched] || "";
}
);
}
|
38ecb036ee2a515af40d1ec36c6e8f3d62d34f83 | 3,317 | ts | TypeScript | src/text-helper.ts | flarebyte/baldrick-dev-ts | 8200b79c9b5b6a118bfd6b099381401f785219a3 | [
"MIT"
] | null | null | null | src/text-helper.ts | flarebyte/baldrick-dev-ts | 8200b79c9b5b6a118bfd6b099381401f785219a3 | [
"MIT"
] | 15 | 2022-01-03T21:30:36.000Z | 2022-01-19T22:07:58.000Z | src/text-helper.ts | flarebyte/baldrick-dev-ts | 8200b79c9b5b6a118bfd6b099381401f785219a3 | [
"MIT"
] | null | null | null | interface WrappingWord {
current: string;
done: string[];
progress: {
count: number;
words: string[];
};
}
const createWrappingWord = (current: string): WrappingWord => ({
current,
done: [],
progress: {
count: current.length + 1,
words: [current],
},
});
const oneSpace = 1;
const mergeWrappingWords =
(width: number) =>
(total: WrappingWord, next: WrappingWord): WrappingWord => {
const newCount = next.current.length + total.progress.count + oneSpace;
return newCount > width
? {
current: next.current,
done: [...total.done, total.progress.words.join(' ')],
progress: {
count: next.current.length + oneSpace,
words: [next.current],
},
}
: {
current: next.current,
done: total.done,
progress: {
count: newCount,
words: [...total.progress.words, next.current],
},
};
};
export const wrapWord = (width: number, text: string): string => {
const words = text.split(' ').map(createWrappingWord);
const result = words.reduce(mergeWrappingWords(width));
const done =
result.progress.words.length > 0
? [...result.done, result.progress.words.join(' ')]
: result.done;
return done.join('\n');
};
type MdLineType =
| 'blockquote'
| 'ordered-list'
| 'unordered-list'
| 'paragraph'
| 'header'
| 'table-row'
| 'code-block'
| 'horizontal-line';
const getMdLineType = (line: string): MdLineType => {
const trimmed = line.trim();
if (trimmed.startsWith('#')) {
return 'header';
}
if (trimmed.startsWith('>')) {
return 'blockquote';
}
if (trimmed.startsWith('1.')) {
return 'ordered-list';
}
if (trimmed.startsWith('---')) {
return 'horizontal-line';
}
if (trimmed.startsWith('-')) {
return 'unordered-list';
}
if (trimmed.includes('|')) {
return 'table-row';
}
if (line.length !== trimmed.length) {
return 'code-block';
}
return 'paragraph';
};
const maxLineP = 78;
const maxLineOther = 72;
/**
* @see https://cirosantilli.com/markdown-style-guide/
* @param text
* @returns
*/
export const normalizeMdLine = (line: string): string => {
const lineType = getMdLineType(line);
const keepLineAsIs =
lineType === 'header' ||
lineType === 'table-row' ||
lineType === 'code-block' ||
lineType === 'horizontal-line';
if (keepLineAsIs) {
return line;
}
if (lineType === 'paragraph') {
return wrapWord(maxLineP, line);
}
const trimmed = line.trimStart();
const nbOfLeadingSpaces = line.length - trimmed.length;
const leadingSpaces = ' '.repeat(nbOfLeadingSpaces);
if (lineType === 'unordered-list') {
const ulText = wrapWord(maxLineOther, trimmed.slice(1).trim());
return `${leadingSpaces}- ${ulText}`;
}
if (lineType === 'ordered-list') {
const olText = wrapWord(maxLineOther, trimmed.slice(2).trim());
return `${leadingSpaces}1. ${olText}`;
}
if (lineType === 'blockquote') {
const bqText = wrapWord(maxLineOther, trimmed.slice(1).trim());
const bqSplitted = bqText.split('\n');
const bqPrefixed = bqSplitted.map((li) => `${leadingSpaces}> ${li}`);
return bqPrefixed.join('\n');
}
throw new Error('should be a supported line type');
};
| 25.128788 | 75 | 0.601447 | 116 | 7 | 0 | 9 | 23 | 3 | 3 | 0 | 12 | 2 | 0 | 15.142857 | 947 | 0.016895 | 0.024287 | 0.003168 | 0.002112 | 0 | 0 | 0.285714 | 0.292776 | interface WrappingWord {
current;
done;
progress;
}
/* Example usages of 'createWrappingWord' are shown below:
text.split(' ').map(createWrappingWord);
*/
const createWrappingWord = (current) => ({
current,
done: [],
progress: {
count: current.length + 1,
words: [current],
},
});
const oneSpace = 1;
/* Example usages of 'mergeWrappingWords' are shown below:
words.reduce(mergeWrappingWords(width));
*/
const mergeWrappingWords =
(width) =>
(total, next) => {
const newCount = next.current.length + total.progress.count + oneSpace;
return newCount > width
? {
current: next.current,
done: [...total.done, total.progress.words.join(' ')],
progress: {
count: next.current.length + oneSpace,
words: [next.current],
},
}
: {
current: next.current,
done: total.done,
progress: {
count: newCount,
words: [...total.progress.words, next.current],
},
};
};
export /* Example usages of 'wrapWord' are shown below:
wrapWord(maxLineP, line);
wrapWord(maxLineOther, trimmed.slice(1).trim());
wrapWord(maxLineOther, trimmed.slice(2).trim());
*/
const wrapWord = (width, text) => {
const words = text.split(' ').map(createWrappingWord);
const result = words.reduce(mergeWrappingWords(width));
const done =
result.progress.words.length > 0
? [...result.done, result.progress.words.join(' ')]
: result.done;
return done.join('\n');
};
type MdLineType =
| 'blockquote'
| 'ordered-list'
| 'unordered-list'
| 'paragraph'
| 'header'
| 'table-row'
| 'code-block'
| 'horizontal-line';
/* Example usages of 'getMdLineType' are shown below:
getMdLineType(line);
*/
const getMdLineType = (line) => {
const trimmed = line.trim();
if (trimmed.startsWith('#')) {
return 'header';
}
if (trimmed.startsWith('>')) {
return 'blockquote';
}
if (trimmed.startsWith('1.')) {
return 'ordered-list';
}
if (trimmed.startsWith('---')) {
return 'horizontal-line';
}
if (trimmed.startsWith('-')) {
return 'unordered-list';
}
if (trimmed.includes('|')) {
return 'table-row';
}
if (line.length !== trimmed.length) {
return 'code-block';
}
return 'paragraph';
};
const maxLineP = 78;
const maxLineOther = 72;
/**
* @see https://cirosantilli.com/markdown-style-guide/
* @param text
* @returns
*/
export const normalizeMdLine = (line) => {
const lineType = getMdLineType(line);
const keepLineAsIs =
lineType === 'header' ||
lineType === 'table-row' ||
lineType === 'code-block' ||
lineType === 'horizontal-line';
if (keepLineAsIs) {
return line;
}
if (lineType === 'paragraph') {
return wrapWord(maxLineP, line);
}
const trimmed = line.trimStart();
const nbOfLeadingSpaces = line.length - trimmed.length;
const leadingSpaces = ' '.repeat(nbOfLeadingSpaces);
if (lineType === 'unordered-list') {
const ulText = wrapWord(maxLineOther, trimmed.slice(1).trim());
return `${leadingSpaces}- ${ulText}`;
}
if (lineType === 'ordered-list') {
const olText = wrapWord(maxLineOther, trimmed.slice(2).trim());
return `${leadingSpaces}1. ${olText}`;
}
if (lineType === 'blockquote') {
const bqText = wrapWord(maxLineOther, trimmed.slice(1).trim());
const bqSplitted = bqText.split('\n');
const bqPrefixed = bqSplitted.map((li) => `${leadingSpaces}> ${li}`);
return bqPrefixed.join('\n');
}
throw new Error('should be a supported line type');
};
|
fd1a43406609cdf0c7e50f51c80c8b4f6cbba4bf | 1,937 | ts | TypeScript | src/controllers/RickLaserScissorController.ts | ali77gh/NodeAndTypeScriptSamples | 293452042e5bd253babae48eb7cb0203a865a058 | [
"MIT"
] | 1 | 2022-03-12T09:13:36.000Z | 2022-03-12T09:13:36.000Z | src/controllers/RickLaserScissorController.ts | ali77gh/NodeAndTypeScriptSamples | 293452042e5bd253babae48eb7cb0203a865a058 | [
"MIT"
] | null | null | null | src/controllers/RickLaserScissorController.ts | ali77gh/NodeAndTypeScriptSamples | 293452042e5bd253babae48eb7cb0203a865a058 | [
"MIT"
] | null | null | null |
export default class RickLasererScissorController{
static prePath = "/ricklaserscissor"
static options = ["rick", "laser", "scissor"]
public static init(app) {
app.post(this.prePath + "/:play", (req, res) => {
let play = req.params["play"]
if (this.options.indexOf(play) == -1) {
res.status(404).send(
"not valid play\n" +
"play one of [rick laser scissor]"
);
} else {
let result = this.play(this.randOption(), play)
res.status(200).send(result)
}
})
app.get(this.prePath + "/getinfo", (req, res) => {
res.status(200).send(
"------game info-------\n" +
"rick > scissor\n" +
"scissor > laser\n" +
"laser > rick\n"
);
})
}
private static play(server: string, player: string): string {
let won = ""
let s = this.options.indexOf(server)
let p = this.options.indexOf(player)
if (s == 0 && p == 0) won = "draw"
if (s == 0 && p == 1) won = "player"
if (s == 0 && p == 2) won = "server"
if (s == 1 && p == 0) won = "server"
if (s == 1 && p == 1) won = "draw"
if (s == 1 && p == 2) won = "player"
if (s == 2 && p == 0) won = "player"
if (s == 2 && p == 1) won = "server"
if (s == 2 && p == 2) won = "draw"
return " you: " + player + "\n" +
" server: " + server + "\n" +
" won: " + won + "\n"
}
private static randOption(): string {
return this.options[this.randInt(0,2)]
}
private static randInt(min :number, max : number) : number {
max++;
return Math.floor(Math.random() * (max - min) + min);
}
} | 27.671429 | 65 | 0.420754 | 50 | 6 | 0 | 9 | 5 | 2 | 3 | 0 | 7 | 1 | 0 | 9 | 560 | 0.026786 | 0.008929 | 0.003571 | 0.001786 | 0 | 0 | 0.318182 | 0.265138 |
export default class RickLasererScissorController{
static prePath = "/ricklaserscissor"
static options = ["rick", "laser", "scissor"]
public static init(app) {
app.post(this.prePath + "/:play", (req, res) => {
let play = req.params["play"]
if (this.options.indexOf(play) == -1) {
res.status(404).send(
"not valid play\n" +
"play one of [rick laser scissor]"
);
} else {
let result = this.play(this.randOption(), play)
res.status(200).send(result)
}
})
app.get(this.prePath + "/getinfo", (req, res) => {
res.status(200).send(
"------game info-------\n" +
"rick > scissor\n" +
"scissor > laser\n" +
"laser > rick\n"
);
})
}
private static play(server, player) {
let won = ""
let s = this.options.indexOf(server)
let p = this.options.indexOf(player)
if (s == 0 && p == 0) won = "draw"
if (s == 0 && p == 1) won = "player"
if (s == 0 && p == 2) won = "server"
if (s == 1 && p == 0) won = "server"
if (s == 1 && p == 1) won = "draw"
if (s == 1 && p == 2) won = "player"
if (s == 2 && p == 0) won = "player"
if (s == 2 && p == 1) won = "server"
if (s == 2 && p == 2) won = "draw"
return " you: " + player + "\n" +
" server: " + server + "\n" +
" won: " + won + "\n"
}
private static randOption() {
return this.options[this.randInt(0,2)]
}
private static randInt(min , max ) {
max++;
return Math.floor(Math.random() * (max - min) + min);
}
} |
fd694cc69891360a53eb28a3dce0ddc7f353dbed | 3,522 | ts | TypeScript | web/src/pages/settings/integrations/add/git/Links.ts | ngalaiko/sturdy | 9b5220a6e2b219650bb36ca4a0319822fb113b76 | [
"Apache-2.0"
] | 226 | 2022-02-09T14:17:59.000Z | 2022-03-31T05:30:54.000Z | web/src/pages/settings/integrations/add/git/Links.ts | ngalaiko/sturdy | 9b5220a6e2b219650bb36ca4a0319822fb113b76 | [
"Apache-2.0"
] | 30 | 2022-02-25T09:06:40.000Z | 2022-03-31T07:34:40.000Z | web/src/pages/settings/integrations/add/git/Links.ts | ngalaiko/sturdy | 9b5220a6e2b219650bb36ca4a0319822fb113b76 | [
"Apache-2.0"
] | 7 | 2022-02-25T09:01:18.000Z | 2022-03-25T17:24:37.000Z | export const removeBasicAuth = function (url: string): string {
if (!url.includes('@')) {
return url
}
const isHTTP = url.startsWith('http://') || url.startsWith('https://')
if (!isHTTP) {
return url
}
const slashslash = url.indexOf('://')
const at = url.indexOf('@')
return url.substring(0, slashslash + 3) + url.substring(at + 1)
}
export const linkLooksLikeHttp = function (url: string): boolean {
const isHTTP = url.startsWith('http://') || url.startsWith('https://')
return isHTTP
}
export const linkLooksLikeSSH = function (url: string): boolean {
const isSSH = url.startsWith('ssh://')
return isSSH
}
export const defaultLinkRepo = function (gitURL: string): string | null {
gitURL = removeBasicAuth(gitURL)
// GitLab HTTP
if (gitURL.startsWith('https://gitlab.com/') && gitURL.endsWith('.git')) {
return gitURL.substring(0, gitURL.length - 4)
}
// GitLab SSH
if (gitURL.startsWith('git@gitlab.com:') && gitURL.endsWith('.git')) {
return 'https://gitlab.com/' + gitURL.substring(15, gitURL.length - 4)
}
// BitBucket HTTP
if (gitURL.startsWith('https://bitbucket.org/') && gitURL.endsWith('.git')) {
return gitURL.substring(0, gitURL.length - 4)
}
// BitBucket SSH
if (gitURL.startsWith('git@bitbucket.org:') && gitURL.endsWith('.git')) {
return 'https://bitbucket.org/' + gitURL.substring(18, gitURL.length - 4)
}
// Azure HTTP
if (gitURL.includes('dev.azure.com') && gitURL.includes('/_git/')) {
const s = gitURL.indexOf('dev.azure.com/')
const git = gitURL.indexOf('/_git/')
const parts = gitURL.substring(s, git).split('/')
if (parts.length === 3) {
return 'https://' + parts[0] + '/' + parts[1] + '/_git/' + parts[2]
}
}
// Azure SSH
if (gitURL.startsWith('git@ssh.dev.azure.com:v3/')) {
const parts = gitURL.substring(25).split('/')
return 'https://dev.azure.com/' + parts[0] + '/' + parts[1] + '/_git/' + parts[2]
}
return null
}
export const defaultLinkBranch = function (gitURL: string): string | null {
gitURL = removeBasicAuth(gitURL)
// GitLab HTTP
if (gitURL.startsWith('https://gitlab.com/') && gitURL.endsWith('.git')) {
return gitURL.substring(0, gitURL.length - 4) + '/-/tree/${BRANCH_NAME}'
}
// GitLab SSH
if (gitURL.startsWith('git@gitlab.com:') && gitURL.endsWith('.git')) {
return (
'https://gitlab.com/' + gitURL.substring(15, gitURL.length - 4) + '/-/tree/${BRANCH_NAME}'
)
}
// BitBucket HTTP
if (gitURL.startsWith('https://bitbucket.org/') && gitURL.endsWith('.git')) {
return gitURL.substring(0, gitURL.length - 4) + '/branch/${BRANCH_NAME}'
}
// BitBucket SSH
if (gitURL.startsWith('git@bitbucket.org:') && gitURL.endsWith('.git')) {
return (
'https://bitbucket.org/' + gitURL.substring(18, gitURL.length - 4) + '/branch/${BRANCH_NAME}'
)
}
// Azure HTTP
if (gitURL.includes('dev.azure.com') && gitURL.includes('/_git/')) {
const s = gitURL.indexOf('dev.azure.com/')
const git = gitURL.indexOf('/_git/')
return (
'https://' +
gitURL.substring(s, git) +
'/_git/' +
gitURL.substring(git + 6) +
'?version=GB${BRANCH_NAME}'
)
}
// Azure SSH
if (gitURL.startsWith('git@ssh.dev.azure.com:v3/')) {
const parts = gitURL.substring(25).split('/')
return (
'https://dev.azure.com/' +
parts[0] +
'/' +
parts[1] +
'/_git/' +
parts[2] +
'?version=GB${BRANCH_NAME}'
)
}
return null
}
| 28.403226 | 99 | 0.60619 | 91 | 5 | 0 | 5 | 17 | 0 | 1 | 0 | 10 | 0 | 0 | 16.2 | 1,100 | 0.009091 | 0.015455 | 0 | 0 | 0 | 0 | 0.37037 | 0.241616 | export /* Example usages of 'removeBasicAuth' are shown below:
gitURL = removeBasicAuth(gitURL);
*/
const removeBasicAuth = function (url) {
if (!url.includes('@')) {
return url
}
const isHTTP = url.startsWith('http://') || url.startsWith('https://')
if (!isHTTP) {
return url
}
const slashslash = url.indexOf('://')
const at = url.indexOf('@')
return url.substring(0, slashslash + 3) + url.substring(at + 1)
}
export const linkLooksLikeHttp = function (url) {
const isHTTP = url.startsWith('http://') || url.startsWith('https://')
return isHTTP
}
export const linkLooksLikeSSH = function (url) {
const isSSH = url.startsWith('ssh://')
return isSSH
}
export const defaultLinkRepo = function (gitURL) {
gitURL = removeBasicAuth(gitURL)
// GitLab HTTP
if (gitURL.startsWith('https://gitlab.com/') && gitURL.endsWith('.git')) {
return gitURL.substring(0, gitURL.length - 4)
}
// GitLab SSH
if (gitURL.startsWith('git@gitlab.com:') && gitURL.endsWith('.git')) {
return 'https://gitlab.com/' + gitURL.substring(15, gitURL.length - 4)
}
// BitBucket HTTP
if (gitURL.startsWith('https://bitbucket.org/') && gitURL.endsWith('.git')) {
return gitURL.substring(0, gitURL.length - 4)
}
// BitBucket SSH
if (gitURL.startsWith('git@bitbucket.org:') && gitURL.endsWith('.git')) {
return 'https://bitbucket.org/' + gitURL.substring(18, gitURL.length - 4)
}
// Azure HTTP
if (gitURL.includes('dev.azure.com') && gitURL.includes('/_git/')) {
const s = gitURL.indexOf('dev.azure.com/')
const git = gitURL.indexOf('/_git/')
const parts = gitURL.substring(s, git).split('/')
if (parts.length === 3) {
return 'https://' + parts[0] + '/' + parts[1] + '/_git/' + parts[2]
}
}
// Azure SSH
if (gitURL.startsWith('git@ssh.dev.azure.com:v3/')) {
const parts = gitURL.substring(25).split('/')
return 'https://dev.azure.com/' + parts[0] + '/' + parts[1] + '/_git/' + parts[2]
}
return null
}
export const defaultLinkBranch = function (gitURL) {
gitURL = removeBasicAuth(gitURL)
// GitLab HTTP
if (gitURL.startsWith('https://gitlab.com/') && gitURL.endsWith('.git')) {
return gitURL.substring(0, gitURL.length - 4) + '/-/tree/${BRANCH_NAME}'
}
// GitLab SSH
if (gitURL.startsWith('git@gitlab.com:') && gitURL.endsWith('.git')) {
return (
'https://gitlab.com/' + gitURL.substring(15, gitURL.length - 4) + '/-/tree/${BRANCH_NAME}'
)
}
// BitBucket HTTP
if (gitURL.startsWith('https://bitbucket.org/') && gitURL.endsWith('.git')) {
return gitURL.substring(0, gitURL.length - 4) + '/branch/${BRANCH_NAME}'
}
// BitBucket SSH
if (gitURL.startsWith('git@bitbucket.org:') && gitURL.endsWith('.git')) {
return (
'https://bitbucket.org/' + gitURL.substring(18, gitURL.length - 4) + '/branch/${BRANCH_NAME}'
)
}
// Azure HTTP
if (gitURL.includes('dev.azure.com') && gitURL.includes('/_git/')) {
const s = gitURL.indexOf('dev.azure.com/')
const git = gitURL.indexOf('/_git/')
return (
'https://' +
gitURL.substring(s, git) +
'/_git/' +
gitURL.substring(git + 6) +
'?version=GB${BRANCH_NAME}'
)
}
// Azure SSH
if (gitURL.startsWith('git@ssh.dev.azure.com:v3/')) {
const parts = gitURL.substring(25).split('/')
return (
'https://dev.azure.com/' +
parts[0] +
'/' +
parts[1] +
'/_git/' +
parts[2] +
'?version=GB${BRANCH_NAME}'
)
}
return null
}
|
fda75c27b5ef1547d8f7c3d77eb2d5a0b85acdae | 2,141 | ts | TypeScript | problemset/course-schedule/index.ts | OUDUIDUI/leet-code | 50e61ce16d1c419ccefc075ae9ead721cdd1cdbb | [
"MIT"
] | 6 | 2022-01-17T03:19:56.000Z | 2022-01-17T05:45:39.000Z | problemset/course-schedule/index.ts | OUDUIDUI/leet-code | 50e61ce16d1c419ccefc075ae9ead721cdd1cdbb | [
"MIT"
] | null | null | null | problemset/course-schedule/index.ts | OUDUIDUI/leet-code | 50e61ce16d1c419ccefc075ae9ead721cdd1cdbb | [
"MIT"
] | null | null | null | /**
* 深度优先搜索
* @desc 时间复杂度 O(M+NaN) 空间复杂度 O(M+N)
* @param numCourses
* @param prerequisites
* @returns
*/
export function canFinish(
numCourses: number,
prerequisites: number[][],
): boolean {
const edges: number[][] = new Array(numCourses)
.fill([])
.map(() => [] as number[])
// 初始化每节课的映射关系
// 即完成info[1]课程后,才可以学习info[0]课程
for (const info of prerequisites) edges[info[1]].push(info[0])
// 0 -> 未搜索
// 1 -> 搜索中
// 2 -> 已完成
const visited: (0 | 1 | 2)[] = new Array(numCourses).fill(0)
let valid = true
// 遍历所有课程
for (let i = 0; i < numCourses && valid; i++) {
// 如果该课程还没开始搜索,则开始递归搜索
if (visited[i] === 0) dfs(i)
}
return valid
/**
* 递归搜索
* @param i
* @returns
*/
function dfs(i: number) {
// 将该课程状态设置为搜索中
visited[i] = 1
// 遍历该门课程修完后才能学习的所有课程
for (const v of edges[i]) {
// 如果课程还未开始搜索,则开始递归搜索
if (visited[v] === 0) {
dfs(v)
if (!valid) return
}
// 如果该课程属于搜索中,则代表陷入循环,证明不可能完成所有课程
else if (visited[v] === 1) {
valid = false
return
}
}
// 搜索完成后,修改课程状态
visited[i] = 2
}
}
/**
* 广度优先搜索
* @desc 时间复杂度 O(M+NaN) 空间复杂度 O(M+N)
* @param numCourses
* @param prerequisites
* @returns
*/
export function canFinish2(
numCourses: number,
prerequisites: number[][],
): boolean {
// 记录每个课程的父节点树
const indeg: number[] = new Array(numCourses).fill(0)
const edges: number[][] = new Array(numCourses)
.fill([])
.map(() => [] as number[])
// 初始化每节课的映射关系
// 即完成info[1]课程后,才可以学习info[0]课程
for (const info of prerequisites) {
edges[info[1]].push(info[0])
indeg[info[0]]++
}
const queue: number[] = []
for (let i = 0; i < numCourses; i++) {
// 如果indeg[i] === 0,则代表这门课无需修完其他课程才可学习
if (indeg[i] === 0) queue.unshift(i)
}
let visited = 0
while (queue.length) {
// 记录已修的课程数
visited++
const i = queue.pop()!
// 遍历修完该课程才可修的课程
for (const v of edges[i]) {
// 更新数据
indeg[v]--
// 如果该课程已经满足可修的状态,则入队
if (indeg[v] === 0) queue.unshift(v)
}
}
// 判断修完的课程是否跟课程总数匹配
return visited === numCourses
}
| 20.390476 | 64 | 0.558617 | 56 | 5 | 0 | 5 | 10 | 0 | 1 | 0 | 13 | 0 | 2 | 12 | 847 | 0.011806 | 0.011806 | 0 | 0 | 0.002361 | 0 | 0.65 | 0.235316 | /**
* 深度优先搜索
* @desc 时间复杂度 O(M+NaN) 空间复杂度 O(M+N)
* @param numCourses
* @param prerequisites
* @returns
*/
export function canFinish(
numCourses,
prerequisites,
) {
const edges = new Array(numCourses)
.fill([])
.map(() => [] as number[])
// 初始化每节课的映射关系
// 即完成info[1]课程后,才可以学习info[0]课程
for (const info of prerequisites) edges[info[1]].push(info[0])
// 0 -> 未搜索
// 1 -> 搜索中
// 2 -> 已完成
const visited = new Array(numCourses).fill(0)
let valid = true
// 遍历所有课程
for (let i = 0; i < numCourses && valid; i++) {
// 如果该课程还没开始搜索,则开始递归搜索
if (visited[i] === 0) dfs(i)
}
return valid
/**
* 递归搜索
* @param i
* @returns
*/
/* Example usages of 'dfs' are shown below:
dfs(i);
dfs(v);
*/
function dfs(i) {
// 将该课程状态设置为搜索中
visited[i] = 1
// 遍历该门课程修完后才能学习的所有课程
for (const v of edges[i]) {
// 如果课程还未开始搜索,则开始递归搜索
if (visited[v] === 0) {
dfs(v)
if (!valid) return
}
// 如果该课程属于搜索中,则代表陷入循环,证明不可能完成所有课程
else if (visited[v] === 1) {
valid = false
return
}
}
// 搜索完成后,修改课程状态
visited[i] = 2
}
}
/**
* 广度优先搜索
* @desc 时间复杂度 O(M+NaN) 空间复杂度 O(M+N)
* @param numCourses
* @param prerequisites
* @returns
*/
export function canFinish2(
numCourses,
prerequisites,
) {
// 记录每个课程的父节点树
const indeg = new Array(numCourses).fill(0)
const edges = new Array(numCourses)
.fill([])
.map(() => [] as number[])
// 初始化每节课的映射关系
// 即完成info[1]课程后,才可以学习info[0]课程
for (const info of prerequisites) {
edges[info[1]].push(info[0])
indeg[info[0]]++
}
const queue = []
for (let i = 0; i < numCourses; i++) {
// 如果indeg[i] === 0,则代表这门课无需修完其他课程才可学习
if (indeg[i] === 0) queue.unshift(i)
}
let visited = 0
while (queue.length) {
// 记录已修的课程数
visited++
const i = queue.pop()!
// 遍历修完该课程才可修的课程
for (const v of edges[i]) {
// 更新数据
indeg[v]--
// 如果该课程已经满足可修的状态,则入队
if (indeg[v] === 0) queue.unshift(v)
}
}
// 判断修完的课程是否跟课程总数匹配
return visited === numCourses
}
|
fdb275ed85129a8c2487948a1f730af148093960 | 1,558 | ts | TypeScript | types/LogLevel.ts | heusalagroup/core | 94a2833012ae492609e79ac08bd31f81e73e7882 | [
"MIT"
] | 2 | 2022-03-05T12:53:04.000Z | 2022-03-05T12:53:06.000Z | types/LogLevel.ts | heusalagroup/fi.hg.core | 94a2833012ae492609e79ac08bd31f81e73e7882 | [
"MIT"
] | null | null | null | types/LogLevel.ts | heusalagroup/fi.hg.core | 94a2833012ae492609e79ac08bd31f81e73e7882 | [
"MIT"
] | null | null | null | // Copyright (c) 2021. Sendanor <info@sendanor.fi>. All rights reserved.
export enum LogLevel {
DEBUG,
INFO,
WARN,
ERROR,
NONE
}
export function isLogLevel (value: any): value is LogLevel {
switch (value) {
case LogLevel.DEBUG:
case LogLevel.INFO:
case LogLevel.WARN:
case LogLevel.ERROR:
case LogLevel.NONE:
return true;
default:
return false;
}
}
export function stringifyLogLevel (value : LogLevel) : string {
switch (value) {
case LogLevel.DEBUG : return 'DEBUG';
case LogLevel.INFO : return 'INFO';
case LogLevel.WARN : return 'WARN';
case LogLevel.ERROR : return 'ERROR';
case LogLevel.NONE : return 'NONE';
default : return `Unknown:${value}`;
}
}
export function parseLogLevel (value: any): LogLevel | undefined {
if ( !value ) return undefined;
if ( isLogLevel(value) ) return value;
value = `${value}`.toUpperCase();
switch (value) {
case 'ALL':
case 'DEBUG':
return LogLevel.DEBUG;
case 'INFO':
return LogLevel.INFO;
case 'WARN' :
case 'WARNING' :
return LogLevel.WARN;
case 'ERR' :
case 'ERROR' :
return LogLevel.ERROR;
case 'FALSE' :
case 'OFF' :
case 'QUIET' :
case 'SILENT' :
case 'NONE' :
return LogLevel.NONE;
default:
return undefined;
}
}
| 20.5 | 72 | 0.533376 | 55 | 3 | 0 | 3 | 0 | 0 | 1 | 2 | 1 | 0 | 0 | 14 | 395 | 0.01519 | 0 | 0 | 0 | 0 | 0.333333 | 0.166667 | 0.200336 | // Copyright (c) 2021. Sendanor <info@sendanor.fi>. All rights reserved.
export enum LogLevel {
DEBUG,
INFO,
WARN,
ERROR,
NONE
}
export /* Example usages of 'isLogLevel' are shown below:
isLogLevel(value);
*/
function isLogLevel (value): value is LogLevel {
switch (value) {
case LogLevel.DEBUG:
case LogLevel.INFO:
case LogLevel.WARN:
case LogLevel.ERROR:
case LogLevel.NONE:
return true;
default:
return false;
}
}
export function stringifyLogLevel (value ) {
switch (value) {
case LogLevel.DEBUG : return 'DEBUG';
case LogLevel.INFO : return 'INFO';
case LogLevel.WARN : return 'WARN';
case LogLevel.ERROR : return 'ERROR';
case LogLevel.NONE : return 'NONE';
default : return `Unknown:${value}`;
}
}
export function parseLogLevel (value) {
if ( !value ) return undefined;
if ( isLogLevel(value) ) return value;
value = `${value}`.toUpperCase();
switch (value) {
case 'ALL':
case 'DEBUG':
return LogLevel.DEBUG;
case 'INFO':
return LogLevel.INFO;
case 'WARN' :
case 'WARNING' :
return LogLevel.WARN;
case 'ERR' :
case 'ERROR' :
return LogLevel.ERROR;
case 'FALSE' :
case 'OFF' :
case 'QUIET' :
case 'SILENT' :
case 'NONE' :
return LogLevel.NONE;
default:
return undefined;
}
}
|
fdc7a1a3de5f51984fc8b1175ea1ac9f85485433 | 1,539 | ts | TypeScript | layerx-angular-frontend/src/app/models/label.model.ts | IsuruJayamanne/layerx-community | 656c04dcbd974388562b865d5acb84bc10a7425b | [
"MIT"
] | 16 | 2022-02-17T13:01:16.000Z | 2022-03-16T13:12:08.000Z | layerx-angular-frontend/src/app/models/label.model.ts | IsuruJayamanne/layerx-community | 656c04dcbd974388562b865d5acb84bc10a7425b | [
"MIT"
] | 1 | 2022-02-15T13:07:38.000Z | 2022-02-15T13:07:38.000Z | layerx-angular-frontend/src/app/models/label.model.ts | IsuruJayamanne/layerx-community | 656c04dcbd974388562b865d5acb84bc10a7425b | [
"MIT"
] | 1 | 2022-02-15T14:30:38.000Z | 2022-02-15T14:30:38.000Z | /**
Copyright (c) 2022 ZOOMi Technologies Inc.
all rights reserved.
This source code is licensed under the license found in the
LICENSE file in the root directory of this source tree.
*/
export class Label {
classAttributesList: Array<ClassWithAttributes>;
constructor() {
this.classAttributesList = [
{
label: '',
key: '',
description:'',
imgURL: '',
isAbleDelete: true,
isEditable:true,
attributes: [
{
label: '',
key: '',
errorMsg: false,
values: [
{
valueName: '',
description: '',
imgURL: '',
errorMsg: false,
},
],
},
],
},
];
}
}
export interface ClassWithAttributes {
label: string;
key: string;
description: string;
imgURL: string;
imgData?: any;
type?:number;
isAbleDelete?:boolean;
isEditable:boolean;
attributes: Array<attributeItem>;
}
export interface attributeItem {
label: string;
key: string;
errorMsg?: boolean;
values: Array<AttributeValueItem>;
}
export interface AttributeValueItem {
valueName: string;
description: string;
imgURL: string;
imgData?: any;
imgHeight?: number;
imgWidth?: number;
errorMsg?: boolean;
}
export class SelectedScreen {
public static classOnly = 1;
public static classWithAttributes = 2;
}
export class SelectedModalType {
public static new = 1;
public static edit = 2;
}
| 19 | 59 | 0.584146 | 64 | 1 | 0 | 0 | 0 | 25 | 0 | 2 | 16 | 6 | 0 | 25 | 371 | 0.002695 | 0 | 0.067385 | 0.016173 | 0 | 0.076923 | 0.615385 | 0.200489 | /**
Copyright (c) 2022 ZOOMi Technologies Inc.
all rights reserved.
This source code is licensed under the license found in the
LICENSE file in the root directory of this source tree.
*/
export class Label {
classAttributesList;
constructor() {
this.classAttributesList = [
{
label: '',
key: '',
description:'',
imgURL: '',
isAbleDelete: true,
isEditable:true,
attributes: [
{
label: '',
key: '',
errorMsg: false,
values: [
{
valueName: '',
description: '',
imgURL: '',
errorMsg: false,
},
],
},
],
},
];
}
}
export interface ClassWithAttributes {
label;
key;
description;
imgURL;
imgData?;
type?;
isAbleDelete?;
isEditable;
attributes;
}
export interface attributeItem {
label;
key;
errorMsg?;
values;
}
export interface AttributeValueItem {
valueName;
description;
imgURL;
imgData?;
imgHeight?;
imgWidth?;
errorMsg?;
}
export class SelectedScreen {
public static classOnly = 1;
public static classWithAttributes = 2;
}
export class SelectedModalType {
public static new = 1;
public static edit = 2;
}
|
fdc9189ec7b996193ecc113e362ffdc22f88d5cc | 1,992 | ts | TypeScript | src/lib/list/utils/pagination-utils.ts | nexys-system/core-list | b2fb09917528f41b438e20717647cdf9ac406d38 | [
"MIT"
] | null | null | null | src/lib/list/utils/pagination-utils.ts | nexys-system/core-list | b2fb09917528f41b438e20717647cdf9ac406d38 | [
"MIT"
] | 1 | 2022-03-23T08:15:10.000Z | 2022-03-23T08:15:10.000Z | src/lib/list/utils/pagination-utils.ts | nexys-system/core-list | b2fb09917528f41b438e20717647cdf9ac406d38 | [
"MIT"
] | null | null | null | /**
* get the number of pages
* @param {[type]} n total number of rows
* @param {[type]} nPerPage number of rows per page
* @return {[type]} number of pages
*/
export const getNPage = (n: number, nPerPage: number): number => {
return Math.ceil(n / nPerPage);
};
interface GetPaginationReturn {
idx: number;
nPerPage: number;
nPage: number;
}
export const getPagination = (
n: number,
nPerPageIn: number
): GetPaginationReturn => {
const nPerPage = nPerPageIn || 10;
const nPage = getNPage(n, nPerPage);
const idx = 1;
return {
idx,
nPerPage,
nPage
};
};
/**
* get list of page based on the index (-i means that there's a gap - we do not use null so that it can than be used as an index)
* @param {[type]} idx the page on which the user id
* @param {[type]} nPage the total amount of pages
* @return {[type]} [1, null, idx - 1, idx, idx + 1, null, nPage]
*/
export const getPageTiles = (idx: number, nPage: number): any[] => {
if (idx < 1) {
idx = 1;
}
if (idx > nPage) {
idx = nPage;
}
const b1 = idx - 1;
const b2 = idx + 1;
// init array
const arr = [idx];
if (idx > 1) {
arr.unshift(b1);
}
if (idx === nPage && nPage > 3) {
arr.unshift(b1 - 1);
}
if (idx < nPage) {
arr.push(b2);
}
if (idx === 1 && nPage > 3) {
arr.push(3);
}
if (b1 > 2 && nPage > 4) {
arr.unshift(-1);
}
if (b1 > 1) {
arr.unshift(1);
}
if (b2 < nPage - 1 && nPage > 4) {
arr.push(-2);
}
if (b2 < nPage) {
arr.push(nPage);
}
return arr;
};
export const paginationBoundaries = (
idx: number,
nPerPage: number
): { start: number; end: number } => {
const start = (idx - 1) * nPerPage;
const end = idx * nPerPage;
return { start, end };
};
export const withPagination = <A>(
data: A[],
idx: number,
nPerPage: number
): A[] => {
const { start, end } = paginationBoundaries(idx, nPerPage);
return data.slice(start, end);
};
| 18.616822 | 129 | 0.565763 | 73 | 5 | 0 | 11 | 14 | 3 | 2 | 1 | 16 | 1 | 0 | 9.6 | 682 | 0.02346 | 0.020528 | 0.004399 | 0.001466 | 0 | 0.030303 | 0.484848 | 0.293797 | /**
* get the number of pages
* @param {[type]} n total number of rows
* @param {[type]} nPerPage number of rows per page
* @return {[type]} number of pages
*/
export /* Example usages of 'getNPage' are shown below:
getNPage(n, nPerPage);
*/
const getNPage = (n, nPerPage) => {
return Math.ceil(n / nPerPage);
};
interface GetPaginationReturn {
idx;
nPerPage;
nPage;
}
export const getPagination = (
n,
nPerPageIn
) => {
const nPerPage = nPerPageIn || 10;
const nPage = getNPage(n, nPerPage);
const idx = 1;
return {
idx,
nPerPage,
nPage
};
};
/**
* get list of page based on the index (-i means that there's a gap - we do not use null so that it can than be used as an index)
* @param {[type]} idx the page on which the user id
* @param {[type]} nPage the total amount of pages
* @return {[type]} [1, null, idx - 1, idx, idx + 1, null, nPage]
*/
export const getPageTiles = (idx, nPage) => {
if (idx < 1) {
idx = 1;
}
if (idx > nPage) {
idx = nPage;
}
const b1 = idx - 1;
const b2 = idx + 1;
// init array
const arr = [idx];
if (idx > 1) {
arr.unshift(b1);
}
if (idx === nPage && nPage > 3) {
arr.unshift(b1 - 1);
}
if (idx < nPage) {
arr.push(b2);
}
if (idx === 1 && nPage > 3) {
arr.push(3);
}
if (b1 > 2 && nPage > 4) {
arr.unshift(-1);
}
if (b1 > 1) {
arr.unshift(1);
}
if (b2 < nPage - 1 && nPage > 4) {
arr.push(-2);
}
if (b2 < nPage) {
arr.push(nPage);
}
return arr;
};
export /* Example usages of 'paginationBoundaries' are shown below:
paginationBoundaries(idx, nPerPage);
*/
const paginationBoundaries = (
idx,
nPerPage
) => {
const start = (idx - 1) * nPerPage;
const end = idx * nPerPage;
return { start, end };
};
export const withPagination = <A>(
data,
idx,
nPerPage
) => {
const { start, end } = paginationBoundaries(idx, nPerPage);
return data.slice(start, end);
};
|
fdf12f247ed75d2db7a6597482d6ebb301ddd41c | 2,916 | ts | TypeScript | lib/poly/simplify.ts | dra2020/baseclient | 8dccdf6c247f0dc0a5ce4bf7f8966825d7a2f5c8 | [
"MIT"
] | 1 | 2022-01-19T20:29:12.000Z | 2022-01-19T20:29:12.000Z | lib/poly/simplify.ts | dra2020/baseclient | 8dccdf6c247f0dc0a5ce4bf7f8966825d7a2f5c8 | [
"MIT"
] | null | null | null | lib/poly/simplify.ts | dra2020/baseclient | 8dccdf6c247f0dc0a5ce4bf7f8966825d7a2f5c8 | [
"MIT"
] | null | null | null | /*
Adapted from:
(c) 2017, Vladimir Agafonkin
Simplify.js, a high-performance JS polyline simplification library
mourner.github.io/simplify-js
*/
export type Point = [ number, number];
// square distance between 2 points
function getSqDist(p1: Point, p2: Point): number
{
var dx = p1[0] - p2[0],
dy = p1[1] - p2[1];
return dx * dx + dy * dy;
}
// square distance from a point to a segment
function getSqSegDist(p: Point, p1: Point, p2: Point): number
{
var x = p1[0],
y = p1[1],
dx = p2[0] - x,
dy = p2[1] - y;
if (dx !== 0 || dy !== 0) {
var t = ((p[0] - x) * dx + (p[1] - y) * dy) / (dx * dx + dy * dy);
if (t > 1) {
x = p2[0];
y = p2[1];
} else if (t > 0) {
x += dx * t;
y += dy * t;
}
}
dx = p[0] - x;
dy = p[1] - y;
return dx * dx + dy * dy;
}
// rest of the code doesn't care about point format
// basic distance-based simplification
function simplifyRadialDist(points: Point[], sqTolerance: number): Point[]
{
let prevPoint: Point = points[0],
newPoints: Point[] = [prevPoint],
point: Point;
for (let i = 1, len = points.length; i < len; i++) {
point = points[i];
if (getSqDist(point, prevPoint) > sqTolerance) {
newPoints.push(point);
prevPoint = point;
}
}
if (prevPoint !== point) newPoints.push(point);
return newPoints;
}
function simplifyDPStep(points: Point[], first: number, last: number, sqTolerance: number, simplified: Point[]): void
{
let maxSqDist: number = sqTolerance,
index: number;
for (let i = first + 1; i < last; i++)
{
let sqDist = getSqSegDist(points[i], points[first], points[last]);
if (sqDist > maxSqDist)
{
index = i;
maxSqDist = sqDist;
}
}
if (maxSqDist > sqTolerance)
{
if (index - first > 1) simplifyDPStep(points, first, index, sqTolerance, simplified);
simplified.push(points[index]);
if (last - index > 1) simplifyDPStep(points, index, last, sqTolerance, simplified);
}
}
// simplification using Ramer-Douglas-Peucker algorithm
function simplifyDouglasPeucker(points: Point[], sqTolerance: number): Point[]
{
let last: number = points.length - 1;
let simplified: Point[] = [points[0]];
simplifyDPStep(points, 0, last, sqTolerance, simplified);
simplified.push(points[last]);
return simplified;
}
// both algorithms combined for awesome performance
export function simplify(points: Point[], tolerance: number = 1, highestQuality: boolean = false): Point[]
{
if (tolerance == 0 || points.length <= 2)
return points;
let sqTolerance: number = tolerance * tolerance;
points = highestQuality ? points : simplifyRadialDist(points, sqTolerance);
points = simplifyDouglasPeucker(points, sqTolerance);
return points;
}
| 24.3 | 117 | 0.597051 | 79 | 6 | 0 | 17 | 19 | 0 | 5 | 0 | 16 | 1 | 0 | 10 | 894 | 0.025727 | 0.021253 | 0 | 0.001119 | 0 | 0 | 0.380952 | 0.302295 | /*
Adapted from:
(c) 2017, Vladimir Agafonkin
Simplify.js, a high-performance JS polyline simplification library
mourner.github.io/simplify-js
*/
export type Point = [ number, number];
// square distance between 2 points
/* Example usages of 'getSqDist' are shown below:
getSqDist(point, prevPoint) > sqTolerance;
*/
function getSqDist(p1, p2)
{
var dx = p1[0] - p2[0],
dy = p1[1] - p2[1];
return dx * dx + dy * dy;
}
// square distance from a point to a segment
/* Example usages of 'getSqSegDist' are shown below:
getSqSegDist(points[i], points[first], points[last]);
*/
function getSqSegDist(p, p1, p2)
{
var x = p1[0],
y = p1[1],
dx = p2[0] - x,
dy = p2[1] - y;
if (dx !== 0 || dy !== 0) {
var t = ((p[0] - x) * dx + (p[1] - y) * dy) / (dx * dx + dy * dy);
if (t > 1) {
x = p2[0];
y = p2[1];
} else if (t > 0) {
x += dx * t;
y += dy * t;
}
}
dx = p[0] - x;
dy = p[1] - y;
return dx * dx + dy * dy;
}
// rest of the code doesn't care about point format
// basic distance-based simplification
/* Example usages of 'simplifyRadialDist' are shown below:
points = highestQuality ? points : simplifyRadialDist(points, sqTolerance);
*/
function simplifyRadialDist(points, sqTolerance)
{
let prevPoint = points[0],
newPoints = [prevPoint],
point;
for (let i = 1, len = points.length; i < len; i++) {
point = points[i];
if (getSqDist(point, prevPoint) > sqTolerance) {
newPoints.push(point);
prevPoint = point;
}
}
if (prevPoint !== point) newPoints.push(point);
return newPoints;
}
/* Example usages of 'simplifyDPStep' are shown below:
simplifyDPStep(points, first, index, sqTolerance, simplified);
simplifyDPStep(points, index, last, sqTolerance, simplified);
simplifyDPStep(points, 0, last, sqTolerance, simplified);
*/
function simplifyDPStep(points, first, last, sqTolerance, simplified)
{
let maxSqDist = sqTolerance,
index;
for (let i = first + 1; i < last; i++)
{
let sqDist = getSqSegDist(points[i], points[first], points[last]);
if (sqDist > maxSqDist)
{
index = i;
maxSqDist = sqDist;
}
}
if (maxSqDist > sqTolerance)
{
if (index - first > 1) simplifyDPStep(points, first, index, sqTolerance, simplified);
simplified.push(points[index]);
if (last - index > 1) simplifyDPStep(points, index, last, sqTolerance, simplified);
}
}
// simplification using Ramer-Douglas-Peucker algorithm
/* Example usages of 'simplifyDouglasPeucker' are shown below:
points = simplifyDouglasPeucker(points, sqTolerance);
*/
function simplifyDouglasPeucker(points, sqTolerance)
{
let last = points.length - 1;
let simplified = [points[0]];
simplifyDPStep(points, 0, last, sqTolerance, simplified);
simplified.push(points[last]);
return simplified;
}
// both algorithms combined for awesome performance
export function simplify(points, tolerance = 1, highestQuality = false)
{
if (tolerance == 0 || points.length <= 2)
return points;
let sqTolerance = tolerance * tolerance;
points = highestQuality ? points : simplifyRadialDist(points, sqTolerance);
points = simplifyDouglasPeucker(points, sqTolerance);
return points;
}
|
fdf4bdbba361f01fc77025a3bba125b4343ebe4d | 2,886 | ts | TypeScript | wwwroot/libs/vidyano/common/expression-parser.ts | Vidyano/vidyano | 1c7639568974515e821dd033beff6df360a3ca58 | [
"MIT"
] | null | null | null | wwwroot/libs/vidyano/common/expression-parser.ts | Vidyano/vidyano | 1c7639568974515e821dd033beff6df360a3ca58 | [
"MIT"
] | 10 | 2022-03-16T12:52:46.000Z | 2022-03-25T12:05:18.000Z | wwwroot/libs/vidyano/common/expression-parser.ts | Vidyano/vidyano | 1c7639568974515e821dd033beff6df360a3ca58 | [
"MIT"
] | null | null | null | export class ExpressionParser {
static readonly alwaysTrue = function () { return true; };
private static _cache = {};
private static _operands = ["<=", ">=", "<", ">", "!=", "="];
static get(expression: string) {
if (!expression || !expression.trim())
return this.alwaysTrue;
expression = expression.replace(/ /g, "").toUpperCase();
var result = this._cache[expression];
if (result == null)
return this._cache[expression] = ExpressionParser.parse(expression);
return result;
}
static parse(expression: string) {
var get = this.get;
var operands = this._operands;
var parts = expression.split('X');
if (parts.length > 1) {
// Combine parts
var result = null;
for (var i = 0; i < parts.length; i++) {
var part = parts[i];
var newResult = get(part);
if (result != null) {
var previousResult = result;
result = function (arg) { return previousResult(arg) && newResult(arg); };
}
else
result = newResult;
}
return result;
}
if (expression != parts[0])
return get(parts[0]);
// Get operand
for (var idx = 0; idx < operands.length; idx++) {
var operand = operands[idx];
var index = expression.indexOf(operand);
if (index >= 0) {
expression = expression.replace(operand, "");
if (index > 0) {
// NOTE: Change 5< to >5
if (operand.includes("<"))
return get(operand.replace("<", ">") + expression);
if (operand.includes(">"))
return get(operand.replace(">", "<") + expression);
}
var number = parseInt(expression, 10);
if (!isNaN(number)) {
switch (operand) {
case "<":
return new Function("x", "return x < " + number + ";");
case "<=":
return new Function("x", "return x <= " + number + ";");
case ">":
return new Function("x", "return x > " + number + ";");
case ">=":
return new Function("x", "return x >= " + number + ";");
case "!=":
return new Function("x", "return x != " + number + ";");
default:
return new Function("x", "return x == " + number + ";");
}
}
}
}
return this.alwaysTrue;
}
} | 36.531646 | 94 | 0.417879 | 66 | 4 | 0 | 3 | 13 | 3 | 2 | 0 | 2 | 1 | 0 | 14.75 | 584 | 0.011986 | 0.02226 | 0.005137 | 0.001712 | 0 | 0 | 0.086957 | 0.274011 | export class ExpressionParser {
static readonly alwaysTrue = function () { return true; };
private static _cache = {};
private static _operands = ["<=", ">=", "<", ">", "!=", "="];
static get(expression) {
if (!expression || !expression.trim())
return this.alwaysTrue;
expression = expression.replace(/ /g, "").toUpperCase();
var result = this._cache[expression];
if (result == null)
return this._cache[expression] = ExpressionParser.parse(expression);
return result;
}
static parse(expression) {
var get = this.get;
var operands = this._operands;
var parts = expression.split('X');
if (parts.length > 1) {
// Combine parts
var result = null;
for (var i = 0; i < parts.length; i++) {
var part = parts[i];
var newResult = get(part);
if (result != null) {
var previousResult = result;
result = function (arg) { return previousResult(arg) && newResult(arg); };
}
else
result = newResult;
}
return result;
}
if (expression != parts[0])
return get(parts[0]);
// Get operand
for (var idx = 0; idx < operands.length; idx++) {
var operand = operands[idx];
var index = expression.indexOf(operand);
if (index >= 0) {
expression = expression.replace(operand, "");
if (index > 0) {
// NOTE: Change 5< to >5
if (operand.includes("<"))
return get(operand.replace("<", ">") + expression);
if (operand.includes(">"))
return get(operand.replace(">", "<") + expression);
}
var number = parseInt(expression, 10);
if (!isNaN(number)) {
switch (operand) {
case "<":
return new Function("x", "return x < " + number + ";");
case "<=":
return new Function("x", "return x <= " + number + ";");
case ">":
return new Function("x", "return x > " + number + ";");
case ">=":
return new Function("x", "return x >= " + number + ";");
case "!=":
return new Function("x", "return x != " + number + ";");
default:
return new Function("x", "return x == " + number + ";");
}
}
}
}
return this.alwaysTrue;
}
} |
bc2b93a54e19a4a8e00e7fd7c505249b9848caf4 | 3,990 | ts | TypeScript | src/model/documentation/blocks/SDKDocumentationPageBlockShortcut.ts | Supernova-Studio/sdk-typescript | 87d4a068ab6fe6cbd8b6876f3e7c7ca8e2b40f8d | [
"MIT"
] | 3 | 2022-01-26T16:45:35.000Z | 2022-03-25T03:44:47.000Z | src/model/documentation/blocks/SDKDocumentationPageBlockShortcut.ts | Supernova-Studio/sdk-typescript | 87d4a068ab6fe6cbd8b6876f3e7c7ca8e2b40f8d | [
"MIT"
] | null | null | null | src/model/documentation/blocks/SDKDocumentationPageBlockShortcut.ts | Supernova-Studio/sdk-typescript | 87d4a068ab6fe6cbd8b6876f3e7c7ca8e2b40f8d | [
"MIT"
] | null | null | null | //
// DocumentationPageBlockShortcut.ts
// Pulsar Language
//
// Created by Jiri Trecak.
// Copyright © 2021 Supernova. All rights reserved.
//
// --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- ---
// MARK: - Imports
// --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- ---
// MARK: - Definitions
export interface DocumentationPageBlockShortcutModel {
title?: string
description?: string
assetId?: string
assetUrl?: string
documentationItemId?: string
url?: string
urlPreview?: {
title?: string
description?: string
thumbnailUrl?: string
}
documentationItemPreview?: {
title?: string
valid?: boolean
}
}
export enum DocumentationPageBlockShortcutType {
external = 'External',
internal = 'Internal'
}
// --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- ---
// MARK: - Object Definition
export class DocumentationPageBlockShortcut {
// --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- ---
// MARK: - Public properties
// Visual data
title: string | null
description: string | null
previewUrl: string | null
// Linking data
externalUrl: string | null
internalId: string | null
// Block type
type: DocumentationPageBlockShortcutType
// --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- ---
// MARK: - Constructor
constructor(model: DocumentationPageBlockShortcutModel) {
// First, configure type of the block properly
if (model.url) {
this.type = DocumentationPageBlockShortcutType.external
} else {
this.type = DocumentationPageBlockShortcutType.internal
}
// Configure visual block information
this.title = this.shortcutTitleFromModel(model, this.type)
this.description = this.shortcutDescriptionFromModel(model, this.type)
this.previewUrl = this.shortcutPreviewUrlFromModel(model, this.type)
// Configure linking for pages and group inside documentation
if (
this.type === DocumentationPageBlockShortcutType.internal &&
model.documentationItemPreview?.valid &&
model.documentationItemId
) {
this.internalId = model.documentationItemId
} else {
this.internalId = null
// Configure for external URLs
if (this.type === DocumentationPageBlockShortcutType.external && model.url) {
this.externalUrl = model.url
} else {
this.externalUrl = null
}
}
}
shortcutTitleFromModel(
model: DocumentationPageBlockShortcutModel,
type: DocumentationPageBlockShortcutType
): string | null {
let result: string | null = null
if (model.title && model.title.trim().length > 0) {
result = model.title
} else if (type === DocumentationPageBlockShortcutType.internal) {
result = model.documentationItemPreview?.title ?? null
} else if (type === DocumentationPageBlockShortcutType.external) {
result = model.urlPreview?.title ?? model.url ?? null
}
if (!result || result.trim().length === 0) {
return null
}
return result
}
shortcutDescriptionFromModel(
model: DocumentationPageBlockShortcutModel,
type: DocumentationPageBlockShortcutType
): string | null {
let result: string | null = null
if (model.description && model.description.trim().length > 0) {
result = model.description
} else if (type === DocumentationPageBlockShortcutType.external) {
result = model.urlPreview?.description
}
if (!result || result.trim().length === 0) {
return null
}
return result
}
shortcutPreviewUrlFromModel(
model: DocumentationPageBlockShortcutModel,
type: DocumentationPageBlockShortcutType
): string | null {
return model.assetUrl ?? model.urlPreview?.thumbnailUrl ?? null
}
}
| 28.705036 | 110 | 0.595238 | 91 | 4 | 0 | 7 | 2 | 14 | 3 | 0 | 21 | 2 | 0 | 11.25 | 943 | 0.011665 | 0.002121 | 0.014846 | 0.002121 | 0 | 0 | 0.777778 | 0.207455 | //
// DocumentationPageBlockShortcut.ts
// Pulsar Language
//
// Created by Jiri Trecak.
// Copyright © 2021 Supernova. All rights reserved.
//
// --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- ---
// MARK: - Imports
// --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- ---
// MARK: - Definitions
export interface DocumentationPageBlockShortcutModel {
title?
description?
assetId?
assetUrl?
documentationItemId?
url?
urlPreview?
documentationItemPreview?
}
export enum DocumentationPageBlockShortcutType {
external = 'External',
internal = 'Internal'
}
// --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- ---
// MARK: - Object Definition
export class DocumentationPageBlockShortcut {
// --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- ---
// MARK: - Public properties
// Visual data
title
description
previewUrl
// Linking data
externalUrl
internalId
// Block type
type
// --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- ---
// MARK: - Constructor
constructor(model) {
// First, configure type of the block properly
if (model.url) {
this.type = DocumentationPageBlockShortcutType.external
} else {
this.type = DocumentationPageBlockShortcutType.internal
}
// Configure visual block information
this.title = this.shortcutTitleFromModel(model, this.type)
this.description = this.shortcutDescriptionFromModel(model, this.type)
this.previewUrl = this.shortcutPreviewUrlFromModel(model, this.type)
// Configure linking for pages and group inside documentation
if (
this.type === DocumentationPageBlockShortcutType.internal &&
model.documentationItemPreview?.valid &&
model.documentationItemId
) {
this.internalId = model.documentationItemId
} else {
this.internalId = null
// Configure for external URLs
if (this.type === DocumentationPageBlockShortcutType.external && model.url) {
this.externalUrl = model.url
} else {
this.externalUrl = null
}
}
}
shortcutTitleFromModel(
model,
type
) {
let result = null
if (model.title && model.title.trim().length > 0) {
result = model.title
} else if (type === DocumentationPageBlockShortcutType.internal) {
result = model.documentationItemPreview?.title ?? null
} else if (type === DocumentationPageBlockShortcutType.external) {
result = model.urlPreview?.title ?? model.url ?? null
}
if (!result || result.trim().length === 0) {
return null
}
return result
}
shortcutDescriptionFromModel(
model,
type
) {
let result = null
if (model.description && model.description.trim().length > 0) {
result = model.description
} else if (type === DocumentationPageBlockShortcutType.external) {
result = model.urlPreview?.description
}
if (!result || result.trim().length === 0) {
return null
}
return result
}
shortcutPreviewUrlFromModel(
model,
type
) {
return model.assetUrl ?? model.urlPreview?.thumbnailUrl ?? null
}
}
|
214457466acdc6f5118b98db04d04347d62d0347 | 2,495 | ts | TypeScript | problemset/word-ladder-2/index.ts | OUDUIDUI/leet-code | 50e61ce16d1c419ccefc075ae9ead721cdd1cdbb | [
"MIT"
] | 6 | 2022-01-17T03:19:56.000Z | 2022-01-17T05:45:39.000Z | problemset/word-ladder-2/index.ts | OUDUIDUI/leet-code | 50e61ce16d1c419ccefc075ae9ead721cdd1cdbb | [
"MIT"
] | null | null | null | problemset/word-ladder-2/index.ts | OUDUIDUI/leet-code | 50e61ce16d1c419ccefc075ae9ead721cdd1cdbb | [
"MIT"
] | null | null | null | /**
* 广度优先搜索
* @param beginWord
* @param endWord
* @param wordList
*/
export function findLadders(
beginWord: string,
endWord: string,
wordList: string[],
): string[][] {
const wordSet = new Set<string>(wordList)
// 如果没有终点词,直接返回
if (!wordSet.has(endWord)) return []
// 增加起点词
wordSet.add(beginWord)
// 存放图中的单词所在的层
// beginWord的level为0,以此叠加
const levelMap = new Map<string, number>()
// 存放图中的单词的邻接单词
const wordMap = new Map<string, string[]>()
// 记录访问过的节点
const visited = new Set<string>()
visited.add(beginWord)
// 维护一个队列,初始放入起点词
const queue = [beginWord]
// 是否存在变化到终点词的路径
let finished = false
// 起始词的level为0
let level = 0
levelMap.set(beginWord, 0)
while (queue.length && !finished) {
// 当前level的单词长度
const levelSize = queue.length
// 遍历当前层的单词,level+1
level++
// 遍历单词的所有字符
for (let i = 0; i < levelSize; i++) {
const word = queue.shift()!
// 遍历26个字母字符
for (let j = 0; j < word.length; j++) {
for (let k = 97; k <= 122; k++) {
// 拼接单词
const newWord
= word.slice(0, j) + String.fromCharCode(k) + word.slice(j + 1)
// 不是单词表中的单词就忽略
if (!wordSet.has(newWord)) continue
// 存入 wordMap
if (wordMap.has(newWord)) wordMap.get(newWord)!.push(word)
else wordMap.set(newWord, [word])
// 该新单词已经访问过就忽略
if (visited.has(newWord)) continue
// 遇到了终点词
if (newWord === endWord) finished = true
// 记录这个单词的level
levelMap.set(newWord, level)
// 该新单词是下一层的,入列
queue.push(newWord)
// 入列即访问,记录一下
visited.add(newWord)
}
}
}
}
// 无法到达终点词,返回[]
if (!finished) return []
const res: string[][] = []
dfs([], beginWord, endWord)
return res
/**
* 回溯 从结束词往前查找开始词
* @param path
* @param beginWord
* @param word
*/
function dfs(path: string[], beginWord: string, word: string) {
// 当前遍历的word,和起始词相同
if (word === beginWord) {
// 将当前路径推入res数组,加上起始词
res.push([beginWord, ...path])
return
}
// 将当前单词加入到path数组的开头
path.unshift(word)
// 当前单词有对应的“父单词”们
if (wordMap.has(word)) {
// 遍历“父单词”们
for (const parent of wordMap.get(word)!) {
if (levelMap.get(parent)! + 1 === levelMap.get(word)) {
// 满足要求的递归dfs
dfs(path, beginWord, parent)
}
}
}
// 回溯,撤销选择,将path数组开头的单词弹出
path.shift()
}
}
| 22.079646 | 75 | 0.559519 | 57 | 2 | 0 | 6 | 14 | 0 | 1 | 0 | 14 | 0 | 0 | 32 | 905 | 0.00884 | 0.01547 | 0 | 0 | 0 | 0 | 0.636364 | 0.240811 | /**
* 广度优先搜索
* @param beginWord
* @param endWord
* @param wordList
*/
export function findLadders(
beginWord,
endWord,
wordList,
) {
const wordSet = new Set<string>(wordList)
// 如果没有终点词,直接返回
if (!wordSet.has(endWord)) return []
// 增加起点词
wordSet.add(beginWord)
// 存放图中的单词所在的层
// beginWord的level为0,以此叠加
const levelMap = new Map<string, number>()
// 存放图中的单词的邻接单词
const wordMap = new Map<string, string[]>()
// 记录访问过的节点
const visited = new Set<string>()
visited.add(beginWord)
// 维护一个队列,初始放入起点词
const queue = [beginWord]
// 是否存在变化到终点词的路径
let finished = false
// 起始词的level为0
let level = 0
levelMap.set(beginWord, 0)
while (queue.length && !finished) {
// 当前level的单词长度
const levelSize = queue.length
// 遍历当前层的单词,level+1
level++
// 遍历单词的所有字符
for (let i = 0; i < levelSize; i++) {
const word = queue.shift()!
// 遍历26个字母字符
for (let j = 0; j < word.length; j++) {
for (let k = 97; k <= 122; k++) {
// 拼接单词
const newWord
= word.slice(0, j) + String.fromCharCode(k) + word.slice(j + 1)
// 不是单词表中的单词就忽略
if (!wordSet.has(newWord)) continue
// 存入 wordMap
if (wordMap.has(newWord)) wordMap.get(newWord)!.push(word)
else wordMap.set(newWord, [word])
// 该新单词已经访问过就忽略
if (visited.has(newWord)) continue
// 遇到了终点词
if (newWord === endWord) finished = true
// 记录这个单词的level
levelMap.set(newWord, level)
// 该新单词是下一层的,入列
queue.push(newWord)
// 入列即访问,记录一下
visited.add(newWord)
}
}
}
}
// 无法到达终点词,返回[]
if (!finished) return []
const res = []
dfs([], beginWord, endWord)
return res
/**
* 回溯 从结束词往前查找开始词
* @param path
* @param beginWord
* @param word
*/
/* Example usages of 'dfs' are shown below:
dfs([], beginWord, endWord);
// 满足要求的递归dfs
dfs(path, beginWord, parent);
*/
function dfs(path, beginWord, word) {
// 当前遍历的word,和起始词相同
if (word === beginWord) {
// 将当前路径推入res数组,加上起始词
res.push([beginWord, ...path])
return
}
// 将当前单词加入到path数组的开头
path.unshift(word)
// 当前单词有对应的“父单词”们
if (wordMap.has(word)) {
// 遍历“父单词”们
for (const parent of wordMap.get(word)!) {
if (levelMap.get(parent)! + 1 === levelMap.get(word)) {
// 满足要求的递归dfs
dfs(path, beginWord, parent)
}
}
}
// 回溯,撤销选择,将path数组开头的单词弹出
path.shift()
}
}
|
7291b06f45ed4125a8cf5d2f9fc1d1a9050c5845 | 1,966 | ts | TypeScript | facturador-java/src/app/core/models/producto.model.ts | dPanibra0/Facturador-JAVA | 2a9111dbce8c6c15fed9d4cc15ad4b9918c602ac | [
"MIT"
] | null | null | null | facturador-java/src/app/core/models/producto.model.ts | dPanibra0/Facturador-JAVA | 2a9111dbce8c6c15fed9d4cc15ad4b9918c602ac | [
"MIT"
] | 1 | 2022-03-02T08:30:43.000Z | 2022-03-02T08:30:43.000Z | facturador-java/src/app/core/models/producto.model.ts | dPanibra0/Facturador-JAVA | 2a9111dbce8c6c15fed9d4cc15ad4b9918c602ac | [
"MIT"
] | null | null | null | export class Producto {
public codproducto: number;
public almacen: string;
public cantidad: number;
public cantmin: number;
public cantp1: number;
public cantp2: number;
public categoria: string;
public codbarra: string;
public color: string;
public detalles: string;
public estado: number;
public fechavenc: string;
public iddistrib: number;
public laboratorio: string;
public lote: string;
public marca: string;
public precioco: number;
public preciove: number;
public prep1: number;
public prep2: number;
public producto: string;
public promo1: string;
public promo2: string;
public ptjganancia: number;
public unimedida: string;
constructor(
codproducto: number,
almacen: string,
cantidad: number,
cantmin: number,
cantp1: number,
cantp2: number,
categoria: string,
codbarra: string,
color: string,
detalles: string,
estado: number,
fechavenc: string,
iddistrib: number,
laboratorio: string,
lote: string,
marca: string,
precioco: number,
preciove: number,
prep1: number,
prep2: number,
producto: string,
promo1: string,
promo2: string,
ptjganancia: number,
unimedida: string
) {
this.codproducto = codproducto;
this.almacen = almacen;
this.cantidad = cantidad;
this.cantmin = cantmin;
this.cantp1 = cantp1;
this.cantp2 = cantp2;
this.categoria = categoria;
this.codbarra = codbarra;
this.color = color;
this.detalles = detalles;
this.estado = estado;
this.fechavenc = fechavenc;
this.iddistrib = iddistrib;
this.laboratorio = laboratorio;
this.lote = lote;
this.marca = marca;
this.precioco = precioco;
this.preciove = preciove;
this.prep1 = prep1;
this.prep2 = prep2;
this.producto = producto;
this.promo1 = promo1;
this.promo2 = promo2;
this.ptjganancia = ptjganancia;
this.unimedida = unimedida;
}
}
| 23.97561 | 35 | 0.671414 | 80 | 1 | 0 | 25 | 0 | 25 | 0 | 0 | 50 | 1 | 0 | 25 | 607 | 0.042834 | 0 | 0.041186 | 0.001647 | 0 | 0 | 0.980392 | 0.271762 | export class Producto {
public codproducto;
public almacen;
public cantidad;
public cantmin;
public cantp1;
public cantp2;
public categoria;
public codbarra;
public color;
public detalles;
public estado;
public fechavenc;
public iddistrib;
public laboratorio;
public lote;
public marca;
public precioco;
public preciove;
public prep1;
public prep2;
public producto;
public promo1;
public promo2;
public ptjganancia;
public unimedida;
constructor(
codproducto,
almacen,
cantidad,
cantmin,
cantp1,
cantp2,
categoria,
codbarra,
color,
detalles,
estado,
fechavenc,
iddistrib,
laboratorio,
lote,
marca,
precioco,
preciove,
prep1,
prep2,
producto,
promo1,
promo2,
ptjganancia,
unimedida
) {
this.codproducto = codproducto;
this.almacen = almacen;
this.cantidad = cantidad;
this.cantmin = cantmin;
this.cantp1 = cantp1;
this.cantp2 = cantp2;
this.categoria = categoria;
this.codbarra = codbarra;
this.color = color;
this.detalles = detalles;
this.estado = estado;
this.fechavenc = fechavenc;
this.iddistrib = iddistrib;
this.laboratorio = laboratorio;
this.lote = lote;
this.marca = marca;
this.precioco = precioco;
this.preciove = preciove;
this.prep1 = prep1;
this.prep2 = prep2;
this.producto = producto;
this.promo1 = promo1;
this.promo2 = promo2;
this.ptjganancia = ptjganancia;
this.unimedida = unimedida;
}
}
|
146dde2a193738de7b016ad0b95997743933de22 | 2,083 | ts | TypeScript | problemset/sum-of-subarray-ranges/index.ts | OUDUIDUI/leet-code | 50e61ce16d1c419ccefc075ae9ead721cdd1cdbb | [
"MIT"
] | 6 | 2022-01-17T03:19:56.000Z | 2022-01-17T05:45:39.000Z | problemset/sum-of-subarray-ranges/index.ts | OUDUIDUI/leet-code | 50e61ce16d1c419ccefc075ae9ead721cdd1cdbb | [
"MIT"
] | null | null | null | problemset/sum-of-subarray-ranges/index.ts | OUDUIDUI/leet-code | 50e61ce16d1c419ccefc075ae9ead721cdd1cdbb | [
"MIT"
] | null | null | null | /**
* 遍历
* @desc 时间复杂度 O(N^1) 空间复杂度 O(1)
* @param nums
*/
export function subArrayRanges(nums: number[]): number {
const len = nums.length
if (len === 1) return 0
let result = 0
for (let i = 0; i < len; i++) {
let max = nums[i]
let min = nums[i]
for (let j = i + 1; j < len; j++) {
max = Math.max(max, nums[j])
min = Math.min(min, nums[j])
result += max - min
}
}
return result
}
/**
* 单调栈
* @desc 时间复杂度 O(N^1) 空间复杂度 O(1)
* @param nums
*/
export function subArrayRanges2(nums: number[]): number {
const len = nums.length
if (len === 1) return 0
const minLeft = new Array(len).fill(0)
const minRight = new Array(len).fill(0)
const maxLeft = new Array(len).fill(0)
const maxRight = new Array(len).fill(0)
const minStack: number[] = []
const maxStack: number[] = []
// 从左到右遍历,找到[0, i]区间的最大值和最小值
for (let i = 0; i < len; i++) {
while (minStack.length && nums[minStack[minStack.length - 1]] > nums[i])
minStack.pop()
minLeft[i] = minStack.length ? minStack[minStack.length - 1] : -1
minStack.push(i)
while (maxStack.length && nums[maxStack[maxStack.length - 1]] <= nums[i])
maxStack.pop()
maxLeft[i] = maxStack.length === 0 ? -1 : maxStack[maxStack.length - 1]
maxStack.push(i)
}
// 清空栈
minStack.length = 0
maxStack.length = 0
// 从右到左遍历,找到[i, len - 1]区间的最大值和最小值
for (let i = len - 1; i >= 0; i--) {
while (minStack.length && nums[minStack[minStack.length - 1]] >= nums[i])
minStack.pop()
minRight[i] = minStack.length === 0 ? len : minStack[minStack.length - 1]
minStack.push(i)
while (maxStack.length && nums[maxStack[maxStack.length - 1]] < nums[i])
maxStack.pop()
maxRight[i] = maxStack.length === 0 ? len : maxStack[maxStack.length - 1]
maxStack.push(i)
}
let sumMax = 0 // 所有子数组的最大值之和
let sumMin = 0 // 所以子数组的最小值之和
for (let i = 0; i < len; i++) {
sumMax += (maxRight[i] - i) * (i - maxLeft[i]) * nums[i]
sumMin += (minRight[i] - i) * (i - minLeft[i]) * nums[i]
}
return sumMax - sumMin
}
| 25.096386 | 77 | 0.581853 | 54 | 2 | 0 | 2 | 18 | 0 | 0 | 0 | 6 | 0 | 0 | 25 | 810 | 0.004938 | 0.022222 | 0 | 0 | 0 | 0 | 0.272727 | 0.253923 | /**
* 遍历
* @desc 时间复杂度 O(N^1) 空间复杂度 O(1)
* @param nums
*/
export function subArrayRanges(nums) {
const len = nums.length
if (len === 1) return 0
let result = 0
for (let i = 0; i < len; i++) {
let max = nums[i]
let min = nums[i]
for (let j = i + 1; j < len; j++) {
max = Math.max(max, nums[j])
min = Math.min(min, nums[j])
result += max - min
}
}
return result
}
/**
* 单调栈
* @desc 时间复杂度 O(N^1) 空间复杂度 O(1)
* @param nums
*/
export function subArrayRanges2(nums) {
const len = nums.length
if (len === 1) return 0
const minLeft = new Array(len).fill(0)
const minRight = new Array(len).fill(0)
const maxLeft = new Array(len).fill(0)
const maxRight = new Array(len).fill(0)
const minStack = []
const maxStack = []
// 从左到右遍历,找到[0, i]区间的最大值和最小值
for (let i = 0; i < len; i++) {
while (minStack.length && nums[minStack[minStack.length - 1]] > nums[i])
minStack.pop()
minLeft[i] = minStack.length ? minStack[minStack.length - 1] : -1
minStack.push(i)
while (maxStack.length && nums[maxStack[maxStack.length - 1]] <= nums[i])
maxStack.pop()
maxLeft[i] = maxStack.length === 0 ? -1 : maxStack[maxStack.length - 1]
maxStack.push(i)
}
// 清空栈
minStack.length = 0
maxStack.length = 0
// 从右到左遍历,找到[i, len - 1]区间的最大值和最小值
for (let i = len - 1; i >= 0; i--) {
while (minStack.length && nums[minStack[minStack.length - 1]] >= nums[i])
minStack.pop()
minRight[i] = minStack.length === 0 ? len : minStack[minStack.length - 1]
minStack.push(i)
while (maxStack.length && nums[maxStack[maxStack.length - 1]] < nums[i])
maxStack.pop()
maxRight[i] = maxStack.length === 0 ? len : maxStack[maxStack.length - 1]
maxStack.push(i)
}
let sumMax = 0 // 所有子数组的最大值之和
let sumMin = 0 // 所以子数组的最小值之和
for (let i = 0; i < len; i++) {
sumMax += (maxRight[i] - i) * (i - maxLeft[i]) * nums[i]
sumMin += (minRight[i] - i) * (i - minLeft[i]) * nums[i]
}
return sumMax - sumMin
}
|
2334bf07360f589cf45569456b9aac2445aa3214 | 1,470 | ts | TypeScript | .storybook/main.ts | NSpencer4/monorepo-poc | d6a805b7212bcbc5f803f03e7832c8bb01ec5e00 | [
"MIT"
] | null | null | null | .storybook/main.ts | NSpencer4/monorepo-poc | d6a805b7212bcbc5f803f03e7832c8bb01ec5e00 | [
"MIT"
] | 3 | 2022-01-22T07:03:18.000Z | 2022-03-30T21:55:21.000Z | .storybook/main.ts | NSpencer4/monorepo-poc | d6a805b7212bcbc5f803f03e7832c8bb01ec5e00 | [
"MIT"
] | null | null | null | // @ts-ignore
module.exports = {
typescript: {
check: false,
checkOptions: {},
reactDocgen: 'react-docgen-typescript',
reactDocgenTypescriptOptions: {
shouldExtractLiteralValuesFromEnum: true,
propFilter: (prop) => (prop.parent ? !/node_modules/.test(prop.parent.fileName) : true),
},
},
stories: [
'../packages/**/*.stories.@(ts|tsx|mdx)'
],
addons: [
'@storybook/addon-a11y',
'@storybook/addon-jest',
'@storybook/addon-essentials',
'storybook-addon-themes',
'@storybook/preset-scss',
],
// @ts-ignore
webpackFinal: async (config, { configType }) => {
config.optimization = {
minimize: true,
runtimeChunk: {
name: (entrypoint) => `runtime~${entrypoint.name}`,
},
splitChunks: {
chunks: 'all',
minSize: 30 * 1024,
maxSize: 1024 * 1024,
maxInitialRequests: 30,
minChunks: 1,
maxAsyncRequests: 30,
enforceSizeThreshold: 50000,
cacheGroups: {
defaultVendors: {
test: /[\\/]node_modules[\\/]/,
priority: -10,
reuseExistingChunk: true,
},
default: {
minChunks: 2,
priority: -20,
reuseExistingChunk: true
}
},
}
};
config.devtool = configType === 'PRODUCTION' ? 'source-map' : 'eval';
config.resolve.extensions.push('.ts', '.tsx', '.mdx');
return config;
}
};
| 26.25 | 94 | 0.545578 | 53 | 3 | 0 | 4 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 10.666667 | 418 | 0.016746 | 0 | 0 | 0 | 0 | 0 | 0 | 0.209223 | // @ts-ignore
module.exports = {
typescript: {
check: false,
checkOptions: {},
reactDocgen: 'react-docgen-typescript',
reactDocgenTypescriptOptions: {
shouldExtractLiteralValuesFromEnum: true,
propFilter: (prop) => (prop.parent ? !/node_modules/.test(prop.parent.fileName) : true),
},
},
stories: [
'../packages/**/*.stories.@(ts|tsx|mdx)'
],
addons: [
'@storybook/addon-a11y',
'@storybook/addon-jest',
'@storybook/addon-essentials',
'storybook-addon-themes',
'@storybook/preset-scss',
],
// @ts-ignore
webpackFinal: async (config, { configType }) => {
config.optimization = {
minimize: true,
runtimeChunk: {
name: (entrypoint) => `runtime~${entrypoint.name}`,
},
splitChunks: {
chunks: 'all',
minSize: 30 * 1024,
maxSize: 1024 * 1024,
maxInitialRequests: 30,
minChunks: 1,
maxAsyncRequests: 30,
enforceSizeThreshold: 50000,
cacheGroups: {
defaultVendors: {
test: /[\\/]node_modules[\\/]/,
priority: -10,
reuseExistingChunk: true,
},
default: {
minChunks: 2,
priority: -20,
reuseExistingChunk: true
}
},
}
};
config.devtool = configType === 'PRODUCTION' ? 'source-map' : 'eval';
config.resolve.extensions.push('.ts', '.tsx', '.mdx');
return config;
}
};
|
236077f82b7ce40b3319ad46b81561f448daaf6d | 2,738 | ts | TypeScript | src/helpers/utils.ts | lettucebowler/stencildoku | bcb9cfdc0f48ca883bbc8b49608b8f19eb1d9828 | [
"MIT"
] | 1 | 2022-03-13T10:26:48.000Z | 2022-03-13T10:26:48.000Z | src/helpers/utils.ts | lettucebowler/stencildoku | bcb9cfdc0f48ca883bbc8b49608b8f19eb1d9828 | [
"MIT"
] | null | null | null | src/helpers/utils.ts | lettucebowler/stencildoku | bcb9cfdc0f48ca883bbc8b49608b8f19eb1d9828 | [
"MIT"
] | null | null | null |
export function cellLegal(board: number[], row: number, col: number, order: number): boolean {
const index = getIndex(row, col, order);
const num = board[index];
if (num === 0) {
return true;
}
let count = 0;
// Check rows/columns
for (let i = 0; i < order * order; i++) {
if (board[getIndex(i, col, order)] === num) {
count++;
}
if (board[getIndex(row, i, order)] === num) {
count++;
}
}
// Check block
const startRow = Math.floor(row / order) * order;
const startCol = Math.floor(col / order) * order;
for (let i = 0; i < order; i++) {
for (let j = 0; j < order; j++) {
const index = getIndex(startRow + i, startCol + j, order);
if (board[index] === num) {
count++;
}
}
}
return count === 3;
}
export function isInitialHint(board: number[], row: number, col: number, order: number): boolean {
return board[getIndex(row, col, order)] !== 0;
}
export function boardSuccess(board: number[], order: number): boolean {
for (let i = 0; i < order * order; i++) {
for (let j = 0; j < order * order; j++) {
if (!rowGood(board, i, order)) {
return false;
}
if (!colGood(board, j, order)) {
return false;
}
if (i < order && j < order) {
if (!blockGood(board, i, j, order)) {
return false;
}
}
}
}
return true;
}
export function getIndex(row: number, col: number, order: number): number {
return row * (order * order) + col;
}
const rowGood = (board: number[], row: number, order: number): boolean => {
const rowSet = new Set();
for (let i = 0; i < order * order; i++) {
const index = getIndex(row, i, order);
const num = board[index];
if (num !== 0) {
rowSet.add(num);
}
}
return rowSet.size === order * order;
}
const colGood = (board: number[], col: number, order: number): boolean => {
const colSet = new Set();
for (let i = 0; i < order * order; i++) {
const index = getIndex(i, col, order);
const num = board[index];
if (num !== 0) {
colSet.add(num);
}
}
return colSet.size === order * order;
}
const blockGood = (board: number[], lane: number, trunk: number, order: number): boolean => {
const blockSet = new Set();
for (let i = lane * order; i < lane * order + order; i++) {
for (let j = trunk * order; j < trunk * order + order; j++) {
const index = getIndex(i, j, order);
const num = board[index];
if (num !== 0) {
blockSet.add(num);
}
}
}
return blockSet.size === order * order;
} | 28.520833 | 98 | 0.517166 | 86 | 7 | 0 | 23 | 27 | 0 | 4 | 0 | 30 | 0 | 0 | 10.285714 | 802 | 0.037406 | 0.033666 | 0 | 0 | 0 | 0 | 0.526316 | 0.367957 |
export function cellLegal(board, row, col, order) {
const index = getIndex(row, col, order);
const num = board[index];
if (num === 0) {
return true;
}
let count = 0;
// Check rows/columns
for (let i = 0; i < order * order; i++) {
if (board[getIndex(i, col, order)] === num) {
count++;
}
if (board[getIndex(row, i, order)] === num) {
count++;
}
}
// Check block
const startRow = Math.floor(row / order) * order;
const startCol = Math.floor(col / order) * order;
for (let i = 0; i < order; i++) {
for (let j = 0; j < order; j++) {
const index = getIndex(startRow + i, startCol + j, order);
if (board[index] === num) {
count++;
}
}
}
return count === 3;
}
export function isInitialHint(board, row, col, order) {
return board[getIndex(row, col, order)] !== 0;
}
export function boardSuccess(board, order) {
for (let i = 0; i < order * order; i++) {
for (let j = 0; j < order * order; j++) {
if (!rowGood(board, i, order)) {
return false;
}
if (!colGood(board, j, order)) {
return false;
}
if (i < order && j < order) {
if (!blockGood(board, i, j, order)) {
return false;
}
}
}
}
return true;
}
export /* Example usages of 'getIndex' are shown below:
getIndex(row, col, order);
board[getIndex(i, col, order)] === num;
board[getIndex(row, i, order)] === num;
getIndex(startRow + i, startCol + j, order);
board[getIndex(row, col, order)] !== 0;
getIndex(row, i, order);
getIndex(i, col, order);
getIndex(i, j, order);
*/
function getIndex(row, col, order) {
return row * (order * order) + col;
}
/* Example usages of 'rowGood' are shown below:
!rowGood(board, i, order);
*/
const rowGood = (board, row, order) => {
const rowSet = new Set();
for (let i = 0; i < order * order; i++) {
const index = getIndex(row, i, order);
const num = board[index];
if (num !== 0) {
rowSet.add(num);
}
}
return rowSet.size === order * order;
}
/* Example usages of 'colGood' are shown below:
!colGood(board, j, order);
*/
const colGood = (board, col, order) => {
const colSet = new Set();
for (let i = 0; i < order * order; i++) {
const index = getIndex(i, col, order);
const num = board[index];
if (num !== 0) {
colSet.add(num);
}
}
return colSet.size === order * order;
}
/* Example usages of 'blockGood' are shown below:
!blockGood(board, i, j, order);
*/
const blockGood = (board, lane, trunk, order) => {
const blockSet = new Set();
for (let i = lane * order; i < lane * order + order; i++) {
for (let j = trunk * order; j < trunk * order + order; j++) {
const index = getIndex(i, j, order);
const num = board[index];
if (num !== 0) {
blockSet.add(num);
}
}
}
return blockSet.size === order * order;
} |