StenoType
Collection
Collection of models and datasets for TypeScript-related projects from Ming-Ho Yee's dissertation (https://doi.org/10.17760/D20653005).
•
9 items
•
Updated
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++;
}
}
|